Compare commits

..

62 Commits
envfs ... xray

Author SHA1 Message Date
chn
f7e2d0d52c services.xray.dae: use default package 2024-04-10 20:15:16 +08:00
chn
473279d295 Revert "move devices into modules"
This reverts commit cfb1e3e727.
2024-04-09 20:52:26 +08:00
chn
cfb1e3e727 move devices into modules 2024-04-09 20:51:25 +08:00
chn
bab71d6f90 user.chn.plasma.wallpaper: update surface wallpaper 2024-04-09 20:47:14 +08:00
chn
abe81f230c Revert "devices.pc: switch to nvidia"
This reverts commit 7fb18889e0.
2024-04-09 19:24:01 +08:00
chn
7fb18889e0 devices.pc: switch to nvidia 2024-04-09 19:06:14 +08:00
chn
d45e033314 services.misskey: remove meilisearch support 2024-04-08 21:31:11 +08:00
chn
8232e3c794 devices.surface: add suspend-hibernate-no-platform bug 2024-04-08 21:30:18 +08:00
chn
d12e234e71 user.chn.plasma.wallpaper: add wallpaper 2024-04-08 00:46:30 +08:00
chn
6ab9fe88ca users.chn.plasma.wallpaper: set different wallpapers 2024-04-07 23:51:36 +08:00
chn
dff2d50f26 add wallpaper 2024-04-07 20:51:48 +08:00
chn
55bf66957c services.chatgpt: init 2024-04-06 22:38:03 +08:00
chn
0cf1c8f7d2 add note 2024-04-06 19:19:19 +08:00
chn
4d28aa50c7 add build, .vscode, .cache to .gitignore 2024-04-03 19:48:46 +08:00
chn
bca081020b Revert "localPackages.vasp: remove additionalCommands"
This reverts commit 4de795bd59.
2024-04-03 19:47:52 +08:00
chn
379dcd7ba9 localPackages.biu: fix 2024-04-03 19:47:29 +08:00
chn
c7aa418408 devices.pcarm: init 2024-04-03 13:50:08 +08:00
chn
ce8086a800 localPackages.biu: add some conversion 2024-04-03 12:17:02 +08:00
chn
4de795bd59 localPackages.vasp: remove additionalCommands 2024-04-03 11:42:21 +08:00
chn
4e7ae53b3d localPackages.biu: merge repo 2024-04-02 11:08:47 +08:00
chn
3087681a19 packages: remove compiler & library 2024-04-02 10:40:03 +08:00
chn
2bdc5b94bc packages.server: add biu 2024-04-01 19:07:36 +08:00
chn
562e51a866 fix overlay 2024-04-01 18:55:33 +08:00
chn
30c7efb426 packages.server: add concurrencpp 2024-04-01 17:27:55 +08:00
chn
aa278b51a8 devices.pc: add suspend-hibernate-no-platform 2024-03-31 19:49:05 +08:00
chn
392433de5a services.sshd: add groupBanner 2024-03-31 15:29:07 +08:00
chn
bc368617b9 packages.server: add lolcat 2024-03-31 12:21:07 +08:00
chn
986dee8d7a packages.server: add toilet 2024-03-31 12:05:41 +08:00
chn
83af1576f1 localPackages.kylin-virtual-keyboard: init 2024-03-31 12:04:10 +08:00
chn
6940dbaf85 Revert "update aagl"
This reverts commit 9f921d8735.
2024-03-29 18:52:33 +08:00
chn
9f921d8735 update aagl 2024-03-29 18:40:27 +08:00
chn
4893999021 packages: add eigen 2024-03-29 18:24:17 +08:00
chn
016b1e179a packages: add highfive 2024-03-29 13:40:18 +08:00
chn
d51cae120d fix 2024-03-28 21:51:11 +08:00
chn
bb9225f236 devices.pi3b: fix 2024-03-28 21:40:16 +08:00
chn
5e7867a76c devices.vps6: add pi3b to wireguard peers 2024-03-28 21:38:26 +08:00
chn
400fc0ae03 devices.pi3b: regenerate secrets 2024-03-28 21:32:24 +08:00
chn
1d8366517a devices.pi3b: use default kernel 2024-03-28 20:53:17 +08:00
chn
db812b2ab7 devices.pi3b: enable ssh and wireguard 2024-03-28 18:35:45 +08:00
chn
bb6b65c4d2 services.xray: explicitly set wanInterface 2024-03-28 10:46:05 +08:00
chn
ff6d0d4af7 packages: add matplotplusplus 2024-03-27 19:59:05 +08:00
chn
b04b1375d0 system.sysctl: 整理 2024-03-27 18:47:56 +08:00
chn
53a2a6ff0c system.systemd: 整理 2024-03-27 18:46:45 +08:00
chn
bf3eee7931 system.sops: move default secret file 2024-03-27 18:43:09 +08:00
chn
56d93beb06 devices.vps6: add xray user 2024-03-27 18:31:29 +08:00
chn
707d068b18 packages: add some libraries 2024-03-26 18:18:54 +08:00
chn
b5fdd69ebd virtualization: fix 2024-03-26 13:49:33 +08:00
chn
f05e34c864 virtualization: fix aarch efi 2024-03-25 19:58:34 +08:00
chn
781da3b465 devices.pi3b: finalize 2024-03-25 18:03:27 +08:00
chn
615d2a4867 devices.rpi3: fix 2024-03-25 17:49:35 +08:00
chn
e69dd36cc3 packages: fix build for aarch64 2024-03-25 17:12:58 +08:00
chn
e7a5fe6190 hardware: fix for aarch64 2024-03-25 17:09:29 +08:00
chn
b8c4e79183 devices.pi3b: fix build 2024-03-25 17:07:54 +08:00
chn
9b1ec2d09c devices.pi3b: init 2024-03-25 16:55:13 +08:00
chn
b2666d1fdf system: only enable envfs and nix-ld on workstation 2024-03-25 14:59:37 +08:00
chn
b3f264a4b6 localPackages.vasp: fix 2024-03-25 14:19:58 +08:00
chn
21614c3b07 devices.pc: enable snapper 2024-03-25 12:57:25 +08:00
chn
6ccdafbdc4 system.nix-ld: init 2024-03-25 12:06:55 +08:00
chn
b8b93e2b85 devices.xmupc2: 整理 2024-03-25 11:44:04 +08:00
chn
5e648574fb hardware.legion: fix 2024-03-25 11:40:13 +08:00
chn
3d08a3b498 hardware: 整理 2024-03-25 11:37:21 +08:00
chn
ff4bbd4b48 localLib.findModules: include mkModules 2024-03-25 11:30:50 +08:00
90 changed files with 2353 additions and 361 deletions

3
.clangd Normal file
View File

@@ -0,0 +1,3 @@
CompileFlags:
Add: [ -Wall, -Wextra, -std=c++23 ]
Compiler: gcc

1
.envrc Normal file
View File

@@ -0,0 +1 @@
use flake

2
.gitattributes vendored
View File

@@ -1,2 +1,4 @@
*.png filter=lfs diff=lfs merge=lfs -text
*.icm filter=lfs diff=lfs merge=lfs -text
*.jpg filter=lfs diff=lfs merge=lfs -text
*.webp filter=lfs diff=lfs merge=lfs -text

4
.gitignore vendored
View File

@@ -1,3 +1,7 @@
result
result-man
outputs
.direnv
build
.vscode
.cache

View File

@@ -7,39 +7,45 @@ keys: # cat /etc/ssh/ssh_host_ed25519_key.pub | ssh-to-age
- &nas age19lhcwk37jmvn6z0v4dpdfh0k4u23f76twdjknc0p7atktf37rd7s4t4wj3
- &xmupc1 age1hnarptkze0ujpp05dqr8uma04cxg9zqcx68qgpks5uf5l6rpk5gqhh8wxg
- &xmupc2 age1l4stuz0vr7gs7pqwjrmezam44702jp2vmqaqyxw0l0r42kf9updq4dfhrw
- &pi3b age1yjgswvexp0x0de0sw4u6hamruzeluxccmx2enxazl6pwhhsr2s9qlxdemq
creation_rules:
- path_regex: devices/pc/secrets/.*$
- path_regex: devices/pc/.*$
key_groups:
- age:
- *chn
- *pc
- path_regex: devices/vps6/secrets/.*$
- path_regex: devices/vps6/.*$
key_groups:
- age:
- *chn
- *vps6
- path_regex: devices/vps7/secrets/.*$
- path_regex: devices/vps7/.*$
key_groups:
- age:
- *chn
- *vps7
- path_regex: devices/nas/secrets/.*$
- path_regex: devices/nas/.*$
key_groups:
- age:
- *chn
- *nas
- path_regex: devices/surface/secrets/.*$
- path_regex: devices/surface/.*$
key_groups:
- age:
- *chn
- *surface
- path_regex: devices/xmupc1/secrets/.*$
- path_regex: devices/xmupc1/.*$
key_groups:
- age:
- *chn
- *xmupc1
- path_regex: devices/xmupc2/secrets/.*$
- path_regex: devices/xmupc2/.*$
key_groups:
- age:
- *chn
- *xmupc2
- path_regex: devices/pi3b/.*$
key_groups:
- age:
- *chn
- *pi3b

View File

@@ -59,8 +59,8 @@ inputs:
hostsAllowed = "192.168. 127.";
shares = { home.path = "/home"; root.path = "/"; };
};
sshd.enable = true;
xray.client = {};
sshd = {};
xray.client.dae.wanInterface = [ "enp3s0" ];
xrdp = { enable = true; hostname = [ "nas.chn.moe" "office.chn.moe" ]; };
groupshare = {};
smartd.enable = true;

View File

@@ -62,11 +62,7 @@ inputs:
{
cpus = [ "amd" ];
gpu = { type = "amd+nvidia"; prime.busId = { amd = "8:0:0"; nvidia = "1:0:0"; }; dynamicBoost = true; };
bluetooth.enable = true;
joystick.enable = true;
printer.enable = true;
sound.enable = true;
legion.enable = true;
legion = {};
};
packages.packageSet = "workstation";
virtualization =
@@ -78,7 +74,7 @@ inputs:
};
services =
{
# snapper.enable = true;
snapper.enable = true;
fontconfig.enable = true;
samba =
{
@@ -93,10 +89,14 @@ inputs:
share.path = "/home/chn/share";
};
};
sshd.enable = true;
xray.client.dnsmasq.hosts = builtins.listToAttrs (builtins.map
(name: { inherit name; value = "74.211.99.69"; })
[ "mirism.one" "beta.mirism.one" "ng01.mirism.one" "initrd.vps6.chn.moe" ]);
sshd = {};
xray.client =
{
dnsmasq.hosts = builtins.listToAttrs (builtins.map
(name: { inherit name; value = "74.211.99.69"; })
[ "mirism.one" "beta.mirism.one" "ng01.mirism.one" "initrd.vps6.chn.moe" ]);
dae.wanInterface = [ "wlp4s0" "enp5s0" ];
};
firewall.trustedInterfaces = [ "virbr0" "waydroid0" ];
acme.cert."debug.mirism.one" = {};
frpClient =
@@ -125,7 +125,7 @@ inputs:
hostname = [ "pc.chn.moe" ];
};
};
bugs = [ "xmunet" "backlight" "amdpstate" ];
bugs = [ "xmunet" "backlight" "amdpstate" "suspend-hibernate-no-platform" ];
};
networking.extraHosts = "74.211.99.69 mirism.one beta.mirism.one ng01.mirism.one";
services.colord.enable = true;

View File

@@ -14,8 +14,6 @@ postgresql:
misskey_misskey: ENC[AES256_GCM,data:MSDbQffk/WjZ6EYiwVuUMdhdv9VE59ZM7t4XldOKRO0=,iv:J/x9t4Pk5zi7Av9fbzxgAbbtbEUZttSx/JGRmmgmvE4=,tag:CwFR9K++T7YqYR932z3IAg==,type:str]
redis:
misskey-misskey: ENC[AES256_GCM,data:vcvQ/hs/F3BZd1sfvWwfEeB8vVoqdnprxobcmL6xsmg=,iv:S32yrjrjj56HbxTlfFGjOb+sO2M9KKEDEazCrpQWj6Q=,tag:iwnvqwQEdd6jicx9jJBdbg==,type:str]
meilisearch:
misskey-misskey: ENC[AES256_GCM,data:/wYR3Bz4LRk/Ks0vizlZS3Ebf5qVfnlBBqZEm/ZIBFdDuhddgu71cqCjTHIKQ6CYh3CoUyguKIIFWku/kOCHKA==,iv:dllKvZwxvZC4pVyEMOB9WNiVBsVxzo5kwbdYKCzzyrY=,tag:MvzqalVvBkyJoLbirN0V8Q==,type:str]
wireguard:
privateKey: ENC[AES256_GCM,data:oIpiXJvEoyryS4eEutoe85Af0L5a5iNuOsCWCat9KEhr2ecY/vRimk/1fbA=,iv:dm2hTSNX7Q38yASon5o1jxEJZbWPXUWYydXYMBHF/sE=,tag:yrANhwIF/wHQGHGA1bfPgw==,type:str]
mariadb:
@@ -46,8 +44,8 @@ sops:
OUlxNjdQaXdXMkZ6bnV1ek4yZ2dpbkEKpKGOAxo5Eef2jtGrg4iSzmGCeg+vTgvu
+K8b+O19MIkGMDBm6UbYUPtc/7eqoEZRiTUzNMTmfkLVS4ul5zou9A==
-----END AGE ENCRYPTED FILE-----
lastmodified: "2024-03-11T08:27:38Z"
mac: ENC[AES256_GCM,data:X5AqIdnMzLNCHXbN3TuG4st907Rw080V8AqzesiwVFOjbBYRZWetCndtfE+/o8G1q5YE/Qwspy7HsxP5tCbSNI5c8P0XTjRTCEGyRFY8fM1TFIM32rCFjUot1iFC+l//iq62M/5iMhT2Z7pi+CDIyNMEE3TJMhBc8JmgTJXIsI8=,iv:UZXFi3rJgVHBNVqwNHlIkmW+xYkX6X2/54QQ1aZTmyU=,tag:SXyL69DZ5i0cQFvXnFkZIg==,type:str]
lastmodified: "2024-04-08T08:13:10Z"
mac: ENC[AES256_GCM,data:44e5uZrJ25aRlrSUlbakyWpqhloyGBjJhHXCJBVBJKi0OKn+QPluS0exBvNhTERhFmGk9qHwiIvjbAbplpg+83/IIcXd3NGxekEhwSAXS5Z+AMGIJ4AMet1SSwP6n8fOiI52hCFFRNJj66MyqKXFrNNye4/DF5Bh0dvXQDQbjSQ=,iv:PHpQ/bGrjrBWCj74kKevBlAV08+SAfV9bXJ7hC4lVYc=,tag:ATLe+m8oYKR0im86UekPAA==,type:str]
pgp: []
unencrypted_suffix: _unencrypted
version: 3.8.1

29
devices/pcarm/default.nix Normal file
View File

@@ -0,0 +1,29 @@
inputs:
{
config =
{
nixos =
{
system =
{
fileSystems =
{
mount =
{
vfat."/dev/disk/by-uuid/CE84-E0D8" = "/boot/efi";
btrfs."/dev/disk/by-uuid/61f51d93-d3e5-4028-a903-332fafbfd365" =
{ "/nix/rootfs/current" = "/"; "/nix" = "/nix"; "/nix/boot" = "/boot"; };
};
rollingRootfs = {};
};
grub.installDevice = "efi";
networking = { hostname = "pcarm"; networkd = {}; };
binfmt.enable = false;
nixpkgs.arch = "aarch64";
kernel.varient = "nixos";
};
packages.packageSet = "server";
services.sshd = {};
};
};
}

44
devices/pi3b/default.nix Normal file
View File

@@ -0,0 +1,44 @@
inputs:
{
config =
{
nixos =
{
system =
{
fileSystems =
{
mount =
{
vfat."/dev/disk/by-uuid/ABC6-6B3E" = "/boot/efi";
btrfs."/dev/disk/by-uuid/c459c6c0-23a6-4ef2-945a-0bfafa9a45b6" =
{ "/nix/rootfs/current" = "/"; "/nix" = "/nix"; "/nix/boot" = "/boot"; };
};
swap = [ "/nix/swap/swap" ];
rollingRootfs = {};
};
grub.installDevice = "efi";
networking = { hostname = "pi3b"; networkd = {}; };
binfmt.enable = false;
nixpkgs.arch = "aarch64";
kernel.varient = "nixos";
};
packages.packageSet = "server";
services =
{
# snapper.enable = true;
sshd = {};
xray.client.dae.wanInterface = [ "enu1u1" ];
fail2ban = {};
wireguard =
{
enable = true;
peers = [ "vps6" ];
publicKey = "X5SwWQk3JDT8BDxd04PYXTJi5E20mZKP6PplQ+GDnhI=";
wireguardIp = "192.168.83.8";
};
beesd.instances.root = { device = "/"; hashTableSizeMB = 32; };
};
};
};
}

33
devices/pi3b/secrets.yaml Normal file
View File

@@ -0,0 +1,33 @@
xray-client:
uuid: ENC[AES256_GCM,data:82Xg9VkmkLrKKcZfojA7dHqqMZh45n+eL4T5qZ1z/xy9k0q5,iv:/2j9flBDwjY6JW2mHYo1S2VE+ruu6gxrw8BzSyoiPcc=,tag:iq8wzfIRyq1T18k3vStVGw==,type:str]
wireguard:
privateKey: ENC[AES256_GCM,data:8whySpY/4WPWx2+t7IOgn+qjKCsv+BgRtaAFLrP8L0fV3TJdLob5vwDplHk=,iv:kXTDwOyJNzbjPtlzQqNsXtuk3EXFdF9CAsYkvImbyDE=,tag:tsK9nCMmwEb0c08rJ3Iwyg==,type:str]
sops:
kms: []
gcp_kms: []
azure_kv: []
hc_vault: []
age:
- recipient: age19ax6vm3pv8rph5tq3mmehd9sy9jk823tw8svsd790r0lkslycquqvlwz9m
enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSB6TzU0U2Facm5yWkYrREgw
a1Fxc1MxaHYwRWUzUHpsbDBHYVoxb1NKVDAwCjNuUFlabzJ0aWtGMFBQb05nSlRP
akwrWDI0QnZBYkFmSUpWZFFnYmQ2aDQKLS0tIGlIQ3lTREN4WXgxV3pNdjdaakF6
ZnppV1ZRZzZ5Smt2NGsyRndjTFdnV00KaWVPGLWPnqINH6AHKS/84kuYy/v1v4Tb
QdehcMiq5ZF5XLqOX5sMDLu8h96FIklqOSTZNFkzr+s9VYv/UO58rg==
-----END AGE ENCRYPTED FILE-----
- recipient: age1yjgswvexp0x0de0sw4u6hamruzeluxccmx2enxazl6pwhhsr2s9qlxdemq
enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSAyTEZERkRSZUdSN2dySnlI
aDFjdXFCWnlJZlpYQmR1WEE2RzdCaVp1WFEwCjd1N1ZpMUExZ0ZBWmFwSHg3RUs4
RkRYTjRMWmE5cTA4Z2JJUGgyN05HSmMKLS0tIFpKZmd2Q2k2bnNYK1V2ZnNQNUxH
aDU3Vm95ZkpvSTJDMjJEOFY1ZjhrQlUKLdMYiOj6tlzwLpwZsTQVSQ8hHart0ba3
NS7+SprzJRb0hQXrvyU6s9zho8dPOw8wiGbscmMXSVS/Kar3eQigmg==
-----END AGE ENCRYPTED FILE-----
lastmodified: "2024-03-28T13:31:33Z"
mac: ENC[AES256_GCM,data:fuppF9gFh3O6ZqJRTcVxNqVlz2y5f4xR39JIeInKblh4hNhrdnQg7oh8repoZeXHVRewGeGyxSqzUg+Twy8J+q+d6TSmiDVViD/SHse5rPns2Egt671geF7JmGEB/yKSCbECjGCp0QFgYYEg/vUOaV3v1a0s7LLTE/t2haPIaYc=,iv:f4T7JGxKB3WmEtETuSH7ApKRJ8ptPwZPfspyqc8+vmM=,tag:GF5br+e/p6qHsNCTjfIBCA==,type:str]
pgp: []
unencrypted_suffix: _unencrypted
version: 3.8.1

View File

@@ -34,23 +34,15 @@ inputs:
kernel.patches = [ "cjktty" "lantian" "surface" ];
networking.hostname = "surface";
};
hardware =
{
cpus = [ "intel" ];
gpu.type = "intel";
bluetooth.enable = true;
joystick.enable = true;
printer.enable = true;
sound.enable = true;
};
hardware = { cpus = [ "intel" ]; gpu.type = "intel"; };
packages.packageSet = "desktop-fat";
virtualization = { docker.enable = true; waydroid.enable = true; };
services =
{
snapper.enable = true;
fontconfig.enable = true;
sshd.enable = true;
xray.client = {};
sshd = {};
xray.client.dae.wanInterface = [ "wlp2s0" ];
firewall.trustedInterfaces = [ "virbr0" ];
wireguard =
{
@@ -61,7 +53,7 @@ inputs:
};
beesd.instances.root = { device = "/"; hashTableSizeMB = 512; };
};
bugs = [ "xmunet" ];
bugs = [ "xmunet" "suspend-hibernate-no-platform" ];
};
boot.kernelParams = [ "intel_iommu=off" ];
environment.systemPackages = with inputs.pkgs; [ maliit-keyboard maliit-framework ];

View File

@@ -35,8 +35,8 @@ inputs:
services =
{
snapper.enable = false;
sshd.enable = true;
xray.server = { serverName = "vps6.xserver.chn.moe"; userNumber = 13; };
sshd = {};
xray.server = { serverName = "vps6.xserver.chn.moe"; userNumber = 14; };
frpServer = { enable = true; serverName = "frp.chn.moe"; };
nginx =
{
@@ -71,7 +71,7 @@ inputs:
wireguard =
{
enable = true;
peers = [ "pc" "nas" "vps7" "surface" "xmupc1" "xmupc2" ];
peers = [ "pc" "nas" "vps7" "surface" "xmupc1" "xmupc2" "pi3b" ];
publicKey = "AVOsYUKQQCvo3ctst3vNi8XSVWo1Wh15066aHh+KpF4=";
wireguardIp = "192.168.83.1";
listenIp = "74.211.99.69";

View File

@@ -30,6 +30,10 @@ xray-server:
user11: ENC[AES256_GCM,data:BIZ2zRgGv5/9AexiZZvu+m4A62YUWtAkjWWMu89GteqpWMBq,iv:13IJcDf18LjoxJk7uoKnuFZT6Ihxrxsy7DBaAaiFqus=,tag:RN7wj+uPneCkqNlMRyYrXw==,type:str]
#ENC[AES256_GCM,data:spyQkQIHwg==,iv:7+0DUK95MPH7lpr+GMbbLu4/5yA11/4gTuLhQKlStfE=,tag:G/gIXML8UhYoCi9FfoTvSA==,type:comment]
user12: ENC[AES256_GCM,data:FAF9lXOzXW9CrZgnQ1a2+E8snZj2+JHqP5Gny92k09o/Wzga,iv:/qZuAtFmUQE7A9lMzJUoCvGx+3Sv9Ioh2ahch3puaC4=,tag:urwbLwGkSX3e85NCjyPhhg==,type:str]
#ENC[AES256_GCM,data:HueqiREBet2bxQ==,iv:WCjTAGg2gXgBSvY3zc/YyB/1X0XjvphPduVXLsjOwH8=,tag:wC+On6lyyYQ1Dt/BHDvONw==,type:comment]
user13: ENC[AES256_GCM,data:ExbnvWDIBqga5+k2mpoT8AKBOXAvUNMjBTPXUKrmtWzz4l+L,iv:UI7CvSx2FHYGf6BEHS4e3iwHZZWkl2Zt5xg2WdKbLvY=,tag:ad0c7YW2Bxo+Dn+BoSZ0Ng==,type:str]
#ENC[AES256_GCM,data:R8lN5T0=,iv:FXLf8Vtjg+PkwNhxXWDViMKqwn7tFMaPhio9zhnudZw=,tag:34gxRH+P9lmkUxlOPKcYMg==,type:comment]
user14: ENC[AES256_GCM,data:dgNPPlJD5JOFPbKhlvlRHBLmUNKeDm/JAiawUVpBE7H07Box,iv:w+t9BkqYvlxVKr+x0MwtBz0/YSR/7z1OnZLIoPdW4gc=,tag:CR3GLbaO0jSQgA2HuwzRqg==,type:str]
telegram:
token: ENC[AES256_GCM,data:xsJoGgQ8pLeZqA2alGKkCyrvnjY6rVF5TlXn4GWDrStFBl65XXzwVY/9ZZthYQ==,iv:qTLfpRUyuIGFM668URfknhSRtx3WEHp/WTGzGUPuFd4=,tag:p8mF0tM+t02g7v2EQZN3Vg==,type:str]
chat: ENC[AES256_GCM,data:X1JxFQw0bPCu,iv:hf+TOSH2p9RdnXDFKxTpSRzxDLdJyzNHVV8MfOQuGWY=,tag:iiWw9IFiBGOOyOSl9Jj2wQ==,type:str]
@@ -73,8 +77,8 @@ sops:
ZXFTU3ZCaW1pTVh0RUJzdDdGdHlPYTgK2mlgcX2kEc8+2UDdBnhUm6IIuh8V6agW
ooxH9OEPXUVI/4JcDo4v8ZUhAyU1ehLH0Ef7PJCChOZe2KZmWSNbhA==
-----END AGE ENCRYPTED FILE-----
lastmodified: "2024-03-14T15:01:58Z"
mac: ENC[AES256_GCM,data:hjG1VHHNTm7qt/f/t0VuziFPQKSv/1qYI2nvNrO7qeHywtEol1SbpaaF0kn8/8TOuZFfdrIECj4CrI2M1nWWEMF+1LBOI4ccBPDY/33tqg4B1ZX90GEdK0ZnaBn0/tEziu4i6wIKcPXQMnpftPrUXegQUKqMlnTTZKY2AGsPXoI=,iv:a+4+n31/3r+nhyAuL7o/lyd7NMA+e+AwfgHneNOFrx8=,tag:Ei8mQiI0+ZS8TWisc3NCDA==,type:str]
lastmodified: "2024-03-28T10:31:05Z"
mac: ENC[AES256_GCM,data:6Z+ltjbvQaYhDPoiCN7ajQeWcp6vj3TIcUXUm/r/tZU4mIOvfxA7hxW971b76bYPTeVwgp7ZB9qQy9emDHV9i+aSyJpTPKQHRRz5J+T+NJhTP/IL3R3VmG89ssC6NH8FSk0S487JkPd8tNz+G6bvwFCPRxRLNj1pXX0Dp6tgwIw=,iv:xLw2iX1ODAbJCTJ8fEvG7SdZ1GnGwADIckH8DibVM2Y=,tag:TTzlHdcyIQr/92ZHmViRXQ==,type:str]
pgp: []
unencrypted_suffix: _unencrypted
version: 3.8.1

View File

@@ -37,14 +37,11 @@ inputs:
{
snapper.enable = true;
fontconfig.enable = true;
sshd.enable = true;
sshd = {};
rsshub.enable = true;
wallabag.enable = true;
misskey.instances =
{
misskey.hostname = "xn--s8w913fdga.chn.moe";
misskey-old = { port = 9727; redis.port = 3546; meilisearch.enable = false; };
};
{ misskey.hostname = "xn--s8w913fdga.chn.moe"; misskey-old = { port = 9727; redis.port = 3546; }; };
synapse.instances =
{
synapse.matrixHostname = "synapse.chn.moe";
@@ -73,6 +70,7 @@ inputs:
listenIp = "95.111.228.40";
};
vikunja.enable = true;
chatgpt = {};
};
};
};

View File

@@ -4,6 +4,7 @@ nginx:
detectAuth:
chn: ENC[AES256_GCM,data:Gk0TTbnFcsvIgoDcen6B8w==,iv:kvyvygw9zDwaiTQ2vPFTHQex0EWDFg8M8U22AConQFM=,tag:ewAZ/nXxmTOhDAjW/A2OnA==,type:str]
led: ENC[AES256_GCM,data:Owax7cyp,iv:NCEKyicVCYZNgxJzlO90heUmwPjfXbZEcyXX09XQKI4=,tag:WMTCVMVCD9sJgAhRUsqvYg==,type:str]
chat: ENC[AES256_GCM,data:1HJiO1zU5SX4G56oWxv5zqGyUqnBWByrtSnQ01wvmZ7PmRkrV+DV6StMg5DtJR9HhkWYnbXlbnBHzP+poPUMag==,iv:sfwI62nwGSnsdj1RyADWgXvp5AY+9RQdtSooxbKFWTs=,tag:pN/LF0mo7RXWoIPPzzs8qw==,type:str]
maxmind-license: ENC[AES256_GCM,data:9aW4QR3K6S+eTqzIjVlNEwkG0wZ4u5jgRfe7CMwRlJlK4AmcS6c45Q==,iv:cPTN1K4Aag5sohGbCQUZHYTvcwAL7AhF+rrY3OvXGPs=,tag:d9GGUMHnfzRz9Cf2U+dBfw==,type:str]
redis:
rsshub: ENC[AES256_GCM,data:uPnZIjbnRRoWIHlWkZNZkMpIb3Ujnnpb+AisVSVGFv4sfDAuDlAjt39pRdnWkCXJPqtXjJzQ+FeT34cqxTf8Bg==,iv:/jcyAHkxByFnbkmCAYQwda2QRmhW7L/ICoLuCgsVLCI=,tag:M5Q+dh/Bn7FiNpqQGYus4Q==,type:str]
@@ -28,8 +29,6 @@ postgresql:
akkoma: ENC[AES256_GCM,data:6piRt7BbMBLVGdot+VyoJN3/S8DoPNTYHFh/1coHSLNmiA6kU/6sca4Bts1Up/Vu164oTsFAr1JsKx6tzNzAPg==,iv:qplA1GXHwzVrmjm7eagCk3PFa7DRdwaf+p7N1HLb6mw=,tag:W6WedSK3R1IgZVo/0Hr9vA==,type:str]
synapse_matrix: ENC[AES256_GCM,data:5j+TYJ3vYUqu6CdRDYAT558DsTWbX4Rh+HuukPog5HGXlhneL3RnxVeGBR9CV1rlCP1NY99Nm8roBG+BcyPYHQ==,iv:CboB6lzqxAE/8ZlzaTU3bxw94N6OAhrq8pZ0AfxQiUc=,tag:z6cM3ufgbMn5n5PzgqdRjw==,type:str]
vikunja: ENC[AES256_GCM,data:syb4NYBxL3DdmZmcC+em0klmm6bkkIL/DH/gnzShYRiaezRFskT+yay9govn++SpbuvkoCJq/GYAFxNL+hcVtw==,iv:TQUgdzYQ0gqsAmux9v3BAQFNzHnCTZ+X/OC0b9Bfya8=,tag:b1AsiAW5XzA3DzGdf8J03g==,type:str]
meilisearch:
misskey-misskey: ENC[AES256_GCM,data:4s+qqd6mmstioC0XmG/vA6ED9mzu1vRJVPFFalRiqnnsFy0dYEU87H+y12eOp/KDSLdTNvpp6Z6jCNvxnpDXzQ==,iv:x6L9OPu/dwVsD9pYb4dqavw9NesMbo7LB+rwz6veAR4=,tag:/BBqV2sHIgPas7XsZydh2g==,type:str]
rsshub:
pixiv-refreshtoken: ENC[AES256_GCM,data:EeSOTSAAh+1Dc8+a/AaPJ0aBK5DTa3pdS6DrIMQmRw/n0SRu2QoynIF76w==,iv:dnZxi8jM1I4w3C2duYielpP/8wOAdHDjcqDIrowM0dM=,tag:8irGvLEbRJHV9TB8Jibs9g==,type:str]
youtube-key: ENC[AES256_GCM,data:OEm/ynOUPUq7ZEVzL2jgs9d+utkLTIdNq0MHE0JDujb9ndAwyJJI,iv:RRae6Cg6GdDnXAQOdtBYmcA7ZNuu70VpIg2MEezBn5k=,tag:gX4ZG345cT3Jh3ovUxtLGw==,type:str]
@@ -106,6 +105,8 @@ wireguard:
privateKey: ENC[AES256_GCM,data:TS+toaJRgAvC78XVwTciXe2IG8++vaqXVCi/u/8Aej6qq1B9Cb6f20cp5K0=,iv:T/NkLvcYiWzIDG3jWtuhe/sH2GT4z5f0xdUGbSL901I=,tag:qN7YokFBj3Kbbx4ijHTRnw==,type:str]
vikunja:
jwtsecret: ENC[AES256_GCM,data:p6e22qPJzTGB21oWhSr8AA4bfrele9ZOHVtZ8BHgX21IhoKdm58coGtSX1CGXR7J6+1/74RdLY9K88nGrM1F1w==,iv:DGUO8rhf7Lg9dTqSmzlR/Jd2K4oUjO8w9E5bihwsykI=,tag:SpX6UI0QIju/tC1fIL9CCg==,type:str]
chatgpt:
key: ENC[AES256_GCM,data:bkLxKUqkjwpUeqeAZCaAgKiOse8QtZ0zOn9TQNA84+B3rxNiTFPisI8=,iv:Zd5dO5Sdt4HCvNZgS2K0FjJAzti6oE22vahYQl99TrI=,tag:E3o+X84tRsIEGU9Jfb85JQ==,type:str]
sops:
kms: []
gcp_kms: []
@@ -130,8 +131,8 @@ sops:
SnFHS1Z0SXUzTFdEd29KTy9DU3Y3R0UKfhh+rUmWDrf+UGjclP57dHipPLFoXSqy
HdelmfV6q4/c7ppx2E+oZw3VNgoZCsrxxzYZfwxHJiZb+5vkE0D8iA==
-----END AGE ENCRYPTED FILE-----
lastmodified: "2024-03-07T12:36:38Z"
mac: ENC[AES256_GCM,data:Pe1wXpemyIGckkldnOy7sWYTp/SlHT7ffNzJbeNwK9hSRGbpU9as7BQ8IenrHbO9U5QT7oij3PdzLk88ImVCbu0rZ8P6k6JbbrSEUSeN+9IRPnMDbIcpd+HQ+Ite4UjLwX7UxPuy0yRCYHiu2Fu2JpdWf+uL5bc/ZFnJ887+3lA=,iv:JmII0faZo+upukOJeCS7AbpCr2wKR5YjPX/W+kJnFUE=,tag:w5woNqrhJbZM38/RPWYmnw==,type:str]
lastmodified: "2024-04-08T08:12:57Z"
mac: ENC[AES256_GCM,data:o+T7o5Z/8JIoS/a3iqFe8CphZzwgQl3RlalGMFE9YEprLUuXLwL4IioU7Q1WKHTS+ih1Q1oCye/7363njewo+8PZq+BbJXOP+cSpoSUflsfyGymxgdQk2vo308TTvCXuHJobVqtxPd2QLUzvCpEXuatUWmxbmJNpSFO+kEvM3qU=,iv:YUUST05szM5BII4SaO8vRm7prS5L5MJJJuecRL5sLUM=,tag:K0NRXtDcn2poi5I7QCl50w==,type:str]
pgp: []
unencrypted_suffix: _unencrypted
version: 3.8.1

View File

@@ -52,23 +52,15 @@ inputs:
networking.hostname = "xmupc1";
nix.remote.slave.enable = true;
};
hardware =
{
cpus = [ "amd" ];
gpu.type = "nvidia";
bluetooth.enable = true;
joystick.enable = true;
printer.enable = true;
sound.enable = true;
};
hardware = { cpus = [ "amd" ]; gpu.type = "nvidia"; };
packages.packageSet = "workstation";
virtualization = { waydroid.enable = true; docker.enable = true; kvmHost = { enable = true; gui = true; }; };
services =
{
snapper.enable = true;
fontconfig.enable = true;
sshd = { enable = true; passwordAuthentication = true; };
xray.client = {};
sshd = { passwordAuthentication = true; groupBanner = true; };
xray.client.dae.wanInterface = [ "wlp57s0" ];
firewall.trustedInterfaces = [ "virbr0" "waydroid0" ];
smartd.enable = true;
beesd.instances =

View File

@@ -46,23 +46,15 @@ inputs:
networking.hostname = "xmupc2";
nix.remote.slave.enable = true;
};
hardware =
{
cpus = [ "intel" ];
gpu.type = "nvidia";
bluetooth.enable = true;
joystick.enable = true;
printer.enable = true;
sound.enable = true;
};
hardware = { cpus = [ "intel" ]; gpu.type = "nvidia"; };
packages.packageSet = "workstation";
virtualization = { waydroid.enable = true; docker.enable = true; kvmHost = { enable = true; gui = true; }; };
services =
{
snapper.enable = true;
fontconfig.enable = true;
sshd = { enable = true; passwordAuthentication = true; };
xray.client = {};
sshd = { passwordAuthentication = true; groupBanner = true; };
xray.client.dae.wanInterface = [ "wlp4s0" ];
firewall.trustedInterfaces = [ "virbr0" "waydroid0" ];
smartd.enable = true;
beesd.instances.root = { device = "/"; hashTableSizeMB = 16384; threads = 4; };
@@ -81,12 +73,7 @@ inputs:
gpus = { "4090" = 1; "p5000" = 1; };
};
xrdp = { enable = true; hostname = [ "xmupc2.chn.moe" ]; };
samba =
{
enable = true;
hostsAllowed = "";
shares = { home.path = "/home"; root.path = "/"; };
};
samba = { enable = true; hostsAllowed = ""; shares = { home.path = "/home"; root.path = "/"; }; };
groupshare = {};
};
bugs = [ "xmunet" ];

17
flake.lock generated
View File

@@ -1030,6 +1030,22 @@
"type": "github"
}
},
"kylin-virtual-keyboard": {
"flake": false,
"locked": {
"lastModified": 1710313521,
"narHash": "sha256-A8Y+lvAPlh0HeTxTaHCdAD/CilQCQwsX4C+fBBKaqTU=",
"ref": "refs/heads/upstream",
"rev": "a8ec88762d63d676aae4f5f1e6d9d1dedf07cf28",
"revCount": 161,
"type": "git",
"url": "https://gitee.com/openkylin/kylin-virtual-keyboard.git"
},
"original": {
"type": "git",
"url": "https://gitee.com/openkylin/kylin-virtual-keyboard.git"
}
},
"lepton": {
"flake": false,
"locked": {
@@ -1934,6 +1950,7 @@
"gricad": "gricad",
"home-manager": "home-manager",
"impermanence": "impermanence",
"kylin-virtual-keyboard": "kylin-virtual-keyboard",
"lepton": "lepton",
"linux-surface": "linux-surface",
"lmod": "lmod",

View File

@@ -67,6 +67,7 @@
lepton = { url = "github:black7375/Firefox-UI-Fix"; flake = false; };
lmod = { url = "github:TACC/Lmod"; flake = false; };
mumax = { url = "github:CHN-beta/mumax"; flake = false; };
kylin-virtual-keyboard = { url = "git+https://gitee.com/openkylin/kylin-virtual-keyboard.git"; flake = false; };
};
outputs = inputs:
@@ -94,13 +95,31 @@
# ssh-keygen -t rsa -C root@pe -f /mnt/nix/persistent/etc/ssh/ssh_host_rsa_key
# ssh-keygen -t ed25519 -C root@pe -f /mnt/nix/persistent/etc/ssh/ssh_host_ed25519_key
# systemd-machine-id-setup --root=/mnt/nix/persistent
nixosConfigurations = builtins.listToAttrs (builtins.map
(system:
{
name = system;
value = inputs.nixpkgs.lib.nixosSystem
nixosConfigurations =
(
(builtins.listToAttrs (builtins.map
(system:
{
system = "x86_64-linux";
name = system;
value = inputs.nixpkgs.lib.nixosSystem
{
system = "x86_64-linux";
specialArgs = { topInputs = inputs; inherit localLib; };
modules = localLib.mkModules
[
(moduleInputs: { config.nixpkgs.overlays = [(prev: final:
# replace pkgs with final to avoid infinite recursion
{ localPackages = import ./local/pkgs (moduleInputs // { pkgs = final; }); })]; })
./modules
./devices/${system}
];
};
})
devices))
// {
pi3b = inputs.nixpkgs.lib.nixosSystem
{
system = "aarch64-linux";
specialArgs = { topInputs = inputs; inherit localLib; };
modules = localLib.mkModules
[
@@ -108,11 +127,11 @@
# replace pkgs with final to avoid infinite recursion
{ localPackages = import ./local/pkgs (moduleInputs // { pkgs = final; }); })]; })
./modules
./devices/${system}
./devices/pi3b
];
};
})
devices);
}
);
# sudo HTTPS_PROXY=socks5://127.0.0.1:10884 nixos-install --flake .#bootstrap --option substituters http://127.0.0.1:5000 --option require-sigs false --option system-features gccarch-silvermont
# nix-serve -p 5000
# nix copy --substitute-on-destination --to ssh://server /run/current-system
@@ -148,12 +167,21 @@
inputs.self.nixosConfigurations.${node};
};
})
[ "vps6" "vps7" "nas" "surface" "xmupc1" "xmupc2" ]
[ "vps6" "vps7" "nas" "surface" "xmupc1" "xmupc2" "pi3b" ]
);
};
checks = builtins.mapAttrs (system: deployLib: deployLib.deployChecks inputs.self.deploy) inputs.deploy-rs.lib;
overlays.default = final: prev:
{ localPackages = (import ./local/pkgs { inherit (inputs) lib; pkgs = final; }); };
{ localPackages = (import ./local/pkgs { inherit (inputs) lib; pkgs = final; topInputs = inputs; }); };
config.archive = false;
devShell.x86_64-linux = let inherit (inputs.self.nixosConfigurations.pc) pkgs; in pkgs.mkShell
{
packages = with pkgs; [ pkg-config cmake ninja clang-tools_17 ];
buildInputs =
(with pkgs; [ fmt boost magic-enum libbacktrace eigen range-v3 ])
++ (with pkgs.localPackages; [ concurrencpp tgbot-cpp nameof ]);
# hardeningDisable = [ "all" ];
# NIX_DEBUG = "1";
};
};
}

View File

@@ -42,7 +42,7 @@ lib: rec
# - all .nix file in the directory except for default.nix
# - all directories containing a default.nix
findModules = path:
builtins.filter (path: path != null) (builtins.map
mkModules (builtins.filter (path: path != null) (builtins.map
(subPath:
if subPath.value == "regular" && subPath.name != "default.nix"
then if lib.strings.hasSuffix ".nix" subPath.name
@@ -53,5 +53,5 @@ lib: rec
then "${path}/${subPath.name}"
else null
else null)
(attrsToList (builtins.readDir path)));
(attrsToList (builtins.readDir path))));
}

View File

@@ -0,0 +1,45 @@
cmake_minimum_required(VERSION 3.14)
project(biu LANGUAGES CXX)
enable_testing()
include(GNUInstallDirs)
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
message("Setting build type to 'Release' as none was specified.")
set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
endif()
find_package(magic_enum REQUIRED)
find_package(fmt REQUIRED)
find_package(Boost REQUIRED COMPONENTS headers iostreams)
# find_package(concurrencpp REQUIRED)
find_package(Eigen3 REQUIRED)
find_package(range-v3 REQUIRED)
find_path(NAMEOF_INCLUDE_DIR nameof.hpp REQUIRED)
# find_path(TGBOTCPP_INCLUDE_DIR tgbot/tgbot.h REQUIRED)
# find_library(TGBOTCPP_LIB libTgBot.a REQUIRED)
# find_path(BACKTRACE_INCLUDE_DIR backtrace.h REQUIRED)
# find_library(BACKTRACE_LIB backtrace REQUIRED)
# add_library(biu SHARED src/common.cpp src/logger.cpp src/string.cpp)
add_library(biu SHARED src/common.cpp)
target_include_directories(biu PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
${NAMEOF_INCLUDE_DIR} ${TGBOTCPP_INCLUDE_DIR})
target_link_libraries(biu PUBLIC
magic_enum::magic_enum
fmt::fmt
Boost::headers Boost::iostreams
# concurrencpp::concurrencpp
Eigen3::Eigen
range-v3::range-v3)
# ${TGBOTCPP_LIB} ${BACKTRACE_LIB})
set_property(TARGET biu PROPERTY CXX_STANDARD 23 CXX_STANDARD_REQUIRED ON CXX_EXTENSIONS OFF)
install(TARGETS biu EXPORT biuConfig)
install(EXPORT biuConfig NAMESPACE ${PROJECT_NAME}:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/biu)
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
get_property(ImportedTargets DIRECTORY "${CMAKE_SOURCE_DIR}" PROPERTY IMPORTED_TARGETS)
message("Imported targets: ${ImportedTargets}")
message("List of compile features: ${CMAKE_CXX_COMPILE_FEATURES}")

View File

@@ -1,17 +1,10 @@
{
stdenv, fetchFromGitHub, cmake, pkg-config, ninja,
fmt, boost, magic-enum, libbacktrace, concurrencpp, tgbot-cpp, nameof, eigen, range-v3
}: stdenv.mkDerivation rec
stdenv, cmake,
magic-enum, fmt, boost, eigen, range-v3, nameof
}: stdenv.mkDerivation
{
name = "libbiu";
src = fetchFromGitHub
{
owner = "CHN-beta";
repo = "biu";
rev = "8ed2e52968f98d3a6ddbd01e86e57604ba3a7f54";
sha256 = "OqQ+QkjjIbpve/xn/DJA7ONw/bBg5zGNr+VJjc3o+K8=";
};
nativeBuildInputs = [ cmake pkg-config ninja ];
buildInputs = [ fmt boost magic-enum libbacktrace concurrencpp tgbot-cpp nameof eigen range-v3 ];
propagatedBuildInputs = buildInputs;
name = "biu";
src = ./.;
buildInputs = [ magic-enum fmt boost eigen range-v3 nameof ];
nativeBuildInputs = [ cmake ];
}

View File

@@ -0,0 +1,10 @@
# pragma once
// # include <biu/atomic/atomic.tpp>
// # include <biu/called_by.hpp>
# include <biu/common.tpp>
// # include <biu/concepts.tpp>
// # include <biu/format.tpp>
// # include <biu/logger.tpp>
// # include <biu/smartref.tpp>
// # include <biu/string.tpp>
# include <biu/eigen.hpp>

View File

@@ -0,0 +1,41 @@
# pragma once
# include <biu/logger.hpp>
namespace biu::detail_
{
template <DecayedType ValueType> class AtomicBase<ValueType, true>
: public Logger::ObjectMonitor<Atomic<ValueType, true>>, protected AtomicBase<ValueType, false>
{
using DeepBase_ = AtomicBase<ValueType, false>;
using DeepBase_::AtomicBase;
public: class TimeoutException : public Logger::Exception<TimeoutException>
{
using Logger::Exception<TimeoutException>::Exception;
};
protected: template
<
bool ReturnFunctionResult,
typename ConditionFunction = std::nullptr_t, typename Duration = std::nullptr_t, bool Nothrow = false
> static auto apply_
(
auto&& atomic, auto&& function,
ConditionFunction&& condition_function = nullptr, Duration timeout = nullptr
) -> DeepBase_::template ApplyReturnType_
<decltype(function), decltype(atomic), ReturnFunctionResult, ConditionFunction, Duration, Nothrow>
requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(atomic), ConditionFunction, Duration>;
protected: template <bool Nothrow = false, typename Duration = std::nullptr_t> static auto wait_
(auto&& atomic, auto&& condition_function, Duration timeout = nullptr)
-> DeepBase_::template WaitReturnType_<decltype(atomic), decltype(condition_function), Duration, Nothrow>
requires DeepBase_::template WaitConstraint_<decltype(condition_function), Duration>;
protected: template
<bool Nothrow = false, typename ConditionFunction = std::nullptr_t, typename Duration = std::nullptr_t>
static auto lock_
(auto&& atomic, ConditionFunction&& condition_function = nullptr, Duration timeout = nullptr)
-> DeepBase_::template LockReturnType_<decltype(atomic), Duration, Nothrow>
requires DeepBase_::template LockConstraint_<ConditionFunction, Duration>;
};
}

View File

@@ -0,0 +1,267 @@
# pragma once
# include <mutex>
# include <optional>
# include <condition_variable>
# include <cstddef>
# include <experimental/memory>
# include <biu/common.hpp>
# include <biu/concepts.hpp>
# include <biu/called_by.hpp>
namespace biu
{
template <DecayedType ValueType, bool UseLogger = true> class Atomic;
namespace detail_
{
template <DecayedType ValueType, bool UseLogger> class AtomicBase;
template <DecayedType ValueType> class AtomicBase<ValueType, false>
{
protected: mutable std::recursive_mutex Mutex_;
protected: mutable std::condition_variable_any ConditionVariable_;
protected: ValueType Value_;
AtomicBase() = default;
AtomicBase(const ValueType& value);
AtomicBase(ValueType&& value);
public: class TimeoutException : public std::exception
{
protected: std::string Message_;
public: explicit TimeoutException(std::string message);
public: const char* what() const noexcept override;
};
// Apply a function to stored value.
// Wait for some time (if provided) until condition funciton returns true (if provided)
// before applying the function.
protected: template
<
typename Function, typename Atomic,
typename ConditionFunction = std::nullptr_t, typename Duration = std::nullptr_t
>
constexpr static bool ApplyConstraint_ =
(
(std::invocable<Function, MoveQualifiers<Atomic, ValueType>> && std::is_null_pointer_v<ConditionFunction>)
|| (
InvocableWithResult<ConditionFunction, bool, const ValueType&>
&& (std::is_null_pointer_v<Duration> || SpecializationOf<Duration, std::chrono::duration>)
)
);
protected: template
<
typename Function, typename Atomic, bool ReturnFunctionResult,
typename ConditionFunction = std::nullptr_t, typename Duration = std::nullptr_t,
bool Nothrow = false
> using ApplyReturnType_ = std::conditional_t
<
Nothrow,
std::conditional_t
<
ReturnFunctionResult && !std::is_void_v<std::invoke_result<Function, ValueType>>,
std::optional<std::remove_cvref_t<FallbackIfNoTypeDeclared<std::invoke_result
<Function, MoveQualifiers<Atomic, ValueType>, int>>>>,
bool
>,
std::conditional_t
<
ReturnFunctionResult,
std::invoke_result_t<Function, MoveQualifiers<Atomic, ValueType>>,
Atomic&&
>
>;
protected: template
<
bool ReturnFunctionResult,
typename ConditionFunction = std::nullptr_t, typename Duration = std::nullptr_t,
bool Nothrow = false
> static auto apply_
(
auto&& atomic, auto&& function,
ConditionFunction&& condition_function = nullptr, Duration timeout = nullptr
) -> ApplyReturnType_
<decltype(function), decltype(atomic), ReturnFunctionResult, ConditionFunction, Duration, Nothrow>
requires ApplyConstraint_<decltype(function), decltype(atomic), ConditionFunction, Duration>;
// Wait until condition funciton returns true, with an optional timeout
protected: template <typename ConditionFunction, typename Duration = std::nullptr_t>
constexpr static bool WaitConstraint_
= (InvocableWithResult<ConditionFunction, bool, const ValueType&>
&& (std::is_null_pointer_v<Duration> || SpecializationOf<Duration, std::chrono::duration>));
protected: template
<typename Atomic, typename ConditionFunction, typename Duration = std::nullptr_t, bool Nothrow = false>
using WaitReturnType_
= std::conditional_t<Nothrow && !std::is_null_pointer_v<Duration>, bool, Atomic&&>;
protected: template <bool Nothrow = false, typename Duration = std::nullptr_t> static auto wait_
(auto&& atomic, auto&& condition_function, Duration timeout = nullptr)
-> WaitReturnType_<decltype(atomic), decltype(condition_function), Duration, Nothrow>
requires WaitConstraint_<decltype(condition_function), Duration>;
protected: template <typename ConditionFunction = std::nullptr_t, typename Duration = std::nullptr_t>
constexpr static bool LockConstraint_
= std::is_null_pointer_v<ConditionFunction> ||
(
InvocableWithResult<ConditionFunction, bool, const ValueType&>
&& (std::is_null_pointer_v<Duration> || SpecializationOf<Duration, std::chrono::duration>)
);
protected: template <typename Atomic, typename Duration = std::nullptr_t, bool Nothrow = false>
using LockReturnType_
= std::conditional_t
<
Nothrow && !std::is_null_pointer_v<Duration>,
std::optional<std::conditional_t
<
std::is_const_v<Atomic>,
typename std::remove_reference_t<Atomic>::template Guard<true>,
typename std::remove_reference_t<Atomic>::template Guard<false>
>>,
std::conditional_t
<
std::is_const_v<Atomic>,
typename std::remove_reference_t<Atomic>::template Guard<true>,
typename std::remove_reference_t<Atomic>::template Guard<false>
>
>;
protected: template
<bool Nothrow = false, typename ConditionFunction = std::nullptr_t, typename Duration = std::nullptr_t>
static auto lock_
(auto&& atomic, ConditionFunction&& condition_function = nullptr, Duration timeout = nullptr)
-> LockReturnType_<decltype(atomic), Duration, Nothrow>
requires LockConstraint_<ConditionFunction, Duration>;
};
}
// Thread safe wrapper of custom class
template <DecayedType ValueType, bool UseLogger> class Atomic : public detail_::AtomicBase<ValueType, UseLogger>
{
public: Atomic() = default;
public: Atomic(const ValueType& value);
public: Atomic(ValueType&& value);
public: template <bool OtherUseLogger> Atomic(const Atomic<ValueType, OtherUseLogger>& other);
public: template <bool OtherUseLogger> Atomic(Atomic<ValueType, OtherUseLogger>&& other);
public: Atomic<ValueType, UseLogger>& operator=(const ValueType& value);
public: Atomic<ValueType, UseLogger>& operator=(ValueType&& value);
public: template <bool OtherUseLogger>
Atomic<ValueType, UseLogger>& operator=(const Atomic<ValueType, OtherUseLogger>& other);
public: template <bool OtherUseLogger>
Atomic<ValueType, UseLogger>& operator=(Atomic<ValueType, OtherUseLogger>&& other);
public: ValueType get() const&;
public: ValueType get() &&;
public: operator ValueType() const&;
public: operator ValueType() &&;
protected: using DeepBase_ = detail_::AtomicBase<ValueType, false>;
public: template <bool ReturnFunctionResult = false> auto apply(auto&& function) const&
-> DeepBase_::template ApplyReturnType_<decltype(function), decltype(*this), ReturnFunctionResult>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this)>;
public: template <bool ReturnFunctionResult = false> auto apply(auto&& function) &
-> DeepBase_::template ApplyReturnType_<decltype(function), decltype(*this), ReturnFunctionResult>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this)>;
public: template <bool ReturnFunctionResult = false> auto apply(auto&& function) &&
-> DeepBase_::template ApplyReturnType_<decltype(function), decltype(*this), ReturnFunctionResult>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this)>;
public: template <bool ReturnFunctionResult = false>
auto apply(auto&& function, auto&& condition_function) const&
-> DeepBase_::template ApplyReturnType_
<decltype(function), decltype(*this), ReturnFunctionResult, decltype(condition_function)>
requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function)>;
public: template <bool ReturnFunctionResult = false> auto apply(auto&& function, auto&& condition_function) &
-> DeepBase_::template ApplyReturnType_
<decltype(function), decltype(*this), ReturnFunctionResult, decltype(condition_function)>
requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function)>;
public: template <bool ReturnFunctionResult = false> auto apply(auto&& function, auto&& condition_function) &&
-> DeepBase_::template ApplyReturnType_
<decltype(function), decltype(*this), ReturnFunctionResult, decltype(condition_function)>
requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function)>;
public: template <bool ReturnFunctionResult = false, bool Nothrow = false>
auto apply(auto&& function, auto&& condition_function, auto timeout) const&
-> DeepBase_::template ApplyReturnType_
<
decltype(function), decltype(*this), ReturnFunctionResult,
decltype(condition_function), decltype(timeout), Nothrow
> requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function), decltype(timeout)>;
public: template <bool ReturnFunctionResult = false, bool Nothrow = false>
auto apply(auto&& function, auto&& condition_function, auto timeout) &
-> DeepBase_::template ApplyReturnType_
<
decltype(function), decltype(*this), ReturnFunctionResult,
decltype(condition_function), decltype(timeout), Nothrow
> requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function), decltype(timeout)>;
public: template <bool ReturnFunctionResult = false, bool Nothrow = false>
auto apply(auto&& function, auto&& condition_function, auto timeout) &&
-> DeepBase_::template ApplyReturnType_
<
decltype(function), decltype(*this), ReturnFunctionResult,
decltype(condition_function), decltype(timeout), Nothrow
> requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function), decltype(timeout)>;
public: auto wait(auto&& condition_function) const&
-> DeepBase_::template WaitReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template WaitConstraint_<decltype(condition_function)>;
public: auto wait(auto&& condition_function) &
-> DeepBase_::template WaitReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template WaitConstraint_<decltype(condition_function)>;
public: auto wait(auto&& condition_function) &&
-> DeepBase_::template WaitReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template WaitConstraint_<decltype(condition_function)>;
public: template <bool Nothrow = false> auto wait(auto&& condition_function, auto timeout) const&
-> DeepBase_::template WaitReturnType_
<decltype(*this), decltype(condition_function), decltype(timeout), Nothrow>
requires DeepBase_::template WaitConstraint_<decltype(condition_function), decltype(timeout)>;
public: template <bool Nothrow = false> auto wait(auto&& condition_function, auto timeout) &
-> DeepBase_::template WaitReturnType_
<decltype(*this), decltype(condition_function), decltype(timeout), Nothrow>
requires DeepBase_::template WaitConstraint_<decltype(condition_function), decltype(timeout)>;
public: template <bool Nothrow = false> auto wait(auto&& condition_function, auto timeout) &&
-> DeepBase_::template WaitReturnType_
<decltype(*this), decltype(condition_function), decltype(timeout), Nothrow>
requires DeepBase_::template WaitConstraint_<decltype(condition_function), decltype(timeout)>;
// Attain lock from outside when constructing, and release when destructing.
// For non-const variant, When destructing, ConditionVariable_.notify_all() is called.
public: template <bool Const> class Guard
{
protected: std::unique_lock<std::recursive_mutex> Lock_;
protected: std::experimental::observer_ptr
<std::conditional_t<Const, const Atomic<ValueType, UseLogger>, Atomic<ValueType, UseLogger>>> Value_;
public: template <bool OtherConst> Guard(const Guard<OtherConst>& other) requires (Const || !OtherConst);
public: Guard
(decltype(Lock_)&& lock, decltype(Value_) value, CalledBy<detail_::AtomicBase<ValueType, UseLogger>>);
public: ~Guard();
public: std::conditional_t<Const, const ValueType&, ValueType&> operator*() const&;
public: std::conditional_t<Const, const ValueType*, ValueType*> operator->() const&;
public: std::conditional_t<Const, const ValueType&, ValueType&> value() const&;
public: auto operator*() const&& = delete;
public: auto operator->() const&& = delete;
public: auto value() const&& = delete;
};
public: auto lock() const& -> DeepBase_::template LockReturnType_<decltype(*this)>
requires DeepBase_::template LockConstraint_<>;
public: auto lock() & -> DeepBase_::template LockReturnType_<decltype(*this)>
requires DeepBase_::template LockConstraint_<>;
public: auto lock() const&& = delete;
public: auto lock(auto&& condition_function) const&
-> DeepBase_::template LockReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template LockConstraint_<decltype(condition_function)>;
public: auto lock(auto&& condition_function) &
-> DeepBase_::template LockReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template LockConstraint_<decltype(condition_function)>;
public: auto lock(auto&& condition_function) const&& = delete;
public: template <bool Nothrow = false> auto lock(auto&& condition_function, auto timeout) const&
-> DeepBase_::template LockReturnType_<decltype(*this), decltype(timeout), Nothrow>
requires DeepBase_::template LockConstraint_<decltype(condition_function), decltype(timeout)>;
public: template <bool Nothrow = false> auto lock(auto&& condition_function, auto timeout) &
-> DeepBase_::template LockReturnType_<decltype(*this), decltype(timeout), Nothrow>
requires DeepBase_::template LockConstraint_<decltype(condition_function), decltype(timeout)>;
public: template <bool Nothrow = false> auto lock(auto&& condition_function, auto timeout) const&& = delete;
};
}

View File

@@ -0,0 +1,366 @@
# pragma once
# include <biu/atomic/nolog.hpp>
namespace biu
{
template <DecayedType ValueType> detail_::AtomicBase<ValueType, false>::AtomicBase(const ValueType& value)
: Value_{value} {}
template <DecayedType ValueType> detail_::AtomicBase<ValueType, false>::AtomicBase(ValueType&& value)
: Value_{std::move(value)} {}
template <DecayedType ValueType>
detail_::AtomicBase<ValueType, false>::TimeoutException::TimeoutException(std::string)
: Message_{"TimeoutException"} {}
template <DecayedType ValueType>
const char* detail_::AtomicBase<ValueType, false>::TimeoutException::what() const noexcept
{return Message_.c_str();}
template <DecayedType ValueType>
template <bool ReturnFunctionResult, typename ConditionFunction, typename Duration, bool Nothrow>
auto detail_::AtomicBase<ValueType, false>::apply_
(auto&& atomic, auto&& function, ConditionFunction&& condition_function, Duration timeout)
-> ApplyReturnType_
<decltype(function), decltype(atomic), ReturnFunctionResult, ConditionFunction, Duration, Nothrow>
requires ApplyConstraint_<decltype(function), decltype(atomic), ConditionFunction, Duration>
{
std::unique_lock lock{atomic.Mutex_};
// try to meet the condition
if constexpr (!std::is_null_pointer_v<ConditionFunction>)
{
if constexpr (std::is_null_pointer_v<Duration>)
atomic.ConditionVariable_.wait(lock, [&]
{return std::forward<ConditionFunction>(condition_function)(std::as_const(atomic.Value_));});
else if (!atomic.ConditionVariable_.wait_for(lock, timeout, [&]
{return std::forward<ConditionFunction>(condition_function)(std::as_const(atomic.Value_));}))
{
if constexpr (Nothrow)
{
if constexpr
(ReturnFunctionResult && !std::is_void_v<std::invoke_result_t<decltype(function), ValueType>>)
return std::nullopt;
else return false;
}
else throw TimeoutException{};
}
}
// apply the function and return
if constexpr (ReturnFunctionResult && !std::is_void_v<std::invoke_result_t<decltype(function), ValueType>>)
{
auto&& result = std::forward<decltype(function)>(function)
(static_cast<MoveQualifiers<decltype(atomic), ValueType>&&>(atomic.Value_));
if constexpr (!std::is_const_v<decltype(atomic)>) atomic.ConditionVariable_.notify_all();
return std::forward<decltype(result)>(result);
}
else
{
std::forward<decltype(function)>(function)
(static_cast<MoveQualifiers<decltype(atomic), ValueType>&&>(atomic.Value_));
if constexpr (!std::is_const_v<decltype(atomic)>) atomic.ConditionVariable_.notify_all();
if constexpr (ReturnFunctionResult && std::is_void_v<std::invoke_result_t<decltype(function), ValueType>>)
return;
else return std::forward<decltype(atomic)>(atomic);
}
}
template <DecayedType ValueType> template <bool Nothrow, typename Duration>
auto detail_::AtomicBase<ValueType, false>::wait_(auto&& atomic, auto&& condition_function, Duration timeout)
-> WaitReturnType_<decltype(atomic), decltype(condition_function), Duration, Nothrow>
requires WaitConstraint_<decltype(condition_function), Duration>
{
std::unique_lock lock{atomic.Mutex_};
if constexpr (std::is_null_pointer_v<Duration>)
{
atomic.ConditionVariable_.wait(lock, [&]
{return std::forward<decltype(condition_function)>(condition_function)(std::as_const(atomic.Value_));});
return std::forward<decltype(atomic)>(atomic);
}
else
{
if (!atomic.ConditionVariable_.wait_for(lock, timeout, [&]
{return std::forward<decltype(condition_function)>(condition_function)(std::as_const(atomic.Value_));}))
{
if constexpr (Nothrow) return false;
else throw TimeoutException{};
}
else
{
if constexpr (Nothrow) return true;
else return std::forward<decltype(atomic)>(atomic);
}
}
}
template <DecayedType ValueType> template <bool Nothrow, typename ConditionFunction, typename Duration>
auto detail_::AtomicBase<ValueType, false>::lock_
(auto&& atomic, ConditionFunction&& condition_function, Duration timeout)
-> LockReturnType_<decltype(atomic), Duration, Nothrow> requires LockConstraint_<ConditionFunction, Duration>
{
if constexpr (std::is_null_pointer_v<ConditionFunction>)
return {std::unique_lock{atomic.Mutex_}, std::experimental::make_observer(&atomic), {}};
else if constexpr (std::is_null_pointer_v<Duration>)
{
std::unique_lock lock{atomic.Mutex_};
atomic.ConditionVariable_.wait(lock, [&]
{return std::forward<ConditionFunction>(condition_function)(std::as_const(atomic.Value_));});
return {std::move(lock), std::experimental::make_observer(&atomic), {}};
}
else
{
std::unique_lock lock{atomic.Mutex_};
if (!atomic.ConditionVariable_.wait_for(lock, timeout, [&]
{return std::forward<ConditionFunction>(condition_function)(std::as_const(atomic.Value_));}))
{
if constexpr (Nothrow) return std::nullopt;
else throw TimeoutException{};
}
else
return {{std::move(lock), std::experimental::make_observer(&atomic), {}}};
}
}
template <DecayedType ValueType, bool UseLogger> Atomic<ValueType, UseLogger>::Atomic(const ValueType& value)
: detail_::AtomicBase<ValueType, UseLogger>{value} {}
template <DecayedType ValueType, bool UseLogger> Atomic<ValueType, UseLogger>::Atomic(ValueType&& value)
: detail_::AtomicBase<ValueType, UseLogger>{std::move(value)} {}
template <DecayedType ValueType, bool UseLogger> template <bool OtherUseLogger>
Atomic<ValueType, UseLogger>::Atomic(const Atomic<ValueType, OtherUseLogger>& other)
: detail_::AtomicBase<ValueType, UseLogger>{other} {}
template <DecayedType ValueType, bool UseLogger> template <bool OtherUseLogger>
Atomic<ValueType, UseLogger>::Atomic(Atomic<ValueType, OtherUseLogger>&& other)
: detail_::AtomicBase<ValueType, UseLogger>{std::move(other)} {}
template <DecayedType ValueType, bool UseLogger>
Atomic<ValueType, UseLogger>& Atomic<ValueType, UseLogger>::operator=(const ValueType& value)
{
std::scoped_lock lock{DeepBase_::Mutex_};
DeepBase_::Value_ = value;
DeepBase_::ConditionVariable_.notify_all();
return *this;
}
template <DecayedType ValueType, bool UseLogger>
Atomic<ValueType, UseLogger>& Atomic<ValueType, UseLogger>::operator=(ValueType&& value)
{
std::scoped_lock lock{DeepBase_::Mutex_};
DeepBase_::Value_ = std::move(value);
DeepBase_::ConditionVariable_.notify_all();
return *this;
}
template <DecayedType ValueType, bool UseLogger> template <bool OtherUseLogger>
Atomic<ValueType, UseLogger>& operator=(const Atomic<ValueType, OtherUseLogger>& other)
{
std::scoped_lock lock{DeepBase_::Mutex_};
DeepBase_::Value_ = value;
DeepBase_::ConditionVariable_.notify_all();
return *this;
}
template <DecayedType ValueType, bool UseLogger> template <bool OtherUseLogger>
Atomic<ValueType, UseLogger>& operator=(Atomic<ValueType, OtherUseLogger>&& other)
{
std::scoped_lock lock{DeepBase_::Mutex_};
DeepBase_::Value_ = std::move(value);
DeepBase_::ConditionVariable_.notify_all();
return *this;
}
template <DecayedType ValueType, bool UseLogger> ValueType Atomic<ValueType, UseLogger>::get() const&
{
std::scoped_lock lock{DeepBase_::Mutex_};
return DeepBase_::Value_;
}
template <DecayedType ValueType, bool UseLogger> ValueType Atomic<ValueType, UseLogger>::get() &&
{
std::scoped_lock lock{DeepBase_::Mutex_};
return std::move(DeepBase_::Value_);
}
template <DecayedType ValueType, bool UseLogger> Atomic<ValueType, UseLogger>::operator ValueType() const&
{return get();}
template <DecayedType ValueType, bool UseLogger> Atomic<ValueType, UseLogger>::operator ValueType() &&
{return std::move(*this).get();}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult>
auto Atomic<ValueType, UseLogger>::apply(auto&& function) const&
-> DeepBase_::template ApplyReturnType_<decltype(function), decltype(*this), ReturnFunctionResult>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this)>
{return apply_<ReturnFunctionResult>(*this, std::forward<decltype(function)>(function));}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult>
auto Atomic<ValueType, UseLogger>::apply(auto&& function) &
-> DeepBase_::template ApplyReturnType_<decltype(function), decltype(*this), ReturnFunctionResult>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this)>
{return apply_<ReturnFunctionResult>(*this, std::forward<decltype(function)>(function));}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult>
auto Atomic<ValueType, UseLogger>::apply(auto&& function) &&
-> DeepBase_::template ApplyReturnType_<decltype(function), decltype(*this), ReturnFunctionResult>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this)>
{return apply_<ReturnFunctionResult>(std::move(*this), std::forward<decltype(function)>(function));}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult>
auto Atomic<ValueType, UseLogger>::apply(auto&& function, auto&& condition_function) const&
-> DeepBase_::template ApplyReturnType_
<decltype(function), decltype(*this), ReturnFunctionResult, decltype(condition_function)>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this), decltype(condition_function)>
{
return apply_<ReturnFunctionResult>
(
*this, std::forward<decltype(function)>(function),
std::forward<decltype(condition_function)>(condition_function)
);
}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult>
auto Atomic<ValueType, UseLogger>::apply(auto&& function, auto&& condition_function) &
-> DeepBase_::template ApplyReturnType_
<decltype(function), decltype(*this), ReturnFunctionResult, decltype(condition_function)>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this), decltype(condition_function)>
{
return apply_<ReturnFunctionResult>
(
*this, std::forward<decltype(function)>(function),
std::forward<decltype(condition_function)>(condition_function)
);
}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult>
auto Atomic<ValueType, UseLogger>::apply(auto&& function, auto&& condition_function) &&
-> DeepBase_::template ApplyReturnType_
<decltype(function), decltype(*this), ReturnFunctionResult, decltype(condition_function)>
requires DeepBase_::template ApplyConstraint_<decltype(function), decltype(*this), decltype(condition_function)>
{
return apply_<ReturnFunctionResult>
(
std::move(*this), std::forward<decltype(function)>(function),
std::forward<decltype(condition_function)>(condition_function)
);
}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult, bool Nothrow>
auto Atomic<ValueType, UseLogger>::apply(auto&& function, auto&& condition_function, auto timeout) const&
-> DeepBase_::template ApplyReturnType_
<
decltype(function), decltype(*this), ReturnFunctionResult,
decltype(condition_function), decltype(timeout), Nothrow
> requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function), decltype(timeout)>
{
return apply_<ReturnFunctionResult, Nothrow>
(
*this, std::forward<decltype(function)>(function),
std::forward<decltype(condition_function)>(condition_function), timeout
);
}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult, bool Nothrow>
auto Atomic<ValueType, UseLogger>::apply(auto&& function, auto&& condition_function, auto timeout) &
-> DeepBase_::template ApplyReturnType_
<
decltype(function), decltype(*this), ReturnFunctionResult,
decltype(condition_function), decltype(timeout), Nothrow
> requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function), decltype(timeout)>
{
return apply_<ReturnFunctionResult, Nothrow>
(
*this, std::forward<decltype(function)>(function),
std::forward<decltype(condition_function)>(condition_function), timeout
);
}
template <DecayedType ValueType, bool UseLogger> template <bool ReturnFunctionResult, bool Nothrow>
auto Atomic<ValueType, UseLogger>::apply(auto&& function, auto&& condition_function, auto timeout) &&
-> DeepBase_::template ApplyReturnType_
<
decltype(function), decltype(*this), ReturnFunctionResult,
decltype(condition_function), decltype(timeout), Nothrow
> requires DeepBase_::template ApplyConstraint_
<decltype(function), decltype(*this), decltype(condition_function), decltype(timeout)>
{
return apply_<ReturnFunctionResult, Nothrow>
(
std::move(*this), std::forward<decltype(function)>(function),
std::forward<decltype(condition_function)>(condition_function), timeout
);
}
template <DecayedType ValueType, bool UseLogger>
auto Atomic<ValueType, UseLogger>::wait(auto&& condition_function) const&
-> DeepBase_::template WaitReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template WaitConstraint_<decltype(condition_function)>
{return wait_(*this, std::forward<decltype(condition_function)>(condition_function));}
template <DecayedType ValueType, bool UseLogger>
auto Atomic<ValueType, UseLogger>::wait(auto&& condition_function) &
-> DeepBase_::template WaitReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template WaitConstraint_<decltype(condition_function)>
{return wait_(*this, std::forward<decltype(condition_function)>(condition_function));}
template <DecayedType ValueType, bool UseLogger>
auto Atomic<ValueType, UseLogger>::wait(auto&& condition_function) &&
-> DeepBase_::template WaitReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template WaitConstraint_<decltype(condition_function)>
{return wait_(std::move(*this), std::forward<decltype(condition_function)>(condition_function));}
template <DecayedType ValueType, bool UseLogger> template <bool Nothrow>
auto Atomic<ValueType, UseLogger>::wait(auto&& condition_function, auto timeout) const&
-> DeepBase_::template WaitReturnType_
<decltype(*this), decltype(condition_function), decltype(timeout), Nothrow>
requires DeepBase_::template WaitConstraint_<decltype(condition_function), decltype(timeout)>
{return wait_<Nothrow>(*this, std::forward<decltype(condition_function)>(condition_function), timeout);}
template <DecayedType ValueType, bool UseLogger> template <bool Nothrow>
auto Atomic<ValueType, UseLogger>::wait(auto&& condition_function, auto timeout) &
-> DeepBase_::template WaitReturnType_
<decltype(*this), decltype(condition_function), decltype(timeout), Nothrow>
requires DeepBase_::template WaitConstraint_<decltype(condition_function), decltype(timeout)>
{return wait_<Nothrow>(*this, std::forward<decltype(condition_function)>(condition_function), timeout);}
template <DecayedType ValueType, bool UseLogger> template <bool Nothrow>
auto Atomic<ValueType, UseLogger>::wait(auto&& condition_function, auto timeout) &&
-> DeepBase_::template WaitReturnType_
<decltype(*this), decltype(condition_function), decltype(timeout), Nothrow>
requires DeepBase_::template WaitConstraint_<decltype(condition_function), decltype(timeout)>
{
return wait_<Nothrow>
(std::move(*this), std::forward<decltype(condition_function)>(condition_function), timeout);
}
template <DecayedType ValueType, bool UseLogger> template <bool Const> template <bool OtherConst>
Atomic<ValueType, UseLogger>::Guard<Const>::Guard(const Guard<OtherConst>& other)
requires (Const || !OtherConst)
: Lock_{other.Lock_}, Value_{other.Value_} {}
template <DecayedType ValueType, bool UseLogger> template <bool Const>
Atomic<ValueType, UseLogger>::Guard<Const>::Guard
(decltype(Lock_)&& lock, decltype(Value_) value, CalledBy<detail_::AtomicBase<ValueType, UseLogger>>)
: Lock_{std::move(lock)}, Value_{value} {}
template <DecayedType ValueType, bool UseLogger> template <bool Const>
Atomic<ValueType, UseLogger>::Guard<Const>::~Guard()
{Value_->ConditionVariable_.notify_all();}
template <DecayedType ValueType, bool UseLogger> template <bool Const>
std::conditional_t<Const, const ValueType&, ValueType&>
Atomic<ValueType, UseLogger>::Guard<Const>::operator*() const&
{return Value_->Value_;}
template <DecayedType ValueType, bool UseLogger> template <bool Const>
std::conditional_t<Const, const ValueType*, ValueType*>
Atomic<ValueType, UseLogger>::Guard<Const>::operator->() const&
{return &Value_->Value_;}
template <DecayedType ValueType, bool UseLogger> template <bool Const>
std::conditional_t<Const, const ValueType&, ValueType&>
Atomic<ValueType, UseLogger>::Guard<Const>::value() const&
{return Value_->Value_;}
template <DecayedType ValueType, bool UseLogger> auto Atomic<ValueType, UseLogger>::lock() const&
-> DeepBase_::template LockReturnType_<decltype(*this)> requires DeepBase_::template LockConstraint_<>
{return lock_(*this);}
template <DecayedType ValueType, bool UseLogger> auto Atomic<ValueType, UseLogger>::lock() &
-> DeepBase_::template LockReturnType_<decltype(*this)> requires DeepBase_::template LockConstraint_<>
{return lock_(*this);}
template <DecayedType ValueType, bool UseLogger>
auto Atomic<ValueType, UseLogger>::lock(auto&& condition_function) const&
-> DeepBase_::template LockReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template LockConstraint_<decltype(condition_function)>
{return lock_(*this, condition_function);}
template <DecayedType ValueType, bool UseLogger>
auto Atomic<ValueType, UseLogger>::lock(auto&& condition_function) &
-> DeepBase_::template LockReturnType_<decltype(*this), decltype(condition_function)>
requires DeepBase_::template LockConstraint_<decltype(condition_function)>
{return lock_(*this, condition_function);}
template <DecayedType ValueType, bool UseLogger> template <bool Nothrow>
auto Atomic<ValueType, UseLogger>::lock(auto&& condition_function, auto timeout) const&
-> DeepBase_::template LockReturnType_<decltype(*this), decltype(timeout), Nothrow>
requires DeepBase_::template LockConstraint_<decltype(condition_function), decltype(timeout)>
{return lock_<Nothrow>(*this, condition_function, timeout);}
template <DecayedType ValueType, bool UseLogger> template <bool Nothrow>
auto Atomic<ValueType, UseLogger>::lock(auto&& condition_function, auto timeout) &
-> DeepBase_::template LockReturnType_<decltype(*this), decltype(timeout), Nothrow>
requires DeepBase_::template LockConstraint_<decltype(condition_function), decltype(timeout)>
{return lock_<Nothrow>(*this, condition_function, timeout);}
}

View File

@@ -0,0 +1,10 @@
# pragma once
namespace biu
{
template <typename AllowedType> class CalledBy
{
protected: CalledBy() = default;
friend AllowedType;
};
}

View File

@@ -0,0 +1,66 @@
# pragma once
# include <regex>
# include <fmt/format.h>
# include <magic_enum.hpp>
namespace biu
{
std::size_t hash(auto&&... objs);
[[gnu::always_inline]] void unused(auto&&...);
using uint128_t = __uint128_t;
inline namespace literals
{
using namespace std::literals;
using namespace fmt::literals;
std::regex operator""_re(const char* str, std::size_t len);
}
inline namespace stream_operators { using namespace magic_enum::iostream_operators; }
struct CaseInsensitiveStringLessComparator
{
template <typename String> constexpr bool operator()(const String& s1, const String& s2) const;
};
namespace detail_
{
template <typename T> struct RemoveMemberPointerHelper { using Type = T; };
template <typename Class, typename Member> struct RemoveMemberPointerHelper<Member Class::*>
{ using Type = Member; };
}
template <typename MemberPointer> using RemoveMemberPointer
= typename detail_::RemoveMemberPointerHelper<MemberPointer>::Type;
[[noreturn]] void block_forever();
namespace detail_
{
template <typename From, typename To> struct MoveQualifiersHelper
{
protected: static constexpr bool Const_ = std::is_const_v<From>;
protected: static constexpr bool Volatile_ = std::is_volatile_v<From>;
protected: static constexpr bool Reference_ = std::is_reference_v<From>;
protected: static constexpr bool Lvalue_ = std::is_lvalue_reference_v<From>;
protected: using NoCvrefType_ = std::remove_cvref_t<To>;
protected: using NoCvType_
= std::conditional_t<Reference_, std::conditional_t<Lvalue_, NoCvrefType_&, NoCvrefType_&&>, NoCvrefType_>;
protected: using NoConstType_ = std::conditional_t<Volatile_, volatile NoCvType_, NoCvType_>;
public: using Type = std::conditional_t<Const_, const NoConstType_, NoConstType_>;
};
}
template <typename From, typename To> using MoveQualifiers
= typename detail_::MoveQualifiersHelper<From, To>::Type;
namespace detail_
{
template <typename T, typename Fallback = void> struct FallbackIfNoTypeDeclaredHelper { using Type = Fallback; };
template <typename T, typename Fallback> requires requires { typename T::Type; }
struct FallbackIfNoTypeDeclaredHelper<T, Fallback> { using Type = typename T::Type; };
template <typename T, typename Fallback> requires requires {typename T::type;}
struct FallbackIfNoTypeDeclaredHelper<T, Fallback> { using Type = typename T::type; };
}
template <typename T, typename Fallback = void> using FallbackIfNoTypeDeclared
= typename detail_::FallbackIfNoTypeDeclaredHelper<T, Fallback>::Type;
}

View File

@@ -0,0 +1,24 @@
# pragma once
# include <boost/functional/hash.hpp>
# include <biu/common.hpp>
namespace biu
{
inline void unused(auto&&...) {}
inline std::size_t hash(auto&&... objs)
{
std::size_t result = 0;
(boost::hash_combine(result, objs), ...);
return result;
}
template <typename String> inline constexpr bool CaseInsensitiveStringLessComparator::operator()
(const String& s1, const String& s2) const
{
return std::lexicographical_compare
(
s1.begin(), s1.end(), s2.begin(), s2.end(),
[](char c1, char c2){return std::tolower(c1) < std::tolower(c2);}
);
}
}

View File

@@ -0,0 +1,47 @@
# pragma once
# include <concepts>
# include <tuple>
# include <type_traits>
# include <complex>
namespace biu
{
template <typename T> concept DecayedType = std::same_as<std::decay_t<T>, T>;
namespace detail_::specialization_of_detail_
{
template <typename Tuple> struct DropFirstMemberOfTupleHelper;
template <typename First, typename... Others> struct DropFirstMemberOfTupleHelper<std::tuple<First, Others...>>
{using Type = std::tuple<Others...>;};
template <typename ProvidedArgs, typename ActualArgs> consteval bool check_provided_args();
template <typename Class, template <typename...> typename Template> struct SpecializationOfHelper
{template <typename... ProvidedArgs> consteval static bool check_provided_args();};
template <template <typename...> typename Template, typename... ActualArgs>
struct SpecializationOfHelper<Template<ActualArgs...>, Template>
{template <typename... ProvidedArgs> consteval static bool check_provided_args();};
}
template <typename Class, template <typename...> typename Template, typename... ProvidedArgs>
concept SpecializationOf
= detail_::specialization_of_detail_::SpecializationOfHelper<std::decay_t<Class>, Template>
::template check_provided_args<ProvidedArgs...>();
template <typename T> concept CompletedType = sizeof(T) == sizeof(T);
template <typename From, typename To> concept ImplicitlyConvertibleTo = std::is_convertible<From, To>::value;
template <typename To, typename From> concept ImplicitlyConvertibleFrom = std::is_convertible<From, To>::value;
template <typename From, typename To> concept ExplicitlyConvertibleTo = std::is_constructible<To, From>::value;
template <typename To, typename From> concept ExplicitlyConvertibleFrom = std::is_constructible<To, From>::value;
template <typename From, typename To> concept ConvertibleTo
= ImplicitlyConvertibleTo<From, To> || ExplicitlyConvertibleTo<From, To>;
template <typename From, typename To> concept ConvertibleFrom = ConvertibleTo<From, To>;
template <typename Function, auto... Args> concept ConstevalInvokable
= requires() {typename std::type_identity_t<int[(Function()(Args...), 1)]>;};
template <typename T> concept Enumerable = std::is_enum_v<T>;
template <typename Function, typename Result, typename... Args> concept InvocableWithResult
= std::is_invocable_r_v<Result, Function, Args...>;
template <typename T> concept Arithmetic = std::is_arithmetic<T>::value || SpecializationOf<T, std::complex>;
}

View File

@@ -0,0 +1,34 @@
# pragma once
# include <tuple>
# include <biu/concepts.hpp>
namespace biu
{
template <typename ProvidedArgs, typename ActualArgs> consteval bool
detail_::specialization_of_detail_::check_provided_args()
{
if constexpr (std::tuple_size_v<ProvidedArgs> == 0)
return true;
else if constexpr (std::tuple_size_v<ActualArgs> == 0)
return false;
else if constexpr
(std::same_as<std::tuple_element_t<0, ProvidedArgs>, std::tuple_element_t<0, ActualArgs>>)
return check_provided_args
<
typename DropFirstMemberOfTupleHelper<ProvidedArgs>::Type,
typename DropFirstMemberOfTupleHelper<ActualArgs>::Type
>();
else
return false;
}
template <typename Class, template <typename...> typename Template> template <typename... ProvidedArgs> consteval
bool detail_::specialization_of_detail_::SpecializationOfHelper<Class, Template>::check_provided_args()
{ return false; }
template <template <typename...> typename Template, typename... ActualArgs> template <typename... ProvidedArgs>
consteval bool detail_::specialization_of_detail_::SpecializationOfHelper
<Template<ActualArgs...>, Template>::check_provided_args()
{
return specialization_of_detail_::check_provided_args
<std::tuple<ProvidedArgs...>, std::tuple<ActualArgs...>>();
}
}

View File

@@ -0,0 +1,54 @@
# pragma once
# include <vector>
# include <span>
# include <Eigen/Dense>
# include <biu/concepts.hpp>
namespace biu
{
namespace detail_::eigen
{
// user-specified size of destination container: dynamic, unspecified(use default), or fixed
constexpr std::size_t dynamicSize = std::dynamic_extent, unspecifiedSize = std::dynamic_extent - 1;
static_assert(std::dynamic_extent == std::numeric_limits<std::size_t>::max());
// supported types of standard containers
template <typename T, typename Scalar> struct SpecializationOfArrayHelper : std::false_type {};
template <typename Scalar, std::size_t N>
struct SpecializationOfArrayHelper<std::array<Scalar, N>, Scalar> : std::true_type {};
template <typename Scalar, std::size_t N>
struct SpecializationOfArrayHelper<std::array<Scalar, N>, void> : std::true_type {};
template <typename T, typename Scalar = void> concept SpecializationOfArray =
SpecializationOfArrayHelper<T, Scalar>::value;
template <typename T, typename Scalar> concept StandardContainer =
SpecializationOf<T, std::vector, Scalar> || SpecializationOfArray<T, Scalar>;
// helper operator| to specify the size of the destination container
// usage: some_value | toEigen<Row, Col>
template <std::size_t Row, std::size_t Col> struct ToEigenHelper {};
template <std::size_t Row = unspecifiedSize, std::size_t Col = unspecifiedSize>
inline constexpr ToEigenHelper<Row, Col> toEigen;
// convert 1D standard container to Eigen::Vector
// if no size is specified, convert std::vector to dynamic-size Eigen::Vector,
// std::array to fixed-size Eigen::Vector;
// if size is std::dynamic_extent, always convert to dynamic-size Eigen::Vector
// if size is specified as a number, convert to fixed-size Eigen::Vector if specified size equals the size of the
// input, otherwise throw an error
template <template <int N> typename Callback, std::size_t ToSize> auto deduce_eigen_size(auto&& container);
template <Arithmetic T, StandardContainer<T> From, std::size_t ToSize> auto operator|
(const From&, const ToEigenHelper<ToSize, unspecifiedSize>&);
// convert 2D standard container to Eigen::Matrix
// the same rules as above apply
// besides, all rows must have the same size, otherwise throw an error
template
<
Arithmetic T, StandardContainer<T> FromPerRow, StandardContainer<FromPerRow> From,
std::size_t ToRow, std::size_t ToCol
>
auto operator|(const From&, const ToEigenHelper<ToRow, ToCol>&);
// TODO: implement fromEigen
}
inline namespace eigen { using detail_::eigen::toEigen; using detail_::eigen::operator|; }
}

View File

@@ -0,0 +1,29 @@
# pragma once
# include <biu/eigen.hpp>
// TODO: fix biu::logger
// # include <biu/logger.hpp>
# include <range/v3/view.hpp>
namespace biu
{
namespace detail_::eigen
{
template <template <int N> typename Callback, std::size_t ToSize> auto deduce_eigen_size(auto&& from)
{
if constexpr (ToSize == dynamicSize)
return Callback<Eigen::Dynamic>()(from.data(), from.size());
else if constexpr (ToSize == unspecifiedSize)
if constexpr (SpecializationOfArray<decltype(from)>)
return Callback<from.size()>()(from.data());
else
return Callback<Eigen::Dynamic>()(from.data(), from.size());
else
if (from.size() != ToSize)
// TODO: use biu::logger
throw std::invalid_argument("biu::toEigen: size mismatch");
else
return Callback<ToSize>()(from.data());
}
// TODO: implement 2D case
}
}

View File

@@ -0,0 +1,72 @@
# pragma once
# include <variant>
# include <experimental/memory>
# include <fmt/ostream.h>
# include <biu/string.hpp>
# include <biu/concepts.hpp>
namespace biu
{
template <typename T, typename Char = char> concept Formattable = fmt::is_formattable<T, Char>::value;
namespace detail_
{
template <typename Char, Char... c> struct FormatLiteralHelper : protected BasicStaticString<Char, c...>
{template <typename... Param> std::basic_string<Char> operator()(Param&&... param) const;};
}
namespace literals
{template <typename Char, Char... c> consteval detail_::FormatLiteralHelper<Char, c...> operator""_f();}
namespace detail_
{
template <typename T> concept OptionalWrap
= SpecializationOf<T, std::optional> || SpecializationOf<T, std::shared_ptr>
|| SpecializationOf<T, std::weak_ptr> || SpecializationOf<T, std::unique_ptr>
|| SpecializationOf<T, std::experimental::observer_ptr>;
template <typename Wrap> struct UnderlyingTypeOfOptionalWrap;
template <typename Wrap> requires requires() {typename Wrap::value_type;}
struct UnderlyingTypeOfOptionalWrap<Wrap>
{using Type = std::remove_cvref_t<typename Wrap::value_type>;};
template <typename Wrap> requires requires() {typename Wrap::element_type;}
struct UnderlyingTypeOfOptionalWrap<Wrap>
{using Type = std::remove_cvref_t<typename Wrap::element_type>;};
template <typename T> struct FormatterReuseProxy
{
constexpr auto parse(fmt::format_parse_context& ctx)
-> std::invoke_result_t<decltype(&fmt::format_parse_context::begin), fmt::format_parse_context>;
};
template <typename T>
requires (!SpecializationOf<T, std::weak_ptr> && std::default_initializable<fmt::formatter<T>>)
struct FormatterReuseProxy<T> : fmt::formatter<T> {};
}
}
namespace std
{
template <typename Char, typename... Ts> requires (sizeof...(Ts) > 0) basic_ostream<Char>& operator<<
(basic_ostream<Char>& os, const variant<Ts...>& value);
}
namespace fmt
{
using namespace biu::stream_operators;
template <typename Char, biu::detail_::OptionalWrap Wrap> struct formatter<Wrap, Char>
: biu::detail_::FormatterReuseProxy<typename biu::detail_::UnderlyingTypeOfOptionalWrap<Wrap>::Type>
{
template <typename FormatContext> auto format(const Wrap& wrap, FormatContext& ctx)
-> std::invoke_result_t<decltype(&FormatContext::out), FormatContext>;
};
template <typename Char, biu::Enumerable T> struct formatter<T, Char>
{
bool full = false;
constexpr auto parse(fmt::format_parse_context& ctx)
-> std::invoke_result_t<decltype(&fmt::format_parse_context::begin), fmt::format_parse_context>;
template <typename FormatContext> auto format(const T& value, FormatContext& ctx)
-> std::invoke_result_t<decltype(&FormatContext::out), FormatContext>;
};
template <typename Char, typename... Ts> struct formatter<std::variant<Ts...>, Char>
: basic_ostream_formatter<Char> {};
}

View File

@@ -0,0 +1,122 @@
# pragma once
# include <nameof.hpp>
# include <biu/format.hpp>
namespace biu
{
template <typename Char, Char... c> template <typename... Param>
std::basic_string<Char> detail_::FormatLiteralHelper<Char, c...>::operator() (Param&&... param) const
{return fmt::format(BasicStaticString<Char, c...>::StringView, std::forward<Param>(param)...);}
template <typename Char, Char... c> consteval
detail_::FormatLiteralHelper<Char, c...> literals::operator""_f()
{return {};}
template <typename T> constexpr
auto detail_::FormatterReuseProxy<T>::parse(fmt::format_parse_context& ctx)
-> std::invoke_result_t<decltype(&fmt::format_parse_context::begin), fmt::format_parse_context>
{
if (ctx.begin() != ctx.end() && *ctx.begin() != '}')
throw fmt::format_error
(
"{} do not support to be format, so the wrapper should not have any format syntax."_f
(nameof::nameof_full_type<T>())
);
return ctx.begin();
}
}
namespace std
{
template <typename Char, typename... Ts> requires (sizeof...(Ts) > 0)
basic_ostream<Char>& operator<<(basic_ostream<Char>& os, const variant<Ts...>& value)
{
using namespace biu::literals;
auto try_print = [&]<typename T>
{
if (holds_alternative<T>(value))
{
if constexpr (biu::Formattable<T, Char>)
os << "({}: {})"_f(nameof::nameof_full_type<T>(), get<T>(value));
else
os << "({}: {})"_f(nameof::nameof_full_type<T>(), "non-null unformattable value");
}
};
(try_print.template operator()<Ts>(), ...);
return os;
}
}
namespace fmt
{
template <typename Char, biu::detail_::OptionalWrap Wrap> template <typename FormatContext>
auto formatter<Wrap, Char>::format(const Wrap& wrap, FormatContext& ctx)
-> std::invoke_result_t<decltype(&FormatContext::out), FormatContext>
{
using namespace biu::literals;
using namespace biu::stream_operators;
using value_t = biu::detail_::UnderlyingTypeOfOptionalWrap<Wrap>::Type;
auto format_value_type = [&, this](const value_t& value)
{
if constexpr (!biu::Formattable<value_t, Char>)
return format_to(ctx.out(), "non-null unformattable value");
else if constexpr (std::default_initializable<formatter<value_t>>)
biu::detail_::FormatterReuseProxy<value_t>::format(value, ctx);
else
format_to(ctx.out(), "{}", value);
};
format_to(ctx.out(), "(");
if constexpr (biu::SpecializationOf<Wrap, std::optional>)
{
if (wrap)
format_value_type(*wrap);
else
format_to(ctx.out(), "null");
}
else if constexpr (biu::SpecializationOf<Wrap, std::weak_ptr>)
{
if (auto shared = wrap.lock())
{
format_to(ctx.out(), "{} ", ptr(shared.get()));
format_value_type(*shared);
}
else
format_to(ctx.out(), "null");
}
else
{
if (wrap)
{
format_to(ctx.out(), "{} ", ptr(wrap.get()));
format_value_type(*wrap);
}
else
format_to(ctx.out(), "null");
}
return format_to(ctx.out(), ")");
}
template <typename Char, biu::Enumerable T> constexpr
auto formatter<T, Char>::parse(format_parse_context& ctx)
-> std::invoke_result_t<decltype(&format_parse_context::begin), format_parse_context>
{
auto it = ctx.begin();
if (it != ctx.end() && *it == 'f')
{
full = true;
it++;
}
if (it != ctx.end() && *it != '}')
throw format_error{"syntax error."};
return it;
}
template <typename Char, biu::Enumerable T> template <typename FormatContext>
auto formatter<T, Char>::format(const T& value, FormatContext& ctx)
-> std::invoke_result_t<decltype(&FormatContext::out), FormatContext>
{
if (full)
return format_to(ctx.out(), "{}::{}", nameof::nameof_type<T>(), nameof::nameof_enum(value));
else
return format_to(ctx.out(), "{}", nameof::nameof_enum(value));
}
}

View File

@@ -0,0 +1,103 @@
# pragma once
# include <map>
# include <boost/stacktrace.hpp>
# include <biu/atomic/nolog.hpp>
namespace biu
{
class Logger
{
// All the member function corresponding to stacktrace should be inlined
// All the public function (including public function of member class) should be thread safe.
public: Logger() = delete;
// Setup output stream and log level in a thread-safe way
public: enum class Level
{
None,
Error,
Access,
Info,
Debug
};
protected: struct LoggerConfigType_
{
std::experimental::observer_ptr<std::ostream> Stream;
std::shared_ptr<std::ostream> StreamStorage;
Logger::Level Level;
};
protected: static Atomic<std::optional<LoggerConfigType_>, false> LoggerConfig_;
public: static void init(std::experimental::observer_ptr<std::ostream> stream, Level level);
public: static void init(std::shared_ptr<std::ostream> stream, Level level);
// Send a telegram message if token and chat id are set, all the functions are thread-safe
protected: static Atomic<std::optional<std::pair<std::string, std::string>>, false> TelegramConfig_;
public: static void telegram_init(const std::string& token, const std::string& chat_id);
public: static void telegram_notify(const std::string& message);
public: static void telegram_notify_async(const std::string& message);
// Monitor the lifetime of an object
// usage: struct my_class : protected Logger::ObjectMonitor<my_class> {}
public: template <typename T> class ObjectMonitor
{
protected: const std::chrono::time_point<std::chrono::steady_clock> CreateTime_;
// call log<Debug>("create {type} at {address}.");
protected: [[gnu::always_inline]] ObjectMonitor();
// call log<Debug>("destroy {type} at {address} after {duration} ms.");
protected: [[gnu::always_inline]] virtual ~ObjectMonitor();
};
template <typename T> friend class ObjectMonitor;
// List of objects that is being monitored by ObjectMonitor, {address, type}
protected: static Atomic<std::multimap<const void*, std::string_view>, false> Objects_;
public: template <typename FinalException> class Exception : public std::exception
{
protected: const std::string Message_;
protected: const boost::stacktrace::stacktrace Stacktrace_;
public: explicit Exception(const std::string& message);
public: const char* what() const noexcept final {return Message_.c_str();}
};
// Monitor the start and end of a function, as well as corresponding thread.
// This object should be construct at the beginning of the function, and should never be passed to another
// function or thread.
public: class Guard
{
protected: thread_local static unsigned Indent_;
protected: const std::chrono::time_point<std::chrono::steady_clock> StartTime_;
// if sizeof...(Param) > 0, call log<Debug>("begin function with {arguments}.");
// else call log<Debug>("begin function.");
public: template <typename... Param> [[gnu::always_inline]] explicit Guard(Param&&... param);
// call log<Debug>("end function after {duration} ms.")
public: [[gnu::always_inline]] virtual ~Guard();
// call log<Debug>("reached after {duration} ms.")
public: [[gnu::always_inline]] void operator()() const;
// call log<Debug>("return {return} after {duration} ms.")
public: template <typename T> [[gnu::always_inline]] T rtn(T&& value) const;
// print the following message if LoggerConfig_ is set and the level is higher than the level of the
// LoggerConfig_
// [ {time} {thread} {indent} {filename}:{line} {function_name} ] {message}
public: template <Level L> [[gnu::always_inline]] void log(const std::string& message) const;
public: template <typename FinalException> [[gnu::always_inline]] void print_exception
(
const std::string& type, const std::string& message, const boost::stacktrace::stacktrace& stacktrace,
CalledBy<Exception<FinalException>>
) const;
};
friend class Guard;
// list of threads which is being monitored by Guard and number of Guard created in this thread so far
protected: static Atomic<std::map<std::size_t, std::size_t>, false> Threads_;
};
}

View File

@@ -0,0 +1,143 @@
# pragma once
# define BOOST_STACKTRACE_USE_BACKTRACE
# include <fmt/chrono.h>
# include <biu/logger.hpp>
# include <biu/common.hpp>
# include <biu/format.hpp>
namespace biu
{
template <typename T> Logger::ObjectMonitor<T>::ObjectMonitor()
: CreateTime_{std::chrono::steady_clock::now()}
{
Guard guard;
guard.log<Level::Debug>("create {} at {}."_f(nameof::nameof_full_type<T>(), fmt::ptr(this)));
auto&& lock = Objects_.lock();
lock->emplace(this, nameof::nameof_full_type<T>());
}
template <typename T> Logger::ObjectMonitor<T>::~ObjectMonitor()
{
Guard guard;
guard.log<Level::Debug>("destroy {} at {} after {} ms."_f
(
nameof::nameof_full_type<T>(), fmt::ptr(this),
std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::steady_clock::now() - CreateTime_).count()
));
auto&& lock = Objects_.lock();
auto range = lock->equal_range(this);
for (auto it = range.first; it != range.second; it++)
if (it->second == nameof::nameof_full_type<T>())
{
lock->erase(it);
return;
}
guard.log<Level::Error>
("{} {} not found in Logger::Objects."_f(fmt::ptr(this), nameof::nameof_full_type<T>()));
}
template <typename FinalException> Logger::Exception<FinalException>::Exception(const std::string& message)
{
Logger::Guard log{message};
log.print_exception(nameof::nameof_full_type<FinalException>(), message, Stacktrace_);
}
template <typename... Param> inline Logger::Guard::Guard(Param&&... param)
: StartTime_{std::chrono::steady_clock::now()}
{
Indent_++;
auto&& lock = Threads_.lock();
auto thread_id = std::hash<std::thread::id>{}(std::this_thread::get_id());
if (lock->contains(thread_id))
lock.value()[thread_id]++;
else
lock->emplace(thread_id, 1);
if constexpr (sizeof...(Param) > 0)
{
std::stringstream ss;
std::vector<std::string> params = {"{}"_f(std::forward<Param>(param))...};
ss << "begin function with {";
for (auto& param : params)
ss << param << ", ";
ss.seekp(-2, ss.cur);
ss << "}.";
log<Level::Debug>(ss.str());
}
else
log<Level::Debug>("begin function.");
}
inline Logger::Guard::~Guard()
{
log<Level::Debug>("end function after {} ms."_f(std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::steady_clock::now() - StartTime_).count()));
Indent_--;
auto&& lock = Threads_.lock();
auto thread_id = std::hash<std::thread::id>{}(std::this_thread::get_id());
if (lock->contains(thread_id))
{
lock.value()[thread_id]--;
if (lock.value()[thread_id] == 0)
lock->erase(thread_id);
}
else [[unlikely]]
log<Level::Debug>("{:08x} not found in Logger::Threads."_f
(std::hash<std::thread::id>{}(std::this_thread::get_id()) % std::numeric_limits<std::uint64_t>::max()));
}
inline void Logger::Guard::operator()() const
{
log<Level::Debug>("reached after {} ms."_f
(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - StartTime_).count()
));
}
template <typename T> inline T Logger::Guard::rtn(T&& value) const
{
log<Level::Debug>("return {} after {} ms."_f
(
std::forward<T>(value),
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - StartTime_).count()
));
return std::forward<T>(value);
}
template <Logger::Level L> inline void Logger::Guard::log(const std::string& message) const
{
if (auto&& lock = LoggerConfig_.lock(); *lock && lock.value()->Level >= L)
{
static_assert(std::same_as<std::size_t, std::uint64_t>);
auto time = std::chrono::system_clock::now();
boost::stacktrace::stacktrace stack;
*lock.value()->Stream << "[ {:%Y-%m-%d %H:%M:%S}:{:03} {:08x} {:04} {}:{} {} ] {}\n"_f
(
time,
std::chrono::time_point_cast<std::chrono::milliseconds>(time).time_since_epoch().count() % 1000,
std::hash<std::thread::id>{}(std::this_thread::get_id())
% std::numeric_limits<std::uint64_t>::max(),
Indent_,
stack[0].source_file().empty() ? "??"s : stack[0].source_file(),
stack[0].source_line() == 0 ? "??"s : "{}"_f(stack[0].source_line()),
stack[0].name(),
message
) << std::flush;
}
}
template <typename FinalException> inline void Logger::Guard::print_exception
(
const std::string& type, const std::string& message, const boost::stacktrace::stacktrace& stacktrace,
CalledBy<Exception<FinalException>>
) const
{
log<Level::Error>("{}: {}"_f(type, message));
if (auto&& lock = LoggerConfig_.lock(); *lock && lock.value()->Level >= Logger::Level::Error)
{
static_assert(std::same_as<std::size_t, std::uint64_t>);
for (auto frame : stacktrace)
*lock.value()->Stream << "\tfrom {}:{} {}\n"_f
(
frame.source_file().empty() ? "??"s : frame.source_file(),
frame.source_line() == 0 ? "??"s : "{}"_f(frame.source_line()),
frame.name()
);
*lock.value()->Stream << std::flush;
}
}
}

View File

@@ -0,0 +1,18 @@
# pragma once
# include <memory>
# include <type_traits>
namespace biu
{
// store a reference to an lvalue, or a value (instead of a reference) copy or moved from an rvalue
template <typename T> class SmartRef
{
protected: std::unique_ptr<T> Ptr_;
protected: T& Ref_;
public: SmartRef(T& val);
public: template <typename... Us> requires (std::is_constructible_v<T, Us...>) SmartRef(Us&&... val);
public: T& operator*();
public: T* operator->();
};
}

View File

@@ -0,0 +1,13 @@
# pragma once
# include <utility>
# include <biu/smartref.hpp>
namespace biu
{
template <typename T> inline SmartRef<T>::SmartRef(T& val) : Ref_(val) {}
template <typename T> template <typename... Us> requires (std::is_constructible_v<T, Us...>)
inline SmartRef<T>::SmartRef(Us&&... val)
: Ptr_(std::make_unique<T>(std::forward<Us>(val)...)), Ref_(*Ptr_) {}
template <typename T> inline T& SmartRef<T>::operator*() {return Ref_;}
template <typename T> inline T* SmartRef<T>::operator->() {return &Ref_;}
}

View File

@@ -0,0 +1,111 @@
# pragma once
# include <regex>
# include <array>
# include <string>
# include <string_view>
# include <iostream>
# include <concurrencpp/concurrencpp.h>
# include <biu/concepts.hpp>
# include <biu/smartref.hpp>
namespace biu
{
// Store a string in a static member of a class; or, use a class to represent a string.
template <DecayedType Char, Char... c> struct BasicStaticString
{
static constexpr std::array<Char, sizeof...(c)> Array{c...};
static constexpr std::basic_string_view<Char> StringView{Array.data(), sizeof...(c)};
};
template <char... c> using StaticString = BasicStaticString<char, c...>;
inline namespace stream_operators
{
template <typename Char, Char... c>
std::basic_ostream<Char>& operator<<(std::basic_ostream<Char>& os, BasicStaticString<Char, c...>);
}
inline namespace literals
{ template <typename Char, Char... c> consteval BasicStaticString<Char, c...> operator""_ss(); }
namespace detail_
{
template <typename C, typename T> struct SpecializationOfBasicStaticStringHelper : std::false_type {};
template <typename C, C... c>
struct SpecializationOfBasicStaticStringHelper<C, BasicStaticString<C, c...>> : std::true_type {};
template <typename C, C... c>
struct SpecializationOfBasicStaticStringHelper<void, BasicStaticString<C, c...>> : std::true_type {};
template <typename T, typename C> concept SpecializationOfBasicStaticString
= SpecializationOfBasicStaticStringHelper<std::decay_t<C>, std::decay_t<T>>::value;
}
template <typename T, typename C = void> concept SpecializationOfBasicStaticString
= detail_::SpecializationOfBasicStaticString<T, C>
&& detail_::SpecializationOfBasicStaticString<T, void>;
template <typename T> concept SpecializationOfStaticString = SpecializationOfBasicStaticString<T, char>;
// Store a string in a fixed-size array
template <DecayedType Char, std::size_t N> struct BasicFixedString
{
Char Data[N];
constexpr static const std::size_t Size = N - 1;
constexpr BasicFixedString(const Char (&str)[N]);
};
template <std::size_t N> using FixedString = BasicFixedString<char, N>;
inline namespace stream_operators
{
template <typename Char, std::size_t N> std::basic_ostream<Char>& operator<<
(std::basic_ostream<Char>& os, const BasicFixedString<Char, N>& str);
}
inline namespace literals { template <BasicFixedString FS> constexpr decltype(FS) operator""_fs(); }
namespace detail_
{
template <typename C, typename T> struct SpecializationOfBasicFixedStringHelper : std::false_type {};
template <typename C, std::size_t N>
struct SpecializationOfBasicFixedStringHelper<C, BasicFixedString<C, N>> : std::true_type {};
template <typename C, std::size_t N>
struct SpecializationOfBasicFixedStringHelper<void, BasicFixedString<C, N>> : std::true_type {};
template <typename T, typename C> concept SpecializationOfBasicFixedString
= SpecializationOfBasicFixedStringHelper<std::decay_t<C>, std::decay_t<T>>::value;
}
template <typename T, typename C = void> concept SpecializationOfBasicFixedString
= detail_::SpecializationOfBasicFixedString<T, C>
&& detail_::SpecializationOfBasicFixedString<T, void>;
template <typename T> concept SpecializationOfFixedString = SpecializationOfBasicFixedString<T, char>;
// Store a string with at most N characters
template <DecayedType Char, std::size_t N> struct BasicVariableString
{
Char Data[N];
std::size_t Size;
constexpr static const std::size_t MaxSize = N - 1;
template <std::size_t M> requires (M<=N) constexpr BasicVariableString(const Char (&str)[M]);
};
template <std::size_t N> using VariableString = BasicVariableString<char, N>;
inline namespace stream_operators
{
template <typename Char, std::size_t N> std::basic_ostream<Char>& operator<<
(std::basic_ostream<Char>& os, const BasicVariableString<Char, N>& str);
}
namespace detail_
{
template <typename C, typename T> struct SpecializationOfBasicVariableStringHelper : std::false_type {};
template <typename C, std::size_t N>
struct SpecializationOfBasicVariableStringHelper<C, BasicVariableString<C, N>> : std::true_type {};
template <typename C, std::size_t N>
struct SpecializationOfBasicVariableStringHelper<void, BasicVariableString<C, N>> : std::true_type {};
template <typename T, typename C> concept SpecializationOfBasicVariableString
= SpecializationOfBasicVariableStringHelper<std::decay_t<C>, std::decay_t<T>>::value;
}
template <typename T, typename C = void> concept SpecializationOfBasicVariableString
= detail_::SpecializationOfBasicVariableString<T, C>
&& detail_::SpecializationOfBasicVariableString<T, void>;
template <typename T> concept SpecializationOfVariableString = SpecializationOfBasicVariableString<T, char>;
namespace string
{
// Find specific content in a string. Return unmatched content before the match and the match result every
// time. If match reached the end, the second returned value will be std::sregex_iterator().
concurrencpp::generator<std::pair<std::string_view, std::sregex_iterator>> find
(SmartRef<const std::string> data, SmartRef<const std::regex> regex);
// Use a regex to find all matches and replace them with a callback function
std::string replace
(const std::string& data, const std::regex& regex, std::function<std::string(const std::smatch&)> function);
}
}

View File

@@ -0,0 +1,30 @@
# pragma once
# include <biu/string.hpp>
namespace biu
{
template <typename Char, Char... c> inline std::basic_ostream<Char>& stream_operators::operator<<
(std::basic_ostream<Char>& os, BasicStaticString<Char, c...>)
{ return os << std::basic_string_view{c...}; }
template <typename Char, Char... c> consteval BasicStaticString<Char, c...> literals::operator""_ss()
{ return {}; }
template <DecayedType Char, std::size_t N> constexpr
BasicFixedString<Char, N>::BasicFixedString(const Char (&str)[N])
{ std::copy_n(str, N, Data); }
template <typename Char, std::size_t N> std::basic_ostream<Char>& stream_operators::operator<<
(std::basic_ostream<Char>& os, const BasicFixedString<Char, N>& str)
{ return os << std::basic_string_view<Char>(str.Data, str.Size); }
template <BasicFixedString FS> constexpr decltype(FS) literals::operator""_fs()
{ return FS; }
template <DecayedType Char, std::size_t N> template <std::size_t M> requires (M<=N) constexpr
BasicVariableString<Char, N>::BasicVariableString(const Char (&str)[M]) : Size(M)
{
std::fill(Data, Data + N, '\0');
std::copy_n(str, M, Data);
}
template <typename Char, std::size_t N> std::basic_ostream<Char>& stream_operators::operator<<
(std::basic_ostream<Char>& os, const BasicVariableString<Char, N>& str)
{ return os << std::basic_string_view<Char>(str.Data, str.Size); }
}

View File

@@ -0,0 +1,14 @@
# include <future>
# include <utility>
# include <biu.hpp>
namespace biu
{
std::regex literals::operator""_re(const char* str, std::size_t len)
{ return std::regex{str, len}; }
void block_forever()
{
std::promise<void>().get_future().wait();
std::unreachable();
}
}

View File

@@ -0,0 +1,36 @@
# include <tgbot/tgbot.h>
# include <biu.hpp>
namespace biu
{
Atomic<std::optional<typename Logger::LoggerConfigType_>, false> Logger::LoggerConfig_;
void Logger::init(std::experimental::observer_ptr<std::ostream> stream, Level level)
{
auto&& lock = LoggerConfig_.lock();
lock->emplace(stream, nullptr, level);
}
void Logger::init(std::shared_ptr<std::ostream> stream, Level level)
{
auto&& lock = LoggerConfig_.lock();
lock->emplace(std::experimental::make_observer(stream.get()), stream, level);
}
Atomic<std::optional<std::pair<std::string, std::string>>, false> Logger::TelegramConfig_;
void Logger::telegram_init(const std::string& token, const std::string& chat_id)
{TelegramConfig_ = std::make_pair(token, chat_id);}
void Logger::telegram_notify(const std::string& message)
{
if (auto&& lock = TelegramConfig_.lock(); *lock)
{
TgBot::Bot bot{lock.value()->first};
bot.getApi().sendMessage(lock.value()->first, message);
}
}
void Logger::telegram_notify_async(const std::string& message)
{std::thread{Logger::telegram_notify, message}.detach();}
Atomic<std::multimap<const void*, std::string_view>, false> Logger::Objects_;
thread_local unsigned Logger::Guard::Indent_ = 0;
Atomic<std::map<std::size_t, std::size_t>, false> Logger::Threads_;
}

View File

@@ -0,0 +1,53 @@
# include <fmt/chrono.h>
# include <biu.hpp>
namespace biu
{
concurrencpp::generator<std::pair<std::string_view, std::sregex_iterator>> string::find
(SmartRef<const std::string> data, SmartRef<const std::regex> regex)
{
Logger::Guard log;
std::string::const_iterator unmatched_prefix_begin = data->cbegin(), unmatched_prefix_end;
std::sregex_iterator regit;
while (true)
{
if (regit == std::sregex_iterator{})
regit = std::sregex_iterator{data->begin(), data->end(), *regex};
else
regit++;
if (regit == std::sregex_iterator{})
{
unmatched_prefix_end = data->cend();
log.log<Logger::Level::Debug>("distance: {}"_f(std::distance(unmatched_prefix_begin, unmatched_prefix_end)));
}
else
unmatched_prefix_end = (*regit)[0].first;
co_yield
{
std::string_view
{
&*unmatched_prefix_begin,
static_cast<std::size_t>(std::distance(unmatched_prefix_begin, unmatched_prefix_end))
},
regit
};
if (regit == std::sregex_iterator{})
break;
unmatched_prefix_begin = (*regit)[0].second;
}
}
std::string string::replace
(const std::string& data, const std::regex& regex, std::function<std::string(const std::smatch&)> function)
{
Logger::Guard log;
std::string result;
for (auto matched : find(data, regex))
{
result.append(matched.first);
if (matched.second != std::sregex_iterator{})
result.append(function(*matched.second));
}
return result;
}
}

View File

@@ -7,8 +7,7 @@ inputs: rec
mk-meili-mgn = inputs.pkgs.callPackage ./mk-meili-mgn {};
vaspkit = inputs.pkgs.callPackage ./vaspkit { inherit (inputs.localLib) attrsToList; };
v-sim = inputs.pkgs.callPackage ./v-sim { src = inputs.topInputs.v-sim; };
concurrencpp = inputs.pkgs.callPackage ./concurrencpp
{ stdenv = inputs.pkgs.gcc13Stdenv; src = inputs.topInputs.concurrencpp; };
concurrencpp = inputs.pkgs.callPackage ./concurrencpp { src = inputs.topInputs.concurrencpp; };
eigengdb = inputs.pkgs.python3Packages.callPackage ./eigengdb {};
nodesoup = inputs.pkgs.callPackage ./nodesoup { src = inputs.topInputs.nodesoup; };
matplotplusplus = inputs.pkgs.callPackage ./matplotplusplus
@@ -21,7 +20,6 @@ inputs: rec
chromiumos-touch-keyboard = inputs.pkgs.callPackage ./chromiumos-touch-keyboard {};
yoga-support = inputs.pkgs.callPackage ./yoga-support {};
tgbot-cpp = inputs.pkgs.callPackage ./tgbot-cpp { src = inputs.topInputs.tgbot-cpp; };
biu = inputs.pkgs.callPackage ./biu { inherit concurrencpp tgbot-cpp nameof; stdenv = inputs.pkgs.gcc13Stdenv; };
citation-style-language = inputs.pkgs.callPackage ./citation-style-language
{ src = inputs.topInputs.citation-style-language; };
mirism = inputs.pkgs.callPackage ./mirism
@@ -80,6 +78,9 @@ inputs: rec
mumax = inputs.pkgs.callPackage ./mumax { src = inputs.topInputs.mumax; };
aocc = inputs.pkgs.callPackage ./aocc {};
aocl = inputs.pkgs.callPackage ./aocl {};
kylin-virtual-keyboard = inputs.pkgs.libsForQt5.callPackage ./kylin-virtual-keyboard
{ src = inputs.topInputs.kylin-virtual-keyboard; };
biu = inputs.pkgs.callPackage ./biu { inherit nameof; };
fromYaml = content: builtins.fromJSON (builtins.readFile
(inputs.pkgs.runCommand "toJSON" {}

View File

@@ -0,0 +1,17 @@
{
stdenv, src, wrapQtAppsHook,
qtbase, gsettings-qt, pkg-config, kwindowsystem, fcitx5-qt, qmake, wrapGAppsHook, glib
}: stdenv.mkDerivation
{
name = "kylin-virtual-keyboard";
inherit src;
buildInputs = [ qtbase gsettings-qt kwindowsystem fcitx5-qt ];
nativeBuildInputs = [ wrapQtAppsHook pkg-config qmake wrapGAppsHook glib ];
qmakeFlags = [ "PREFIX=/" ];
installFlags = [ "INSTALL_ROOT=$(out)" ];
postInstall =
''
mv $out/usr/* $out
rm -rf $out/usr
'';
}

View File

@@ -79,6 +79,9 @@ let
# fork to bootstrap, do not use srun, causing it could not find proper ld
export I_MPI_HYDRA_BOOTSTRAP=''${I_MPI_HYDRA_BOOTSTRAP-fork}
# set OMP_STACKSIZE if not set
export OMP_STACKSIZE=''${OMP_STACKSIZE-512M}
${additionalCommands}
${

View File

@@ -1,77 +1,75 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
options.nixos.hardware = let inherit (inputs.lib) mkOption types; in
{
bluetooth.enable = mkOption { type = types.bool; default = false; };
joystick.enable = mkOption { type = types.bool; default = false; };
printer.enable = mkOption { type = types.bool; default = false; };
sound.enable = mkOption { type = types.bool; default = false; };
bluetooth = mkOption { type = types.nullOr (types.submodule {}); default = {}; };
joystick = mkOption { type = types.nullOr (types.submodule {}); default = {}; };
printer = mkOption { type = types.nullOr (types.submodule {}); default = {}; };
sound = mkOption { type = types.nullOr (types.submodule {}); default = {}; };
cpus = mkOption { type = types.listOf (types.enum [ "intel" "amd" ]); default = []; };
};
config =
let
inherit (inputs.lib) mkMerge mkIf;
inherit (inputs.config.nixos) hardware;
inherit (builtins) listToAttrs map concatLists;
inherit (inputs.localLib) attrsToList;
in mkMerge
[
# bluetooth
(mkIf hardware.bluetooth.enable { hardware.bluetooth.enable = true; })
# joystick
(mkIf hardware.joystick.enable { hardware = { xone.enable = true; xpadneo.enable = true; }; })
# printer
(
mkIf hardware.printer.enable
config = let inherit (inputs.config.nixos) hardware; in inputs.lib.mkMerge
[
# bluetooth
(inputs.lib.mkIf (hardware.bluetooth != null) { hardware.bluetooth.enable = true; })
# joystick
(inputs.lib.mkIf (hardware.joystick != null) { hardware = { xone.enable = true; xpadneo.enable = true; }; })
# printer
(
inputs.lib.mkIf (hardware.printer != null)
{
services =
{
services =
printing =
{
printing = { enable = true; drivers = [ inputs.pkgs.cnijfilter2 ]; };
avahi = { enable = true; nssmdns = true; openFirewall = true; };
enable = true;
drivers = inputs.lib.mkIf (inputs.config.nixos.system.nixpkgs.arch == "x86_64") [ inputs.pkgs.cnijfilter2 ];
};
}
)
# sound
(
mkIf hardware.sound.enable
{
hardware.pulseaudio.enable = false;
services.pipewire = { enable = true; alsa = { enable = true; support32Bit = true; }; pulse.enable = true; };
sound.enable = true;
security.rtkit.enable = true;
environment.etc."wireplumber/main.lua.d/50-alsa-config.lua".text =
let
content = builtins.readFile
(inputs.pkgs.wireplumber + "/share/wireplumber/main.lua.d/50-alsa-config.lua");
matched = builtins.match
".*\n([[:space:]]*)(--\\[\"session\\.suspend-timeout-seconds\"][^\n]*)[\n].*" content;
spaces = builtins.elemAt matched 0;
comment = builtins.elemAt matched 1;
config = ''["session.suspend-timeout-seconds"] = 0'';
in
builtins.replaceStrings [(spaces + comment)] [(spaces + config)] content;
}
)
# cpus
(
mkIf (hardware.cpus != [])
{
hardware.cpu = listToAttrs
(map (name: { inherit name; value = { updateMicrocode = true; }; }) hardware.cpus);
boot.initrd.availableKernelModules =
let
modules =
{
intel =
[
"intel_cstate" "aesni_intel" "intel_cstate" "intel_uncore" "intel_uncore_frequency" "intel_powerclamp"
];
amd = [];
};
in
concatLists (map (cpu: modules.${cpu}) hardware.cpus);
}
)
];
avahi = { enable = true; nssmdns = true; openFirewall = true; };
};
}
)
# sound
(
inputs.lib.mkIf (hardware.sound != null)
{
hardware.pulseaudio.enable = false;
services.pipewire = { enable = true; alsa = { enable = true; support32Bit = true; }; pulse.enable = true; };
sound.enable = true;
security.rtkit.enable = true;
environment.etc."wireplumber/main.lua.d/50-alsa-config.lua".text =
let
content = builtins.readFile
(inputs.pkgs.wireplumber + "/share/wireplumber/main.lua.d/50-alsa-config.lua");
matched = builtins.match
".*\n([[:space:]]*)(--\\[\"session\\.suspend-timeout-seconds\"][^\n]*)[\n].*" content;
spaces = builtins.elemAt matched 0;
comment = builtins.elemAt matched 1;
config = ''["session.suspend-timeout-seconds"] = 0'';
in
builtins.replaceStrings [(spaces + comment)] [(spaces + config)] content;
}
)
# cpus
(
inputs.lib.mkIf (hardware.cpus != [])
{
hardware.cpu = builtins.listToAttrs
(map (name: { inherit name; value = { updateMicrocode = true; }; }) hardware.cpus);
boot.initrd.availableKernelModules =
let
modules =
{
intel =
[
"intel_cstate" "aesni_intel" "intel_cstate" "intel_uncore" "intel_uncore_frequency" "intel_powerclamp"
];
amd = [];
};
in
builtins.concatLists (map (cpu: modules.${cpu}) hardware.cpus);
}
)
];
}

View File

@@ -1,16 +1,10 @@
inputs:
{
options.nixos.hardware.legion = let inherit (inputs.lib) mkOption types; in
options.nixos.hardware.legion = let inherit (inputs.lib) mkOption types; in mkOption
{ type = types.nullOr (types.submodule {}); default = null; };
config = let inherit (inputs.config.nixos.hardware) legion; in inputs.lib.mkIf (legion != null)
{
enable = mkOption { type = types.bool; default = false; };
environment.systemPackages = [ inputs.pkgs.lenovo-legion ];
boot.extraModulePackages = [ inputs.config.boot.kernelPackages.lenovo-legion-module ];
};
config =
let
inherit (inputs.lib) mkIf;
inherit (inputs.config.nixos.hardware) legion;
in mkIf legion.enable
{
environment.systemPackages = [ inputs.pkgs.lenovo-legion ];
boot.extraModulePackages = [ inputs.config.boot.kernelPackages.lenovo-legion-module ];
};
}

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
options.nixos.packages =
let
inherit (inputs.lib) mkOption types;

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
config =
let
inherit (inputs.lib) mkIf;

View File

@@ -12,6 +12,8 @@ inputs:
{
enable = true;
extensions =
# TODO: declartive way to install extensions, with fixed xpi file
# TODO: declartively config
[
{ id = "mpkodccbngfoacfalldjimigbofkhgjn"; } # Aria2 Explorer
{ id = "nngceckbapebfimnlniiiahkandclblb"; } # Bitwarden

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
config =
let
inherit (inputs.lib) mkIf;
@@ -34,6 +34,10 @@ inputs:
localPackages.slate utterly-nord-plasma
# terminal
unstablePackages.warp-terminal
# development
adb-sync
# virtual keyboard
localPackages.kylin-virtual-keyboard
];
};
programs =

View File

@@ -9,6 +9,7 @@ inputs:
enable = true;
# TODO: switch to 24.05
# nativeMessagingHosts = [ inputs.pkgs.plasma-browser-integration ];
# TODO: switch to chromium as default browser
package = inputs.pkgs.firefox.override { nativeMessagingHosts = [ inputs.pkgs.plasma-browser-integration ]; };
policies.DefaultDownloadDirectory = "\${home}/Downloads";
profiles.default =

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
config.nixos.user.sharedModules = inputs.lib.mkIf inputs.config.nixos.system.gui.enable
[{
config.programs.plasma = inputs.lib.mkMerge

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
config =
let
inherit (inputs.lib) mkIf;
@@ -30,9 +30,9 @@ inputs:
# file manager
tree eza trash-cli lsd broot file xdg-ninja mlocate
# compress
pigz rar upx unzip zip lzip p7zip
pigz upx unzip zip lzip p7zip
# file system management
sshfs e2fsprogs adb-sync duperemove compsize exfatprogs
sshfs e2fsprogs duperemove compsize exfatprogs
# disk management
smartmontools hdparm
# encryption and authentication
@@ -44,9 +44,22 @@ inputs:
# office
todo-txt-cli pdfgrep
# development
gdb try inputs.topInputs.plasma-manager.packages.x86_64-linux.rc2nix hexo-cli gh
gdb try inputs.topInputs.plasma-manager.packages.${inputs.pkgs.system}.rc2nix hexo-cli gh
# install per project
# stdenv gfortran nodejs
# library
# fmt fmt.dev localPackages.nameof localPackages.matplotplusplus highfive hdf5 hdf5.dev
# localPackages.concurrencpp localPackages.biu localPackages.magik-enum
# (
# runCommand "concurrencpp" {}
# "mkdir $out; ln -s ${localPackages.concurrencpp}/include/concurrencpp-* $out/include"
# )
# eigen (runCommand "eigen" {} "mkdir $out; ln -s ${eigen}/include/eigen3 $out/include")
# stupid things
toilet lolcat
]
++ (with inputs.config.boot.kernelPackages; [ cpupower usbip ]);
++ (with inputs.config.boot.kernelPackages; [ cpupower usbip ])
++ (inputs.lib.optional (inputs.config.nixos.system.nixpkgs.arch == "x86_64") rar);
_pythonPackages = [(pythonPackages: with pythonPackages;
[
openai python-telegram-bot fastapi pypdf2 pandas matplotlib plotly gunicorn redis jinja2

View File

@@ -20,7 +20,9 @@ inputs:
# instant messager
qq nur-xddxdd.wechat-uos cinny-desktop nheko
# development
jetbrains.clion android-studio dbeaver cling clang-tools_16 ccls fprettify aircrack-ng
jetbrains.clion android-studio dbeaver cling fprettify aircrack-ng
# install per project
# clang-tools_16 ccls
# media
nur-xddxdd.svp
# virtualization

View File

@@ -0,0 +1,48 @@
inputs:
{
options.nixos.services.chatgpt = let inherit (inputs.lib) mkOption types; in mkOption
{
type = types.nullOr (types.submodule { options =
{
hostname = mkOption { type = types.str; default = "chat.chn.moe"; };
};});
default = null;
};
config = let inherit (inputs.config.nixos.services) chatgpt; in inputs.lib.mkIf (chatgpt != null)
{
virtualisation.oci-containers.containers.chatgpt =
{
image = "yidadaa/chatgpt-next-web:v2.11.3";
imageFile = inputs.pkgs.dockerTools.pullImage
{
imageName = "yidadaa/chatgpt-next-web";
imageDigest = "sha256:622462a7958f82e128a0e1ebd07b96e837f3d457b912fb246b550fb730b538a7";
sha256 = "00qwh1kjdchf1nhaz18s2yly2xhvpaa83ym5x4wy3z0y3vc1zwxx";
finalImageName = "yidadaa/chatgpt-next-web";
finalImageTag = "v2.11.3";
};
ports = [ "127.0.0.1:6184:3000/tcp" ];
extraOptions = [ "--add-host=host.docker.internal:host-gateway" ];
environmentFiles = [ inputs.config.sops.templates."chatgpt/env".path ];
};
sops =
{
templates."chatgpt/env".content =
''
OPENAI_API_KEY=${inputs.config.sops.placeholder."chatgpt/key"}
BASE_URL=https://oa.api2d.net
'';
secrets."chatgpt/key" = {};
};
nixos =
{
services.nginx =
{
enable = true;
https."${chatgpt.hostname}".location."/".proxy =
{ upstream = "http://127.0.0.1:6184"; detectAuth.users = [ "chat" ]; };
};
virtualization.docker.enable = true;
};
};
}

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
options.nixos.services = let inherit (inputs.lib) mkOption types; in
{
firewall.trustedInterfaces = mkOption { type = types.listOf types.nonEmptyStr; default = []; };

View File

@@ -8,11 +8,6 @@ inputs:
port = mkOption { type = types.ints.unsigned; default = 9726; };
redis.port = mkOption { type = types.ints.unsigned; default = 3545; };
hostname = mkOption { type = types.nonEmptyStr; default = "misskey.chn.moe"; };
meilisearch =
{
enable = mkOption { type = types.bool; default = true; };
port = mkOption { type = types.ints.unsigned; default = 7700; };
};
};});
default = {};
};
@@ -31,9 +26,7 @@ inputs:
{
enable = instance.value.autoStart;
description = "misskey ${instance.name}";
after = [ "network.target" "redis-misskey-${instance.name}.service" "postgresql.service" ]
++ (if instance.value.meilisearch.enable then [ "meilisearch-misskey-${instance.name}.service" ]
else []);
after = [ "network.target" "redis-misskey-${instance.name}.service" "postgresql.service" ];
requires = after;
wantedBy = [ "multi-user.target" ];
environment.MISSKEY_CONFIG_YML = inputs.config.sops.templates."misskey/${instance.name}.yml".path;
@@ -77,7 +70,6 @@ inputs:
let
placeholder = inputs.config.sops.placeholder;
redis = inputs.config.nixos.services.redis.instances."misskey-${instance.name}";
meilisearch = inputs.config.nixos.services.meilisearch.instances."misskey-${instance.name}";
in
''
url: https://${instance.value.hostname}/
@@ -105,17 +97,7 @@ inputs:
proxyRemoteFiles: true
signToActivityPubGet: true
maxFileSize: 1073741824
''
+ (if instance.value.meilisearch.enable then
''
meilisearch:
host: 127.0.0.1
port: ${toString meilisearch.port}
apiKey: ${placeholder."meilisearch/misskey-${instance.name}"}
ssl: false
index: misskey
scope: global
'' else "");
'';
owner = inputs.config.users.users."misskey-${instance.name}".name;
};
})
@@ -146,17 +128,6 @@ inputs:
(instance: { name = "misskey_${replaceStrings [ "-" ] [ "_" ] instance.name}"; value = {}; })
(attrsToList misskey.instances));
};
meilisearch.instances = listToAttrs (map
(instance:
{
name = "misskey-${instance.name}";
value =
{
user = inputs.config.users.users."misskey-${instance.name}".name;
port = instance.value.meilisearch.port;
};
})
(filter (instance: instance.value.meilisearch.enable) (attrsToList misskey.instances)));
nginx =
{
enable = mkIf (misskey.instances != {}) true;

View File

@@ -1,4 +1,4 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
}

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
options.nixos.services.nginx = let inherit (inputs.lib) mkOption types; in
{
enable = mkOption { type = types.bool; default = false; };

View File

@@ -1,27 +0,0 @@
inputs:
{
options.nixos.services.sshd = let inherit (inputs.lib) mkOption types; in
{
enable = mkOption { type = types.bool; default = false; };
passwordAuthentication = mkOption { type = types.bool; default = false; };
};
config =
let
inherit (inputs.lib) mkIf;
inherit (inputs.config.nixos.services) sshd;
in mkIf sshd.enable
{
services.openssh =
{
enable = true;
settings =
{
X11Forwarding = true;
ChallengeResponseAuthentication = false;
PasswordAuthentication = sshd.passwordAuthentication;
KbdInteractiveAuthentication = false;
UsePAM = true;
};
};
};
}

View File

@@ -0,0 +1,19 @@
                   ░▒▓█▓▒░      ░▒▓█▓▒░▒▓███████▓▒░  
                  ░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
                 ░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
                ░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
               ░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
              ░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
             ░▒▓████████▓▒░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░

      ░▒▓██████▓▒░░▒▓███████▓▒░ ░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░  
    ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
   ░▒▓█▓▒░      ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
  ░▒▓█▓▒▒▓███▓▒░▒▓███████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░  
 ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░        
░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░        
░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░░▒▓██████▓▒░ ░▒▓██████▓▒░░▒▓█▓▒░        

               ┌──────────────────────────┐
               │    │
               └──────────────────────────┘

View File

@@ -0,0 +1,19 @@
░▒▓█▓▒░ ░▒▓█▓▒░▒▓███████▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░
░▒▓████████▓▒░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░
░▒▓██████▓▒░░▒▓███████▓▒░ ░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░
░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░
░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░
░▒▓█▓▒▒▓███▓▒░▒▓███████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░
░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░
░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░░▒▓██████▓▒░ ░▒▓██████▓▒░░▒▓█▓▒░
┌──────────────────────────┐
│InAlGaN SiC│
└──────────────────────────┘

View File

@@ -0,0 +1,32 @@
inputs:
{
options.nixos.services.sshd = let inherit (inputs.lib) mkOption types; in mkOption
{
type = types.nullOr (types.submodule { options =
{
passwordAuthentication = mkOption { type = types.bool; default = false; };
groupBanner = mkOption { type = types.bool; default = false; };
};});
default = null;
};
config = let inherit (inputs.config.nixos.services) sshd; in inputs.lib.mkIf (sshd != null)
{
services.openssh =
{
enable = true;
settings =
{
X11Forwarding = true;
ChallengeResponseAuthentication = false;
PasswordAuthentication = sshd.passwordAuthentication;
KbdInteractiveAuthentication = false;
UsePAM = true;
};
};
# generate from https://patorjk.com/software/taag with font "BlurVision ASCII"
# generate using `toilet -f wideterm -F border "InAlGaN / SiC"`
# somehow lolcat could not run with these characters, use rendered directly
# TODO: move this settings to user
users.motdFile = inputs.lib.mkIf sshd.groupBanner ./banner-rendered.txt;
};
}

View File

@@ -26,7 +26,7 @@ inputs:
inherit (inputs.lib) mkIf mkMerge;
inherit (inputs.config.nixos.services) wireguard;
inherit (builtins) map toString listToAttrs filter;
in mkMerge
in mkIf wireguard.enable (mkMerge
[
{
assertions =
@@ -35,56 +35,53 @@ inputs:
message = "wireguard.listenIp should be not null when behindNat is false.";
}];
}
(
mkIf wireguard.enable
{
networking =
{
networking =
firewall = { allowedUDPPorts = [ wireguard.listenPort ]; trustedInterfaces = [ "wireguard" ]; };
wireguard.interfaces.wireguard =
{
firewall = { allowedUDPPorts = [ wireguard.listenPort ]; trustedInterfaces = [ "wireguard" ]; };
wireguard.interfaces.wireguard =
{
ips = [ "${wireguard.wireguardIp}/24" ];
inherit (wireguard) listenPort;
privateKeyFile = inputs.config.sops.secrets."wireguard/privateKey".path;
peers = map
(peer:
{
publicKey = peer.publicKey;
allowedIPs = [ (if peer.lighthouse then "192.168.83.0/24" else "${peer.wireguardIp}/32") ];
endpoint = mkIf (!peer.behindNat) "${peer.listenIp}:${builtins.toString peer.listenPort}";
persistentKeepalive = mkIf peer.lighthouse 5;
})
(map
(peer: inputs.topInputs.self.nixosConfigurations.${peer}.config.nixos.services.wireguard)
wireguard.peers);
};
};
sops.secrets."wireguard/privateKey" = {};
# somehow fix wireguard connection
systemd.services = mkIf wireguard.behindNat (listToAttrs (map
(peer:
{
name = "wireguard-ping-${peer.name}";
value =
{
description = "ping ${peer.name}";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig =
{
ExecStart = "${inputs.pkgs.iputils}/bin/ping -i 5 ${peer.value.wireguardIp}";
Restart = "always";
};
};
})
(filter (peer: !peer.value.behindNat) (map
ips = [ "${wireguard.wireguardIp}/24" ];
inherit (wireguard) listenPort;
privateKeyFile = inputs.config.sops.secrets."wireguard/privateKey".path;
peers = map
(peer:
{
name = peer;
value = inputs.topInputs.self.nixosConfigurations.${peer}.config.nixos.services.wireguard;
publicKey = peer.publicKey;
allowedIPs = [ (if peer.lighthouse then "192.168.83.0/24" else "${peer.wireguardIp}/32") ];
endpoint = mkIf (!peer.behindNat) "${peer.listenIp}:${builtins.toString peer.listenPort}";
persistentKeepalive = mkIf peer.lighthouse 5;
})
wireguard.peers))));
}
)
];
(map
(peer: inputs.topInputs.self.nixosConfigurations.${peer}.config.nixos.services.wireguard)
wireguard.peers);
};
};
sops.secrets."wireguard/privateKey" = {};
# somehow fix wireguard connection
systemd.services = mkIf wireguard.behindNat (listToAttrs (map
(peer:
{
name = "wireguard-ping-${peer.name}";
value =
{
description = "ping ${peer.name}";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig =
{
ExecStart = "${inputs.pkgs.iputils}/bin/ping -i 5 ${peer.value.wireguardIp}";
Restart = "always";
};
};
})
(filter (peer: !peer.value.behindNat) (map
(peer:
{
name = peer;
value = inputs.topInputs.self.nixosConfigurations.${peer}.config.nixos.services.wireguard;
})
wireguard.peers))));
}
]);
}

View File

@@ -75,7 +75,7 @@ inputs:
dae =
{
enable = true;
package = inputs.pkgs.callPackage "${inputs.topInputs.nixpkgs-unstable}/pkgs/tools/networking/dae" {};
# package = inputs.pkgs.callPackage "${inputs.topInputs.nixpkgs-unstable}/pkgs/tools/networking/dae" {};
config =
let
lanString = (inputs.lib.optionalString (xray.client.dae.lanInterfaces != []) "lan_interface: ")

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
config =
{
services = { dbus.implementation = "broker"; fstrim.enable = true; acpid.enable = true; };
@@ -29,14 +29,17 @@ inputs:
MATHEMATICA_USERBASE = "${XDG_CONFIG_HOME}/mathematica";
_JAVA_OPTIONS = "-Djava.util.prefs.userRoot=${XDG_CONFIG_HOME}/java";
};
variables.NIXOS_CONFIGURATION_REVISION = inputs.config.system.configurationRevision;
variables =
{
NIXOS_CONFIGURATION_REVISION = inputs.config.system.configurationRevision;
# CPATH = "/run/current-system/sw/include";
# LIBRARY_PATH = "/run/current-system/sw/lib";
};
# pathsToLink = [ "/include" ];
};
i18n =
{ defaultLocale = "C.UTF-8"; supportedLocales = [ "zh_CN.UTF-8/UTF-8" "en_US.UTF-8/UTF-8" "C.UTF-8/UTF-8" ]; };
users.mutableUsers = false;
# environment.pathsToLink = [ "/include" ];
# environment.variables.CPATH = "/run/current-system/sw/include";
# environment.variables.LIBRARY_PATH = "/run/current-system/sw/lib";
virtualisation.oci-containers.backend = "docker";
home-manager.sharedModules = [{ home.stateVersion = "22.11"; }];
system =

View File

@@ -1,7 +1,10 @@
inputs:
{
options.nixos.system.envfs = let inherit (inputs.lib) mkOption types; in mkOption
{ type = types.nullOr (types.submodule {}); default = {}; };
{
type = types.nullOr (types.submodule {});
default = if inputs.config.nixos.packages.packageSet == "workstation" then {} else null;
};
config = let inherit (inputs.config.nixos.system) envfs; in inputs.lib.mkIf (envfs != null) (inputs.lib.mkMerge
[
(builtins.elemAt inputs.topInputs.envfs.nixosModules.envfs.imports 0 inputs)

View File

@@ -34,7 +34,7 @@ inputs:
{
boot.loader.grub =
{
memtest86.enable = true;
memtest86.enable = inputs.lib.mkIf (inputs.config.nixos.system.nixpkgs.arch == "x86_64") true;
extraFiles = inputs.lib.mkIf (builtins.elem grub.installDevice [ "efi" "efiRemovable" ])
{ "shell.efi" = "${inputs.pkgs.edk2-uefi-shell}/shell.efi"; };
extraEntries = inputs.lib.mkMerge (builtins.concatLists

View File

@@ -4,7 +4,7 @@ inputs:
{
varient = mkOption
{
type = types.enum [ "xanmod-lts" "xanmod-latest" "cachyos" "cachyos-lto" ];
type = types.enum [ "nixos" "xanmod-lts" "xanmod-latest" "cachyos" "cachyos-lto" ];
default = "xanmod-lts";
};
patches = mkOption { type = types.listOf types.nonEmptyStr; default = []; };
@@ -25,21 +25,27 @@ inputs:
# modprobe --show-depends
initrd.availableKernelModules =
[
"ahci" "ata_piix" "bfq" "failover" "net_failover" "nls_cp437" "nls_iso8859-1" "nvme" "sdhci_acpi" "sd_mod"
"bfq" "failover" "net_failover" "nls_cp437" "nls_iso8859-1" "sd_mod"
"sr_mod" "usbcore" "usbhid" "usbip-core" "usb-common" "usb_storage" "vhci-hcd" "virtio" "virtio_blk"
"virtio_net" "virtio_pci" "xhci_pci" "virtio_ring" "virtio_scsi" "cryptd" "crypto_simd" "libaes"
"virtio_net" "virtio_ring" "virtio_scsi" "cryptd" "libaes"
"ahci" "ata_piix" "nvme" "sdhci_acpi" "virtio_pci" "xhci_pci"
# networking for nas
"igb"
];
]
++ (inputs.lib.optionals (kernel.varient != "nixos") [ "crypto_simd" ])
# for pi3b to show message over hdmi while boot
++ (inputs.lib.optionals (kernel.varient == "nixos") [ "vc4" "bcm2835_dma" "i2c_bcm2835" ]);
extraModulePackages = (with inputs.config.boot.kernelPackages; [ v4l2loopback ]) ++ kernel.modules.install;
extraModprobeConfig = builtins.concatStringsSep "\n" kernel.modules.modprobeConfig;
kernelParams = [ "delayacct" "acpi_osi=Linux" "acpi.ec_no_wakeup=1" ];
kernelPackages =
{
nixos = inputs.pkgs.linuxPackages;
xanmod-lts = inputs.pkgs.linuxPackages_xanmod;
xanmod-latest = inputs.pkgs.linuxPackages_xanmod_latest;
cachyos = inputs.pkgs.linuxPackages_cachyos;
cachyos-lto = inputs.pkgs.linuxPackages_cachyos-lto;
rpi3 = inputs.pkgs.linuxPackages_rpi3;
}.${kernel.varient};
kernelPatches =
let
@@ -148,5 +154,9 @@ inputs:
in { environment.systemPackages = [ scx ]; }
)
)
(
inputs.lib.mkIf (kernel.varient == "rpi3")
{ boot.initrd = { systemd.enableTpm2 = false; includeDefaultModules = false; }; }
)
];
}

12
modules/system/nix-ld.nix Normal file
View File

@@ -0,0 +1,12 @@
inputs:
{
options.nixos.system.nix-ld = let inherit (inputs.lib) mkOption types; in mkOption
{
type = types.nullOr (types.submodule {});
default = if inputs.config.nixos.packages.packageSet == "workstation" then {} else null;
};
config = let inherit (inputs.config.nixos.system) nix-ld; in inputs.lib.mkIf (nix-ld != null)
{
programs.nix-ld = { enable = true; libraries = [ inputs.pkgs.steam-run.fhsenv ]; };
};
}

View File

@@ -2,6 +2,7 @@ inputs:
{
options.nixos.system.nixpkgs = let inherit (inputs.lib) mkOption types; in
{
arch = mkOption { type = types.enum [ "x86_64" "aarch64" ]; default = "x86_64"; };
march = mkOption { type = types.nullOr types.nonEmptyStr; default = null; };
cuda =
{
@@ -24,8 +25,8 @@ inputs:
permittedInsecurePackages =
[ "openssl_1_1" "electron_19" "python2" "electron_12" "electron_24" "zotero" "electron_25" ];
hostPlatform = if nixpkgs.march != null
then { system = "x86_64-linux"; gcc = { arch = nixpkgs.march; tune = nixpkgs.march; }; }
else "x86_64-linux";
then { system = "${nixpkgs.arch}-linux"; gcc = { arch = nixpkgs.march; tune = nixpkgs.march; }; }
else "${nixpkgs.arch}-linux";
cudaConfig = inputs.lib.optionalAttrs nixpkgs.cuda.enable
(
{ cudaSupport = true; }
@@ -54,13 +55,14 @@ inputs:
overlays =
[(final: prev:
let
inherit (final) system;
genericPackages = import inputs.topInputs.nixpkgs
{
system = "x86_64-linux";
inherit system;
config =
{
allowUnfree = true;
permittedInsecurePackages = let pkgs = inputs.topInputs.nixpkgs.legacyPackages.x86_64-linux; in map
permittedInsecurePackages = let pkgs = inputs.topInputs.nixpkgs.legacyPackages.${system}; in map
(package: pkgs.${package}.name)
(filter (package: pkgs ? ${package}) permittedInsecurePackages);
};
@@ -83,7 +85,7 @@ inputs:
{
allowUnfree = true;
permittedInsecurePackages =
let pkgs = inputs.topInputs.${source.${name}}.legacyPackages.x86_64-linux;
let pkgs = inputs.topInputs.${source.${name}}.legacyPackages.${system};
in map
(package: pkgs.${package}.name)
(filter (package: pkgs ? ${package}) permittedInsecurePackages);

View File

@@ -14,7 +14,16 @@ inputs:
sops =
{
defaultSopsFile =
"${inputs.topInputs.self}/devices/${inputs.config.nixos.system.networking.hostname}/secrets/default.yaml";
let deviceDir = "${inputs.topInputs.self}/devices/${inputs.config.nixos.system.networking.hostname}";
in mkIf
(
builtins.pathExists "${deviceDir}/secrets.yaml"
|| builtins.pathExists "${deviceDir}/secrets/default.yaml"
)
(
if builtins.pathExists "${deviceDir}/secrets.yaml" then "${deviceDir}/secrets.yaml"
else "${deviceDir}/secrets/default.yaml"
);
# sops start before impermanence, so we need to use the absolute path
age.sshKeyPaths = [ "${sops.keyPathPrefix}/etc/ssh/ssh_host_ed25519_key" ];
gnupg.sshKeyPaths = [ "${sops.keyPathPrefix}/etc/ssh/ssh_host_rsa_key" ];

View File

@@ -4,21 +4,17 @@ inputs:
{
laptop-mode = mkOption { type = types.nullOr types.int; default = null; };
};
config =
let
inherit (inputs.lib) mkIf mkMerge;
inherit (inputs.config.nixos.system) sysctl;
in mkMerge
[
config = let inherit (inputs.config.nixos.system) sysctl; in inputs.lib.mkMerge
[
{
boot.kernel.sysctl =
{
boot.kernel.sysctl =
{
"vm.oom_kill_allocating_task" = true;
"vm.oom_dump_tasks" = false;
"vm.overcommit_memory" = 1;
"kernel.sysrq" = 438;
};
}
(mkIf (sysctl.laptop-mode != null) { boot.kernel.sysctl."vm.laptop_mode" = sysctl.laptop-mode; })
];
"vm.oom_kill_allocating_task" = true;
"vm.oom_dump_tasks" = false;
"vm.overcommit_memory" = 1;
"kernel.sysrq" = 438;
};
}
(inputs.lib.mkIf (sysctl.laptop-mode != null) { boot.kernel.sysctl."vm.laptop_mode" = sysctl.laptop-mode; })
];
}

View File

@@ -1,19 +1,22 @@
inputs: { config =
inputs:
{
# only preserve the last 7 days of logs
services.journald.extraConfig = "MaxRetentionSec=7d";
systemd =
config =
{
extraConfig =
''
DefaultTimeoutStopSec=10s
DefaultLimitNOFILE=1048576:1048576
'';
user.extraConfig = "DefaultTimeoutStopSec=10s";
# do not create /var/lib/machines and /var/lib/portables as subvolumes
services.systemd-tmpfiles-setup.environment.SYSTEMD_TMPFILES_FORCE_SUBVOL = "0";
# do not clean /tmp
timers.systemd-tmpfiles-clean.enable = false;
coredump = { enable = true; extraConfig = "Storage=none"; };
# only preserve the last 7 days of logs
services.journald.extraConfig = "MaxRetentionSec=7d";
systemd =
{
extraConfig =
''
DefaultTimeoutStopSec=10s
DefaultLimitNOFILE=1048576:1048576
'';
user.extraConfig = "DefaultTimeoutStopSec=10s";
# do not create /var/lib/machines and /var/lib/portables as subvolumes
services.systemd-tmpfiles-setup.environment.SYSTEMD_TMPFILES_FORCE_SUBVOL = "0";
# do not clean /tmp
timers.systemd-tmpfiles-clean.enable = false;
coredump = { enable = true; extraConfig = "Storage=none"; };
};
};
};}
}

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
config =
let
inherit (inputs.lib) mkIf;

View File

@@ -1,4 +1,4 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
}

View File

@@ -1,13 +1,20 @@
inputs:
{
config.home-manager.users.chn.config.programs.plasma.configFile =
let wallpaper = "${./pixiv-96734339-x2.png}"; in
let wallpaper =
{
pc = ./pixiv-117612023.png;
surface = ./misskey.io-9rr96ml6nti300ds-x4.png;
}.${inputs.config.nixos.system.networking.hostname} or ./pixiv-96734339-x2.png;
in
{
"plasma-org.kde.plasma.desktop-appletsrc" =
{
"Containments.1".wallpaperplugin = "a2n.blur";
"Containments.1.Wallpaper.a2n\\.blur.General".Image = wallpaper;
"Containments.1.Wallpaper.a2n\\.blur.General".Image = "${wallpaper}";
};
kscreenlockerrc."Greeter.Wallpaper.org\\.kde\\.image.General" = { Image = wallpaper; PreviewImage = wallpaper; };
kscreenlockerrc."Greeter.Wallpaper.org\\.kde\\.image.General" =
{ Image = "${wallpaper}"; PreviewImage = "${wallpaper}"; };
kdeglobals.General.accentColorFromWallpaper = true;
};
}

Binary file not shown.

Binary file not shown.

View File

@@ -1,6 +1,6 @@
inputs:
{
imports = inputs.localLib.mkModules (inputs.localLib.findModules ./.);
imports = inputs.localLib.findModules ./.;
options.nixos.user = let inherit (inputs.lib) mkOption types; in
{
users = mkOption { type = types.listOf types.nonEmptyStr; default = [ "chn" ]; };

View File

@@ -68,6 +68,7 @@ inputs:
onBoot = "ignore";
onShutdown = "shutdown";
parallelShutdown = 4;
qemu.ovmf.packages = with inputs.pkgs; [ OVMF.fd pkgsCross.aarch64-multiplatform.OVMFFull.fd ];
};
spiceUSBRedirection.enable = true;
};