diff --git a/.editorconfig b/.editorconfig index 4753adb..ec1575b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + [*] end_of_line = lf insert_final_newline = true diff --git a/.gitignore b/.gitignore index ea8c4bf..de75ea9 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + /target diff --git a/Cargo.lock b/Cargo.lock index cba4ce7..fabdb82 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,6 +73,17 @@ version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" +[[package]] +name = "bstr" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" +dependencies = [ + "memchr", + "regex-automata", + "serde", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -86,10 +97,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] -name = "clap" -version = "4.5.58" +name = "circular-buffer" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63be97961acde393029492ce0be7a1af7e323e6bae9511ebfac33751be5e6806" +checksum = "14c638459986b83c2b885179bd4ea6a2cbb05697b001501a56adb3a3d230803b" + +[[package]] +name = "clap" +version = "4.5.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a" dependencies = [ "clap_builder", "clap_derive", @@ -97,9 +114,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.58" +version = "4.5.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f13174bda5dfd69d7e947827e5af4b0f2f94a4a3ee92912fba07a66150f21e2" +checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876" dependencies = [ "anstream", "anstyle", @@ -143,6 +160,23 @@ dependencies = [ "utf8-command", ] +[[package]] +name = "const-str" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18f12cc9948ed9604230cdddc7c86e270f9401ccbe3c2e98a4378c5e7632212f" + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "dyn-clone" version = "1.0.20" @@ -153,15 +187,23 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" name = "dynix" version = "0.1.0" dependencies = [ + "bitflags", + "bstr", + "circular-buffer", "clap", "command-error", + "const-str", + "displaydoc", "fs-err", "itertools", "libc", + "mio", "regex", "regex-lite", + "rustix", "serde", "serde_json", + "sync-fd", "tap", "tracing", "tracing-human-layer", @@ -273,15 +315,15 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.182" +version = "0.2.183" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" +checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" [[package]] name = "linux-raw-sys" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "lock_api" @@ -313,6 +355,18 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "nix" version = "0.30.1" @@ -348,9 +402,9 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "owo-colors" -version = "4.2.3" +version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52" +checksum = "d211803b9b6b570f68772237e415a029d5a50c65d382910b879fb19d3271f94d" dependencies = [ "supports-color 2.1.0", "supports-color 3.0.2", @@ -381,9 +435,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "proc-macro2" @@ -408,9 +462,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.44" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] @@ -455,15 +509,15 @@ checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" [[package]] name = "regex-syntax" -version = "0.8.9" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" [[package]] name = "rustix" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ "bitflags", "errno", @@ -575,15 +629,24 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.116" +version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "sync-fd" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5666edb8017247cac3f25fe3f2a8c889177d8adda7ce7d29a1f7278e2858aee2" +dependencies = [ + "libc", +] + [[package]] name = "tap" version = "1.0.1" @@ -733,6 +796,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "windows" version = "0.61.3" diff --git a/Cargo.lock.license b/Cargo.lock.license new file mode 100644 index 0000000..39b098c --- /dev/null +++ b/Cargo.lock.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2026 Qyriad + +SPDX-License-Identifier: EUPL-1.1 diff --git a/Cargo.toml b/Cargo.toml index 2e6dd55..ed6bd37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,12 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + [package] name = "dynix" version = "0.1.0" edition = "2024" +license = "EUPL-1.2" [[bin]] name = "dynix" @@ -17,15 +22,24 @@ regex-full = ["dep:regex"] regex-lite = ["dep:regex-lite"] [dependencies] +bitflags = { version = "2.11.0", features = ["std"] } +bstr = "1.12.1" +circular-buffer = "1.2.0" clap = { version = "4.5.54", features = ["color", "derive"] } command-error = "0.8.0" +const-str = "1.1.0" +displaydoc = "0.2.5" fs-err = "3.2.2" itertools = "0.14.0" libc = { version = "0.2.180", features = ["extra_traits"] } +#macro_rules_attribute = { version = "0.2.2", features = ["better-docs", "verbose-expansions"] } +mio = { version = "1.1.1", features = ["os-ext", "os-poll", "net"] } regex = { version = "1.12.3", optional = true } regex-lite = { version = "0.1.9", optional = true } -serde = { version = "1.0.228", features = ["derive"] } +rustix = { version = "1.1.4", features = ["event", "fs", "net", "process", "termios"] } +serde = { version = "1.0.228", features = ["derive", "rc"] } serde_json = "1.0.149" +sync-fd = "0.1.0" tap = "1.0.1" tracing = { version = "0.1.44", features = ["attributes"] } tracing-human-layer = "0.2.1" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4153cd3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,287 @@ + EUROPEAN UNION PUBLIC LICENCE v. 1.2 + EUPL © the European Union 2007, 2016 + +This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined +below) which is provided under the terms of this Licence. Any use of the Work, +other than as authorised under this Licence is prohibited (to the extent such +use is covered by a right of the copyright holder of the Work). + +The Work is provided under the terms of this Licence when the Licensor (as +defined below) has placed the following notice immediately following the +copyright notice for the Work: + + Licensed under the EUPL + +or has expressed by any other means his willingness to license under the EUPL. + +1. Definitions + +In this Licence, the following terms have the following meaning: + +- ‘The Licence’: this Licence. + +- ‘The Original Work’: the work or software distributed or communicated by the + Licensor under this Licence, available as Source Code and also as Executable + Code as the case may be. + +- ‘Derivative Works’: the works or software that could be created by the + Licensee, based upon the Original Work or modifications thereof. This Licence + does not define the extent of modification or dependence on the Original Work + required in order to classify a work as a Derivative Work; this extent is + determined by copyright law applicable in the country mentioned in Article 15. + +- ‘The Work’: the Original Work or its Derivative Works. + +- ‘The Source Code’: the human-readable form of the Work which is the most + convenient for people to study and modify. + +- ‘The Executable Code’: any code which has generally been compiled and which is + meant to be interpreted by a computer as a program. + +- ‘The Licensor’: the natural or legal person that distributes or communicates + the Work under the Licence. + +- ‘Contributor(s)’: any natural or legal person who modifies the Work under the + Licence, or otherwise contributes to the creation of a Derivative Work. + +- ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of + the Work under the terms of the Licence. + +- ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, + renting, distributing, communicating, transmitting, or otherwise making + available, online or offline, copies of the Work or providing access to its + essential functionalities at the disposal of any other natural or legal + person. + +2. Scope of the rights granted by the Licence + +The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, +sublicensable licence to do the following, for the duration of copyright vested +in the Original Work: + +- use the Work in any circumstance and for all usage, +- reproduce the Work, +- modify the Work, and make Derivative Works based upon the Work, +- communicate to the public, including the right to make available or display + the Work or copies thereof to the public and perform publicly, as the case may + be, the Work, +- distribute the Work or copies thereof, +- lend and rent the Work or copies thereof, +- sublicense rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now +known or later invented, as far as the applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to +exercise his moral right to the extent allowed by law in order to make effective +the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to +any patents held by the Licensor, to the extent necessary to make use of the +rights granted on the Work under this Licence. + +3. Communication of the Source Code + +The Licensor may provide the Work either in its Source Code form, or as +Executable Code. If the Work is provided as Executable Code, the Licensor +provides in addition a machine-readable copy of the Source Code of the Work +along with each copy of the Work that the Licensor distributes or indicates, in +a notice following the copyright notice attached to the Work, a repository where +the Source Code is easily and freely accessible for as long as the Licensor +continues to distribute or communicate the Work. + +4. Limitations on copyright + +Nothing in this Licence is intended to deprive the Licensee of the benefits from +any exception or limitation to the exclusive rights of the rights owners in the +Work, of the exhaustion of those rights or of other applicable limitations +thereto. + +5. Obligations of the Licensee + +The grant of the rights mentioned above is subject to some restrictions and +obligations imposed on the Licensee. Those obligations are the following: + +Attribution right: The Licensee shall keep intact all copyright, patent or +trademarks notices and all notices that refer to the Licence and to the +disclaimer of warranties. The Licensee must include a copy of such notices and a +copy of the Licence with every copy of the Work he/she distributes or +communicates. The Licensee must cause any Derivative Work to carry prominent +notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes or communicates copies of the +Original Works or Derivative Works, this Distribution or Communication will be +done under the terms of this Licence or of a later version of this Licence +unless the Original Work is expressly distributed only under this version of the +Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee +(becoming Licensor) cannot offer or impose any additional terms or conditions on +the Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes or Communicates Derivative +Works or copies thereof based upon both the Work and another work licensed under +a Compatible Licence, this Distribution or Communication can be done under the +terms of this Compatible Licence. For the sake of this clause, ‘Compatible +Licence’ refers to the licences listed in the appendix attached to this Licence. +Should the Licensee's obligations under the Compatible Licence conflict with +his/her obligations under this Licence, the obligations of the Compatible +Licence shall prevail. + +Provision of Source Code: When distributing or communicating copies of the Work, +the Licensee will provide a machine-readable copy of the Source Code or indicate +a repository where this Source will be easily and freely available for as long +as the Licensee continues to distribute or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, +trademarks, service marks, or names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the copyright notice. + +6. Chain of Authorship + +The original Licensor warrants that the copyright in the Original Work granted +hereunder is owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings +to the Work are owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent +Contributors grant You a licence to their contributions to the Work, under the +terms of this Licence. + +7. Disclaimer of Warranty + +The Work is a work in progress, which is continuously improved by numerous +Contributors. It is not a finished work and may therefore contain defects or +‘bugs’ inherent to this type of development. + +For the above reason, the Work is provided under the Licence on an ‘as is’ basis +and without warranties of any kind concerning the Work, including without +limitation merchantability, fitness for a particular purpose, absence of defects +or errors, accuracy, non-infringement of intellectual property rights other than +copyright as stated in Article 6 of this Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition +for the grant of any rights to the Work. + +8. Disclaimer of Liability + +Except in the cases of wilful misconduct or damages directly caused to natural +persons, the Licensor will in no event be liable for any direct or indirect, +material or moral, damages of any kind, arising out of the Licence or of the use +of the Work, including without limitation, damages for loss of goodwill, work +stoppage, computer failure or malfunction, loss of data or any commercial +damage, even if the Licensor has been advised of the possibility of such damage. +However, the Licensor will be liable under statutory product liability laws as +far such laws apply to the Work. + +9. Additional agreements + +While distributing the Work, You may choose to conclude an additional agreement, +defining obligations or services consistent with this Licence. However, if +accepting obligations, You may act only on your own behalf and on your sole +responsibility, not on behalf of the original Licensor or any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor harmless +for any liability incurred by, or claims asserted against such Contributor by +the fact You have accepted any warranty or additional liability. + +10. Acceptance of the Licence + +The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ +placed under the bottom of a window displaying the text of this Licence or by +affirming consent in any other similar way, in accordance with the rules of +applicable law. Clicking on that icon indicates your clear and irrevocable +acceptance of this Licence and all of its terms and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and +conditions by exercising any rights granted to You by Article 2 of this Licence, +such as the use of the Work, the creation by You of a Derivative Work or the +Distribution or Communication by You of the Work or copies thereof. + +11. Information to the public + +In case of any Distribution or Communication of the Work by means of electronic +communication by You (for example, by offering to download the Work from a +remote location) the distribution channel or media (for example, a website) must +at least provide to the public the information requested by the applicable law +regarding the Licensor, the Licence and the way it may be accessible, concluded, +stored and reproduced by the Licensee. + +12. Termination of the Licence + +The Licence and the rights granted hereunder will terminate automatically upon +any breach by the Licensee of the terms of the Licence. + +Such a termination will not terminate the licences of any person who has +received the Work from the Licensee under the Licence, provided such persons +remain in full compliance with the Licence. + +13. Miscellaneous + +Without prejudice of Article 9 above, the Licence represents the complete +agreement between the Parties as to the Work. + +If any provision of the Licence is invalid or unenforceable under applicable +law, this will not affect the validity or enforceability of the Licence as a +whole. Such provision will be construed or reformed so as necessary to make it +valid and enforceable. + +The European Commission may publish other linguistic versions or new versions of +this Licence or updated versions of the Appendix, so far this is required and +reasonable, without reducing the scope of the rights granted by the Licence. New +versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, +have identical value. Parties can take advantage of the linguistic version of +their choice. + +14. Jurisdiction + +Without prejudice to specific agreement between parties, + +- any litigation resulting from the interpretation of this License, arising + between the European Union institutions, bodies, offices or agencies, as a + Licensor, and any Licensee, will be subject to the jurisdiction of the Court + of Justice of the European Union, as laid down in article 272 of the Treaty on + the Functioning of the European Union, + +- any litigation arising between other parties and resulting from the + interpretation of this License, will be subject to the exclusive jurisdiction + of the competent court where the Licensor resides or conducts its primary + business. + +15. Applicable Law + +Without prejudice to specific agreement between parties, + +- this Licence shall be governed by the law of the European Union Member State + where the Licensor has his seat, resides or has his registered office, + +- this licence shall be governed by Belgian law if the Licensor has no seat, + residence or registered office inside a European Union Member State. + +Appendix + +‘Compatible Licences’ according to Article 5 EUPL are: + +- GNU General Public License (GPL) v. 2, v. 3 +- GNU Affero General Public License (AGPL) v. 3 +- Open Software License (OSL) v. 2.1, v. 3.0 +- Eclipse Public License (EPL) v. 1.0 +- CeCILL v. 2.0, v. 2.1 +- Mozilla Public Licence (MPL) v. 2 +- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 +- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for + works other than software +- European Union Public Licence (EUPL) v. 1.1, v. 1.2 +- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong + Reciprocity (LiLiQ-R+). + +The European Commission may update this Appendix to later versions of the above +licences without producing a new version of the EUPL, as long as they provide +the rights granted in Article 2 of this Licence and protect the covered Source +Code from exclusive appropriation. + +All other changes or additions to this Appendix require the production of a new +EUPL version. diff --git a/LICENSES/EUPL-1.1.txt b/LICENSES/EUPL-1.1.txt new file mode 100644 index 0000000..3e0d612 --- /dev/null +++ b/LICENSES/EUPL-1.1.txt @@ -0,0 +1,157 @@ +European Union Public Licence V. 1.1 + +EUPL (c) the European Community 2007 + +This European Union Public Licence (the "EUPL") applies to the Work or Software (as defined below) which is provided under the terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such use is covered by a right of the copyright holder of the Work). + +The Original Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following notice immediately following the copyright notice for the Original Work: + + Licensed under the EUPL V.1.1 + +or has expressed by any other mean his willingness to license under the EUPL. + +1. Definitions + +In this Licence, the following terms have the following meaning: + + - The Licence: this Licence. + + - The Original Work or the Software: the software distributed and/or communicated by the Licensor under this Licence, available as Source Code and also as Executable Code as the case may be. + + - Derivative Works: the works or software that could be created by the Licensee, based upon the Original Work or modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in the country mentioned in Article 15. + + - The Work: the Original Work and/or its Derivative Works. + + - The Source Code: the human-readable form of the Work which is the most convenient for people to study and modify. + + - The Executable Code: any code which has generally been compiled and which is meant to be interpreted by a computer as a program. + + - The Licensor: the natural or legal person that distributes and/or communicates the Work under the Licence. + + - Contributor(s): any natural or legal person who modifies the Work under the Licence, or otherwise contributes to the creation of a Derivative Work. + + - The Licensee or "You": any natural or legal person who makes any usage of the Software under the terms of the Licence. + + - Distribution and/or Communication: any act of selling, giving, lending, renting, distributing, communicating, transmitting, or otherwise making available, on-line or off-line, copies of the Work or providing access to its essential functionalities at the disposal of any other natural or legal person. + +2. Scope of the rights granted by the Licence + +The Licensor hereby grants You a world-wide, royalty-free, non-exclusive, sublicensable licence to do the following, for the duration of copyright vested in the Original Work: + + - use the Work in any circumstance and for all usage, + + - reproduce the Work, + + - modify the Original Work, and make Derivative Works based upon the Work, + + - communicate to the public, including the right to make available or display the Work or copies thereof to the public and perform publicly, as the case may be, the Work, + + - distribute the Work or copies thereof, + + - lend and rent the Work or copies thereof, + + - sub-license rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed by law in order to make effective the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non exclusive usage rights to any patents held by the Licensor, to the extent necessary to make use of the rights granted on the Work under this Licence. + +3. Communication of the Source Code + +The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to distribute and/or communicate the Work. + +4. Limitations on copyright + +Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the exclusive rights of the rights owners in the Original Work or Software, of the exhaustion of those rights or of other applicable limitations thereto. + +5. Obligations of the Licensee + +The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those obligations are the following: + +Attribution right: the Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the Licence with every copy of the Work he/she distributes and/or communicates. The Licensee must cause any Derivative Work to carry prominent notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes and/or communicates copies of the Original Works or Derivative Works based upon the Original Work, this Distribution and/or Communication will be done under the terms of this Licence or of a later version of this Licence unless the Original Work is expressly distributed only under this version of the Licence. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes and/or Communicates Derivative Works or copies thereof based upon both the Original Work and another work licensed under a Compatible Licence, this Distribution and/or Communication can be done under the terms of this Compatible Licence. For the sake of this clause, "Compatible Licence," refers to the licences listed in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail. + +Provision of Source Code: When distributing and/or communicating copies of the Work, the Licensee will provide a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available for as long as the Licensee continues to distribute and/or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the copyright notice. + +6. Chain of Authorship + +The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or licensed to him/her and that he/she has the power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or licensed to him/her and that he/she has the power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions to the Work, under the terms of this Licence. + +7. Disclaimer of Warranty + +The Work is a work in progress, which is continuously improved by numerous contributors. It is not a finished work and may therefore contain defects or "bugs" inherent to this type of software development. + +For the above reason, the Work is provided under the Licence on an "as is" basis and without warranties of any kind concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work. + +8. Disclaimer of Liability + +Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However, the Licensor will be liable under statutory product liability laws as far such laws apply to the Work. + +9. Additional agreements + +While distributing the Original Work or Derivative Works, You may choose to conclude an additional agreement to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or services consistent with this Licence. However, in accepting such obligations, You may act only on your own behalf and on your sole responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by the fact You have accepted any such warranty or additional liability. + +10. Acceptance of the Licence + +The provisions of this Licence can be accepted by clicking on an icon "I agree" placed under the bottom of a window displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution and/or Communication by You of the Work or copies thereof. + +11. Information to the public + +In case of any Distribution and/or Communication of the Work by means of electronic communication by You (for example, by offering to download the Work from a remote location) the distribution channel or media (for example, a website) must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence and the way it may be accessible, concluded, stored and reproduced by the Licensee. + +12. Termination of the Licence + +The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms of the Licence. Such a termination will not terminate the licences of any person who has received the Work from the Licensee under the Licence, provided such persons remain in full compliance with the Licence. + +13. Miscellaneous + +Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the Work licensed hereunder. + +If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or enforceability of the Licence as a whole. Such provision will be construed and/or reformed so as necessary to make it valid and enforceable. + +The European Commission may publish other linguistic versions and/or new versions of this Licence, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence. New versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take advantage of the linguistic version of their choice. + +14. Jurisdiction + +Any litigation resulting from the interpretation of this License, arising between the European Commission, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice of the European Communities, as laid down in article 238 of the Treaty establishing the European Community. + +Any litigation arising between Parties, other than the European Commission, and resulting from the interpretation of this License, will be subject to the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business. + +15. Applicable Law + +This Licence shall be governed by the law of the European Union country where the Licensor resides or has his registered office. + +This licence shall be governed by the Belgian law if: + + - a litigation arises between the European Commission, as a Licensor, and any Licensee; + + - the Licensor, other than the European Commission, has no residence or registered office inside a European Union country. + + + +Appendix + +"Compatible Licences" according to article 5 EUPL are: + + - GNU General Public License (GNU GPL) v. 2 + - Open Software License (OSL) v. 2.1, v. 3.0 + - Common Public License v. 1.0 + - Eclipse Public License v. 1.0 + - Cecill v. 2.0 diff --git a/README.md b/README.md index a82f2cc..32c52f5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,12 @@ + + # Dynix — WIP modular dynamicism for NixOS systems -Dynix is a prototype for modifying an append-only NixOS configuration, and dynamically +Dynix is a prototype for modifying an append-only NixOS configuration, and dynamically applying that configuration. ## Running the tests diff --git a/default.nix b/default.nix index 64072a2..d6a38de 100644 --- a/default.nix +++ b/default.nix @@ -1,5 +1,9 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { - pkgs ? import { }, + pkgs ? import { config.checkMeta = true; }, qpkgs ? let src = fetchTarball "https://github.com/Qyriad/nur-packages/archive/main.tar.gz"; in import src { inherit pkgs; }, diff --git a/flake.lock b/flake.lock index f07fa2c..3173a57 100644 --- a/flake.lock +++ b/flake.lock @@ -3,11 +3,11 @@ "fenix": { "flake": false, "locked": { - "lastModified": 1771226183, - "narHash": "sha256-AbaMtaLbe37l2VI/KSRk63PuBnX/YDDFL0G1eFMbvwI=", + "lastModified": 1773126504, + "narHash": "sha256-/iXlg2V5UMlgCmyRHkPHjlD6NdMfFOnwFMvH7REigD4=", "owner": "nix-community", "repo": "fenix", - "rev": "2e3759c5ef51f320eb0aaf83f2a32baae33db237", + "rev": "64407ddb1932af06ed5cd711f6a2ed946b2548b9", "type": "github" }, "original": { @@ -37,11 +37,11 @@ "nixpkgs": { "flake": false, "locked": { - "lastModified": 1770537093, - "narHash": "sha256-pF1quXG5wsgtyuPOHcLfYg/ft/QMr8NnX0i6tW2187s=", + "lastModified": 1772956932, + "narHash": "sha256-M0yS4AafhKxPPmOHGqIV0iKxgNO8bHDWdl1kOwGBwRY=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "fef9403a3e4d31b0a23f0bacebbec52c248fbb51", + "rev": "608d0cadfed240589a7eea422407a547ad626a14", "type": "github" }, "original": { @@ -54,11 +54,11 @@ "qyriad-nur": { "flake": false, "locked": { - "lastModified": 1770385314, - "narHash": "sha256-zDlvon/yF9STxGi3l38j9EgTFHBHOjCJlP8mMX7zw5M=", + "lastModified": 1773152764, + "narHash": "sha256-y1DgLrzhBUwAFMuk4rUT4aHSXwPeteQOJCukAXb6FdE=", "owner": "Qyriad", "repo": "nur-packages", - "rev": "23716e0347215a721f9489515a0c3dc91122c7d5", + "rev": "c94411f1020bc95f6f90f3d3b8ec1207ab635cd9", "type": "github" }, "original": { diff --git a/flake.lock.license b/flake.lock.license new file mode 100644 index 0000000..39b098c --- /dev/null +++ b/flake.lock.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2026 Qyriad + +SPDX-License-Identifier: EUPL-1.1 diff --git a/flake.nix b/flake.nix index 276cfb0..6d53131 100644 --- a/flake.nix +++ b/flake.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { inputs = { nixpkgs = { @@ -22,7 +26,7 @@ fenix, qyriad-nur, }: flake-utils.lib.eachDefaultSystem (system: let - pkgs = import nixpkgs { inherit system; }; + pkgs = import nixpkgs { inherit system; config.checkMeta = true; }; qpkgs = import qyriad-nur { inherit pkgs; }; inherit (qpkgs) lib; fenixLib = import fenix { inherit pkgs; }; diff --git a/modules/dynamicism/default.nix b/modules/dynamicism/default.nix index 1fca96c..9703245 100644 --- a/modules/dynamicism/default.nix +++ b/modules/dynamicism/default.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { ... }: { diff --git a/modules/dynamicism/distccd.nix b/modules/dynamicism/distccd.nix index 3b87764..bf027f2 100644 --- a/modules/dynamicism/distccd.nix +++ b/modules/dynamicism/distccd.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, ... }: let cfg = config.services.distccd; diff --git a/modules/dynamicism/dynamicism.nix b/modules/dynamicism/dynamicism.nix index 75f9fcb..3f98b09 100644 --- a/modules/dynamicism/dynamicism.nix +++ b/modules/dynamicism/dynamicism.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, options, ... }: let inherit (lib.options) diff --git a/modules/dynamicism/gotosocial.nix b/modules/dynamicism/gotosocial.nix index b1fedc6..449d714 100644 --- a/modules/dynamicism/gotosocial.nix +++ b/modules/dynamicism/gotosocial.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, ... }: let settingsFormat = pkgs.formats.yaml { }; diff --git a/modules/dynamicism/harmonia.nix b/modules/dynamicism/harmonia.nix index e4284d0..8dbfead 100644 --- a/modules/dynamicism/harmonia.nix +++ b/modules/dynamicism/harmonia.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, ... }: let cfg = config.dynamicism.for.harmonia; diff --git a/modules/dynamicism/lib.nix b/modules/dynamicism/lib.nix index ec41ab7..d3db655 100644 --- a/modules/dynamicism/lib.nix +++ b/modules/dynamicism/lib.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { lib ? import , }: let diff --git a/modules/dynamicism/submodule.nix b/modules/dynamicism/submodule.nix index 4100217..15b5774 100644 --- a/modules/dynamicism/submodule.nix +++ b/modules/dynamicism/submodule.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { name, lib, diff --git a/modules/dynamicism/tzupdate.nix b/modules/dynamicism/tzupdate.nix index 73f634d..b284cf9 100644 --- a/modules/dynamicism/tzupdate.nix +++ b/modules/dynamicism/tzupdate.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, ... }: let cfg = config.dynamicism.for.tzupdate; diff --git a/package.nix b/package.nix index 309f2d4..e5c4f98 100644 --- a/package.nix +++ b/package.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { lib, clangStdenv, @@ -24,33 +28,22 @@ in { outputs = [ "out" "modules" ]; + # These are propagated to sub-derivations. doCheck = true; doInstallCheck = true; - phases = [ "unpackPhase" "patchPhase" "installPhase" ]; - - src = linkFarm "dynix-source" { - inherit (self) dynixCommand dynixModules; - }; - - installPhase = '' - runHook preInstall - + buildCommand = '' mkdir -p "$out" cp -r --reflink=auto "$dynixCommand/"* "$out/" mkdir -p "$modules" cp -r --reflink=auto "$dynixModules/"* "$modules/" - - runHook postInstall ''; # # SUB-DERIVATONS # - dynixCommand = stdenv.mkDerivation (finalAttrs: let - commandSelf = finalAttrs.finalPackage; - in { + dynixCommand = stdenv.mkDerivation { pname = "${self.pname}-command"; inherit (self) version; inherit (self) strictDeps __structuredAttrs; @@ -79,12 +72,12 @@ in { meta = { mainProgram = "dynix"; + description = "The Rust part of Dynix"; + inherit (self.meta) license; }; - }); + }; - dynixModules = stdenv.mkDerivation (finalAttrs: let - modulesSelf = finalAttrs.finalPackage; - in { + dynixModules = stdenv.mkDerivation { pname = "${self.pname}-modules"; inherit (self) version; inherit (self) strictDeps __structuredAttrs; @@ -109,7 +102,12 @@ in { runHook postInstall ''; - }); + + meta = { + description = "The NixOS modules part of Dynix"; + inherit (self.meta) license; + }; + }; # # ---------------------------------------------------------------------------- @@ -120,9 +118,14 @@ in { mkShell, python3Packages, fenixToolchain, + cargo, }: let mkShell' = mkShell.override { inherit stdenv; }; pyEnv = python3Packages.python.withPackages (p: [ p.beartype ]); + # Fenix's Cargo doesn't have completions, but Nixpkgs' does. + cargoCompletions = linkFarm "cargo-bash-completions" { + "share/bash-completion" = cargo + "/share/bash-completion"; + }; in mkShell' { name = "devshell-for-${self.name}"; inputsFrom = [ self ]; @@ -130,12 +133,15 @@ in { pyEnv stdenv.cc fenixToolchain + cargoCompletions ]; env.PYTHONPATH = [ "${pyEnv}/${pyEnv.sitePackages}" # Cursed. "${path}/nixos/lib/test-driver/src" ] |> lib.concatStringsSep ":"; + + passthru = { inherit cargoCompletions; }; }; passthru.modulesPath = self.modules + "/share/nixos/modules"; @@ -154,6 +160,7 @@ in { The `dynix` passthru attr is a shortcut for the modules output *with* the modules prefix, and thus `dynix.dynix` can be passed directly to `imports = [`. ''; + license = with lib.licenses; [ eupl12 ]; mainProgram = "dynix"; outputsToInstall = [ "out" "modules" ]; }; diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..d662dc1 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + +match_block_trailing_comma = true +merge_derives = false diff --git a/shell.nix b/shell.nix index 4b93b7f..37ad241 100644 --- a/shell.nix +++ b/shell.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs ? import { config = { diff --git a/src/args.rs b/src/args.rs index 0028e0f..5c9bb73 100644 --- a/src/args.rs +++ b/src/args.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::{ env, sync::{Arc, LazyLock}, @@ -7,51 +11,8 @@ use clap::ColorChoice; use crate::prelude::*; -//#[derive(Debug, Clone, PartialEq)] -//#[derive(clap::Args)] -//#[group(required = true, multiple = false)] -//pub enum Config -//{ -// Flake, -//} - -#[derive(Debug, Clone, PartialEq)] -pub struct NixOsOption { - name: String, - value: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct NixOptionParseError(pub Box); - -impl Display for NixOptionParseError { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - write!(f, "{}", self.0) - } -} - -impl From for NixOptionParseError { - fn from(value: String) -> Self { - Self(value.into_boxed_str()) - } -} - -impl StdError for NixOptionParseError {} - -impl FromStr for NixOsOption { - type Err = NixOptionParseError; - - fn from_str(s: &str) -> Result { - // FIXME: allow escaping equals sign? - let Some(delim) = s.find('=') else { - return Err(format!("equals sign not found in {}", s).into()); - }; - - todo!(); - } -} - #[derive(Debug, Clone, PartialEq, clap::Parser)] +#[command(long_about = None)] pub struct AppendCmd { #[arg(required = true)] pub name: Arc, @@ -60,15 +21,26 @@ pub struct AppendCmd { pub value: Arc, } +/// Accept commands over (default stdin). #[derive(Debug, Clone, PartialEq, clap::Parser)] -pub struct DeltaCmd {} +#[command(long_about = None)] +pub struct DaemonCmd { + /// Read from stdin instead of a Unix socket. + #[arg(long)] + pub stdin: bool, + + /// Manually specify the full alternative path to the server socket. + /// + /// If not specified and `--stdin` is not specified, defaults to $XDG_RUNTIME_DIR/dynix.sock + #[arg(long)] + #[arg(conflicts_with = "stdin")] + pub socket: Option, +} #[derive(Debug, Clone, PartialEq, clap::Subcommand)] -#[command(flatten_help = true)] pub enum Subcommand { Append(AppendCmd), - // TODO: rename - Delta(DeltaCmd), + Daemon(DaemonCmd), } static DEFAULT_PATH: LazyLock> = LazyLock::new(|| { @@ -110,16 +82,3 @@ pub struct Args { #[command(subcommand)] pub subcommand: Subcommand, } -///// Flakeref to a base configuration to modify. -//#[arg(group = "config", long, default_value("."))] -//#[arg(long, default_value(Some(".")))] -//flake: Option>>, -// -//#[arg(group = "config", long)] -//expr: Option, - -//impl Parser { -// fn eval_cmd(&self) { -// todo!(); -// } -//} diff --git a/src/boxext.rs b/src/boxext.rs new file mode 100644 index 0000000..03200ec --- /dev/null +++ b/src/boxext.rs @@ -0,0 +1,27 @@ +use std::{ffi::OsStr, path::Path, ptr}; + +/// Until [`Box::map()`] is stable, there's no way to do this that is safe, stable, and +/// allocationless. +pub trait BoxedPathExt { + fn into_boxed_os_str(self) -> Box; +} + +impl BoxedPathExt for Box { + fn into_boxed_os_str(self) -> Box { + let path_mut_ptr: *mut Path = Box::into_raw(self); + + // SAFETY: we just got `path_mut_ptr` from a valid Box. + let os_str_mut_ptr: *mut OsStr = unsafe { + let os_str_mut_ref = path_mut_ptr + .as_mut() + .expect("avoided undefined behavior") + .as_mut_os_str(); + + ptr::from_mut(os_str_mut_ref) + }; + + // SAFETY: allocation came from `Box::into_raw()`, and we are not extending + // its lifetime. There are also no shared or exclusive references. + unsafe { Box::::from_raw(os_str_mut_ptr) } + } +} diff --git a/src/color.rs b/src/color.rs index 1e420f6..f51dc77 100644 --- a/src/color.rs +++ b/src/color.rs @@ -1,3 +1,10 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + +// The entire point of this module. +#![allow(clippy::declare_interior_mutable_const)] + use std::{ env, sync::{LazyLock, OnceLock}, @@ -18,13 +25,7 @@ fn is_color_reqd() -> bool { fn is_clicolor_forced() -> bool { env::var("CLICOLOR_FORCE") - .map(|value| { - if value.is_empty() || value == "0" { - false - } else { - true - } - }) + .map(|value| !(value.is_empty() || value == "0")) .unwrap_or(false) } diff --git a/src/daemon.rs b/src/daemon.rs new file mode 100644 index 0000000..506527a --- /dev/null +++ b/src/daemon.rs @@ -0,0 +1,411 @@ +use std::{ + env, io, + ops::Deref, + os::fd::{AsFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}, + sync::LazyLock, + time::Duration, +}; + +use circular_buffer::CircularBuffer; + +use mio::{Events, Interest, Poll, Token, net::UnixListener, unix::SourceFd}; + +use rustix::{ + buffer::{Buffer, spare_capacity}, + fs::{FileType, OFlags, Stat, fcntl_setfl}, + io::Errno, + net::SocketFlags, + process::Uid, + termios::{ + ControlModes, InputModes, LocalModes, OptionalActions, OutputModes, SpecialCodeIndex, + SpecialCodes, Termios, tcgetattr, tcsetattr, + }, +}; + +use serde::{Deserialize, Serialize}; +use serde_json::StreamDeserializer; + +use crate::prelude::*; + +use crate::OwnedFdWithFlags; + +pub static UID: LazyLock = LazyLock::new(|| rustix::process::getuid()); + +pub static USER_SOCKET_DIR: LazyLock<&'static Path> = LazyLock::new(|| { + let dir: Box = env::var_os("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| ["/", "run", "user", &UID.to_string()].into_iter().collect()) + .into_boxed_path(); + + Box::leak(dir) +}); + +pub static TMPDIR: LazyLock<&'static Path> = LazyLock::new(|| { + let dir: Box = env::temp_dir().into_boxed_path(); + + Box::leak(dir) +}); + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Deserialize, Serialize)] +#[serde(untagged)] +pub enum ConvenientAttrPath { + Dotted(Box), + Split(Box<[Box]>), +} + +impl ConvenientAttrPath { + pub fn clone_from_dotted(s: &str) -> Self { + Self::Dotted(Box::from(s)) + } + + pub fn clone_from_split(s: &[&str]) -> Self { + Self::from_str_iter(s.into_iter().map(Deref::deref)) + } + + pub fn from_str_iter<'i, I>(iter: I) -> Self + where + I: Iterator, + { + let boxed = iter.map(|s| Box::from(s)); + Self::Split(Box::from_iter(boxed)) + } +} + +impl<'i> FromIterator<&'i str> for ConvenientAttrPath { + fn from_iter(iter: I) -> Self + where + I: IntoIterator, + { + Self::from_str_iter(iter.into_iter()) + } +} + +impl FromIterator> for ConvenientAttrPath { + fn from_iter(iter: I) -> Self + where + I: IntoIterator>, + { + Self::Split(Box::from_iter(iter)) + } +} + +#[derive(Debug, Clone, PartialEq)] +#[derive(serde::Deserialize, serde::Serialize)] +#[serde(tag = "action", content = "args", rename_all = "snake_case")] +pub enum DaemonCmd { + Append { + name: ConvenientAttrPath, + value: Box, + }, +} + +const TIMEOUT_NEVER: Option = None; + +#[derive(Debug)] +pub struct Daemon { + fd: OwnedFdWithFlags, + path: Box, + poll_error_buffer: CircularBuffer, + fd_error_buffer: CircularBuffer, + + cmd_buffer: Vec, + next_timeout: Option, +} + +impl Daemon { + pub fn new(fd: OwnedFd, name_or_path: Box) -> Self { + let fd = OwnedFdWithFlags::new_with_fallback(fd); + + debug!( + "opened daemon to {} file descriptor {fd:?}", + name_or_path.display(), + ); + + Self { + fd, + path: name_or_path, + poll_error_buffer: Default::default(), + fd_error_buffer: Default::default(), + cmd_buffer: Vec::with_capacity(1024), + next_timeout: TIMEOUT_NEVER, + } + } + + pub fn from_unix_socket_path(path: &Path) -> Result { + // We unconditionally unlink() `path` before binding, but completely ignore the result. + let _ = rustix::fs::unlink(path); + let listener = UnixListener::bind(path) + .tap_err(|e| error!("failed to bind AF_UNIX socket at {}: {e}", path.display()))?; + //let (stream, _addr) = listener.accept().unwrap_or_else(|e| todo!("error: {e}")); + //warn!("stream is: {stream:?} ({})", stream.as_raw_fd()); + let listener_owned_fd = OwnedFd::from(listener); + rustix::net::sockopt::set_socket_keepalive(&listener_owned_fd, true).unwrap(); + let path: Box = path.to_path_buf().into_boxed_path().into_boxed_os_str(); + + Ok(Self::new(listener_owned_fd, path)) + } + + pub fn open_default_socket() -> Result { + use IoErrorKind::*; + let preferred = USER_SOCKET_DIR.join("dynix.sock").into_boxed_path(); + let constructed = match Self::from_unix_socket_path(&preferred) { + Ok(v) => v, + Err(e) if e.kind() == Unsupported => { + // + return Err(e); + }, + Err(e) => { + warn!( + "failed binding AF_UNIX socket at {}: {e}; trying elsewhere", + preferred.display() + ); + + let fallback = TMPDIR.join("dynix.sock").into_boxed_path(); + Self::from_unix_socket_path(&fallback).tap_err(|e| { + error!( + "failed binding AF_UNIX socket at {}: {e}", + fallback.display() + ) + })? + }, + }; + + Ok(constructed) + } + + /// This panics if stdin cannot be opened. + /// + /// If you want to handle that error, use [`Daemon::from_raw_parts()`]. + pub fn from_stdin() -> Self { + let stdin = io::stdin(); + let fd = stdin + .as_fd() + .try_clone_to_owned() + .expect("dynix daemon could not open stdin; try a Unix socket?"); + + Self::new(fd, Box::from(OsStr::new("«stdin»"))) + } + + //pub unsafe fn from_raw_parts(fd: OwnedFd) -> Self { + // Self { + // fd: OwnedFdWithFlags::new_with_fallback(fd), + // } + //} + + pub fn fd(&self) -> BorrowedFd<'_> { + self.fd.as_fd() + } +} + +const ERROR_BUFFER_LEN: usize = 8; + +/// Private helpers. +impl Daemon { + fn read_cmd(&mut self, fd: Option<&dyn AsFd>) -> Result<(), IoError> { + let fd = match fd.as_ref() { + Some(fd) => fd.as_fd(), + None => self.fd.as_fd(), + }; + + if self.cmd_buffer.len() == self.cmd_buffer.capacity() { + self.cmd_buffer.reserve(1024); + } + + let _count = rustix::io::read(fd, spare_capacity(&mut self.cmd_buffer)) + .tap_err(|e| error!("read() on daemon fd {fd:?} failed: {e}"))?; + + // The buffer might have existing data from the last read. + let deserializer = serde_json::Deserializer::from_slice(&self.cmd_buffer); + let stream: StreamDeserializer<_, DaemonCmd> = deserializer.into_iter(); + for cmd in stream { + let cmd = match cmd { + Ok(cmd) => cmd, + Err(e) if e.is_eof() => { + self.next_timeout = Some(Duration::from_secs(4)); + warn!("Didn't get a valid daemon command; giving the other side 4 seconds..."); + return Ok(()); + }, + Err(e) => { + warn!("error deserializing command: {e}"); + warn!("error count: {}", self.fd_error_buffer.len()); + self.cmd_buffer.clear(); + // Don't propagate the error unless we have too many. + self.fd_error_buffer.try_push_back(e.into()).tap_err(|e| { + error!("Accumulated too many errors for daemon fd {fd:?}: {e}") + })?; + return Ok(()); + }, + }; + debug!("got cmd: {cmd:?}"); + } + + self.cmd_buffer.clear(); + + Ok(()) + } + + pub(crate) fn enter_loop(&mut self) -> Result, IoError> { + let raw_fd = self.fd.as_raw_fd(); + let mut daemon_source = SourceFd(&raw_fd); + const DAEMON: Token = Token(0); + let mut next_token_number: usize = 1; + let mut extra_tokens: Vec<(Token, RawFd)> = Default::default(); + let mut poll = Poll::new().unwrap_or_else(|e| unreachable!("creating new mio Poll: {e}")); + + poll.registry() + .register(&mut daemon_source, DAEMON, Interest::READABLE) + .unwrap_or_else(|e| unreachable!("registering mio Poll for daemon fd {raw_fd:?}: {e}")); + + let mut events = Events::with_capacity(1024); + + let example = DaemonCmd::Append { + //name: ConvenientAttrPath::Dotted(Box::from( + // "services.gotosocial.settings.application-name", + //)), + //name: ConvenientAttrPath::Split(Box::from([ + // Box::from("services"), + // Box::from("gotosocial"), + //])), + name: ConvenientAttrPath::clone_from_split(&[ + "services", + "gotosocial", + "settings", + "application-name", + ]), + value: Box::from("foo"), + }; + + //let example_as_json = serde_json::to_string_pretty(&example).unwrap(); + //info!("{}", example_as_json); + + loop { + match poll.poll(&mut events, self.next_timeout.take()) { + Ok(_) => { + if events.is_empty() { + warn!("timeout expired"); + self.cmd_buffer.clear(); + } else { + let _ = self.poll_error_buffer.pop_front(); + } + }, + Err(e) => { + warn!("mio Poll::poll() error: {e}"); + self.poll_error_buffer.try_push_back(e).tap_err(|e| { + error!("accumulated too many errors for mio::Poll::poll(): {e}") + })?; + }, + } + + for event in &events { + match event.token() { + DAEMON => { + let is_sock = rustix::fs::fstat(&self.fd) + .map(|Stat { st_mode, .. }| st_mode) + .map(FileType::from_raw_mode) + .map(FileType::is_socket) + .unwrap_or(false); + + if !is_sock { + self.read_cmd(None).unwrap(); + continue; + } + + // Accept, first. + let flags = SocketFlags::NONBLOCK | SocketFlags::CLOEXEC; + let stream_fd = match rustix::net::accept_with(&self.fd, flags) { + Ok(stream) => { + debug!( + "Accepted connection from socket {:?} as stream {:?}", + self.fd, stream, + ); + stream + }, + Err(e) => { + error!("accept4 on daemon socket failed: {e}"); + self.fd_error_buffer.try_push_back(e.into()).tap_err(|e| { + error!( + "Accumulated too many errors for daemon fd {:?}: {e}", + self.fd + ) + })?; + continue; + }, + }; + + let mut stream_fd = stream_fd.into_raw_fd(); + + // And add this stream to our poll interest list. + if let Err(idx) = + extra_tokens.binary_search_by_key(&stream_fd, |(_, fd)| fd.as_raw_fd()) + { + let token = Token(next_token_number); + extra_tokens.insert(idx, (token, stream_fd)); + next_token_number = next_token_number.wrapping_add(1); + let mut source = SourceFd(&mut stream_fd); + poll.registry() + .register(&mut source, token, Interest::READABLE) + .unwrap(); + } + + // Wait for the next poll to handle. + + //match self.read_cmd(Some(&stream_fd)) { + // Ok(()) => (), + // Err(e) if e.kind() == IoErrorKind::WouldBlock => { + // continue; + // }, + // Err(e) => { + // self.fd_error_buffer.try_push_back(e.into()).tap_err(|e| { + // error!( + // "Accumulated too many errors for fd {:?} {e}", + // &stream_fd, + // ) + // })?; + // }, + //} + }, + other_token => { + let index = match extra_tokens + .binary_search_by_key(&other_token, |&(t, _)| t) + { + Ok(index) => index, + Err(index) => unreachable!( + "tried to get index ({index}) for non-existent token {other_token:?}" + ), + }; + + // This must be a stream fd. + let (_, stream_fd) = extra_tokens[index]; + // SAFETY: oh boy. + let stream_fd = unsafe { BorrowedFd::borrow_raw(stream_fd) }; + self.read_cmd(Some(&stream_fd)).unwrap(); + }, + } + } + } + } + + fn get_fallback_fd_name(fd: Fd) -> Option> { + let dev_fd_path = Path::new("/dev/fd").join(fd.as_raw_fd().to_string()); + + fs_err::read_link(dev_fd_path) + .map(PathBuf::into_os_string) + .map(OsString::into_boxed_os_str) + .ok() + } +} + +impl Drop for Daemon { + fn drop(&mut self) { + let probably_synthetic = self + .path + .to_str() + .map(|p| p.starts_with("«") && p.ends_with("»")) + .unwrap_or(false); + if probably_synthetic { + return; + } + let _ = rustix::fs::unlink(&*self.path); + } +} diff --git a/src/daemon_io.rs b/src/daemon_io.rs new file mode 100644 index 0000000..891a518 --- /dev/null +++ b/src/daemon_io.rs @@ -0,0 +1,150 @@ +use std::{ + mem::ManuallyDrop, + os::{ + fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}, + unix::prelude::RawFd, + }, +}; + +use rustix::{ + fs::{OFlags, fcntl_getfl, fcntl_setfl}, + io::Errno, +}; + +use crate::prelude::*; + +/// An [`OwnedFd`] that captures file status flags on init and restores them on: +/// +/// - [`IntoRawFd`] +/// - [`drop()`] +pub struct OwnedFdWithFlags { + fd: OwnedFd, + oflags: OFlags, +} + +impl OwnedFdWithFlags { + pub fn new(fd: OwnedFd) -> Result { + let oflags = fcntl_getfl(&fd)?; + Ok(Self { fd, oflags }) + } + + pub fn as_ref_owned(&self) -> &OwnedFd { + &self.fd + } + + /// If, for some ungodly reason, `fcntl(F_GETFL)` fails, then empty flags are used. + /// Empty flags should not be restored on close. + /// + /// I'm pretty sure this should never happen if the program is IO-safe. + pub fn new_with_fallback(fd: OwnedFd) -> Self { + let oflags = Self::get_flags_or_log(&fd); + Self { fd, oflags } + } + + pub fn oflags(&self) -> OFlags { + self.oflags + } +} + +impl Debug for OwnedFdWithFlags { + fn fmt(&self, f: &mut Formatter) -> FmtResult { + let mut flags_str: String = Default::default(); + bitflags::parser::to_writer(&self.oflags, &mut flags_str)?; + + f.debug_struct("OwnedFdWithFlags") + .field("fd", &self.fd.as_raw_fd()) + .field("oflags", &flags_str) + .finish() + } +} + +impl Drop for OwnedFdWithFlags { + fn drop(&mut self) { + self.restore_flags_or_log(); + } +} + +/// Private helpers. +impl OwnedFdWithFlags { + fn restore_flags_or_log(&self) { + // As far as we can tell there's no such thing as a file with entirely empty + // flags (at minimum, it needs read/write mode, right?). + // So empty `oflags` is our sentinel that `fcntl(F_GETFL)` somehow failed. + // Empty oflags is our sentinel that + if self.oflags.is_empty() { + return; + } + + match fcntl_setfl(&self.fd, self.oflags) { + Ok(_) => (), + // EBADF + //Err(Errno::BADF) => (), + Err(e) => error!( + "fcntl(F_SETFL) to restore flags {:?} on fd {:?} failed: {e}\nIO safety violation?", + self.oflags, self.fd, + ), + } + } + + fn get_flags_or_log(fd: Fd) -> OFlags { + let fd = fd.as_fd(); + fcntl_getfl(fd) + .tap_err(|e| error!("fcntl(F_GETFL) failed on fd {fd:?}: {e}\nIO-safety violation?")) + .unwrap_or(OFlags::empty()) + } +} + +impl AsRawFd for OwnedFdWithFlags { + fn as_raw_fd(&self) -> RawFd { + AsRawFd::as_raw_fd(&self.fd) + } +} + +impl IntoRawFd for OwnedFdWithFlags { + fn into_raw_fd(self) -> RawFd { + self.restore_flags_or_log(); + ManuallyDrop::new(self).fd.as_raw_fd() + } +} + +impl FromRawFd for OwnedFdWithFlags { + unsafe fn from_raw_fd(fd: RawFd) -> Self { + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + let oflags = Self::get_flags_or_log(&fd); + Self { fd, oflags } + } +} + +impl AsFd for OwnedFdWithFlags { + fn as_fd(&self) -> BorrowedFd<'_> { + AsFd::as_fd(&self.fd) + } +} + +impl From for OwnedFdWithFlags { + fn from(fd: OwnedFd) -> Self { + let oflags = Self::get_flags_or_log(fd.as_fd()); + Self { fd, oflags } + } +} + +impl Read for &OwnedFdWithFlags { + fn read(&mut self, buf: &mut [u8]) -> Result { + debug_assert!(buf.len() > 0); + loop { + buf.fill(0); + match rustix::io::read(self.as_ref_owned(), &mut *buf) { + Ok(count) => { + debug_assert!(count <= buf.len()); + return Ok(count); + }, + Err(e) if e.kind() == IoErrorKind::Interrupted => continue, + Err(e) if e.kind() == IoErrorKind::WouldBlock => return Ok(0), + Err(e) => { + let e = IoError::from_raw_os_error(e.raw_os_error()); + return Err(e); + }, + } + } + } +} diff --git a/src/lib.rs b/src/lib.rs index cf7839a..e0211ec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::{ iter, sync::{Arc, LazyLock}, @@ -9,8 +13,8 @@ pub(crate) mod prelude { pub use std::{ error::Error as StdError, ffi::{OsStr, OsString}, - fmt::{Display, Formatter, Result as FmtResult}, - io::{Error as IoError, Read, Seek, SeekFrom, Write}, + fmt::{Debug, Display, Formatter, Result as FmtResult}, + io::{Error as IoError, ErrorKind as IoErrorKind, Read, Seek, SeekFrom, Write}, path::{Path, PathBuf}, process::{Command, ExitCode}, str::FromStr, @@ -29,21 +33,31 @@ pub(crate) mod prelude { #[cfg(unix)] pub use fs_err::os::unix::fs::{FileExt, OpenOptionsExt}; - pub use tap::{Pipe, Tap}; + pub use bstr::ByteSlice; + + pub use tap::{Pipe, Tap, TapFallible}; pub use tracing::{Level, debug, error, info, trace, warn}; + + pub use crate::boxext::BoxedPathExt; } use prelude::*; pub mod args; -pub use args::{AppendCmd, Args, DeltaCmd}; +pub use args::{AppendCmd, Args}; +mod boxext; mod color; pub use color::{_CLI_ENABLE_COLOR, SHOULD_COLOR}; +mod daemon; +pub use daemon::Daemon; +mod daemon_io; +pub use daemon_io::OwnedFdWithFlags; pub mod line; -mod nixcmd; pub use line::Line; +mod nixcmd; pub mod source; +use rustix::fs::Mode; pub use source::{SourceFile, SourceLine}; #[cfg(all(not(feature = "regex-full"), not(feature = "regex-lite")))] @@ -61,6 +75,8 @@ use _regex::Regex; use itertools::Itertools; use serde::{Deserialize, Serialize}; +use crate::args::DaemonCmd; + pub const ASCII_WHITESPACE: &[char] = &['\t', '\n', '\x0C', '\r', ' ']; /// Regex pattern to extract the priority in a `lib.mkOverride` call. @@ -76,11 +92,6 @@ static MK_OVERRIDE_RE: LazyLock = LazyLock::new(|| { Regex::new(r"(?-u)\bmkOverride\s+\((?[\d-]+)\)").unwrap() }); -#[tracing::instrument(level = "debug")] -pub fn do_delta(args: Arc, delta_args: DeltaCmd) -> Result<(), BoxDynError> { - todo!(); -} - #[tracing::instrument(level = "debug")] pub fn do_append(args: Arc, append_args: AppendCmd) -> Result<(), BoxDynError> { let filepath = Path::new(&args.file); @@ -105,9 +116,9 @@ pub fn do_append(args: Arc, append_args: AppendCmd) -> Result<(), BoxDynEr let new_pri_line = get_next_prio_line( source_file.clone(), - append_args.name.into(), + append_args.name, new_pri, - append_args.value.into(), + append_args.value, )?; debug!("new_pri_line={new_pri_line}"); @@ -117,6 +128,27 @@ pub fn do_append(args: Arc, append_args: AppendCmd) -> Result<(), BoxDynEr Ok(()) } +//#[tracing::instrument(level = "debug")] +pub fn do_daemon(_args: Arc, daemon_args: DaemonCmd) -> Result<(), BoxDynError> { + // FIXME: make configurable? + let _ = rustix::process::umask(Mode::from_bits_retain(0o600).complement()); + + let mut daemon = match daemon_args { + DaemonCmd { stdin: true, .. } => Daemon::from_stdin(), + DaemonCmd { socket: None, .. } => Daemon::open_default_socket()?, + DaemonCmd { + socket: Some(socket), + .. + } => Daemon::from_unix_socket_path(&socket)?, + }; + + daemon.enter_loop().unwrap(); + + info!("daemon has exited"); + + Ok(()) +} + #[derive(Debug, Clone, PartialEq, Hash, Serialize, Deserialize)] pub struct DefinitionWithLocation { pub file: Box, @@ -150,7 +182,7 @@ fn maybe_extract_prio_from_line(line: &SourceLine) -> Option { pub fn get_where(dynamic_nix: SourceFile) -> Result { let lines = dynamic_nix.lines()?; let prio = lines - .into_iter() + .iter() .filter_map(maybe_extract_prio_from_line) .sorted_unstable() .next() // Priorities with lower integer values are "stronger" priorities. diff --git a/src/line.rs b/src/line.rs index e7ec169..aa0d706 100644 --- a/src/line.rs +++ b/src/line.rs @@ -1,9 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::num::NonZeroU64; #[allow(unused_imports)] use crate::prelude::*; - #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Line(pub u64); @@ -39,5 +42,3 @@ impl Line { self.0 + 1 } } - -pub struct Lines(Vec); diff --git a/src/main.rs b/src/main.rs index ef00265..a54078e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,8 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + +use std::env; use std::io::{self, IsTerminal}; use std::process::ExitCode; use std::{error::Error as StdError, sync::Arc}; @@ -8,6 +13,13 @@ use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::{EnvFilter, layer::SubscriberExt}; fn main_wrapped() -> Result<(), Box> { + // Default RUST_LOG to warn if it's not specified. + if let None = env::var_os("RUST_LOG") { + unsafe { + env::set_var("RUST_LOG", "warn"); + } + } + let args = Arc::new(dynix::Args::parse()); let success = dynix::_CLI_ENABLE_COLOR.set(match args.color { @@ -30,7 +42,7 @@ fn main_wrapped() -> Result<(), Box> { use dynix::args::Subcommand::*; match &args.subcommand { Append(append_args) => dynix::do_append(args.clone(), append_args.clone())?, - Delta(delta_args) => dynix::do_delta(args.clone(), delta_args.clone())?, + Daemon(daemon_args) => dynix::do_daemon(args.clone(), daemon_args.clone())?, }; } @@ -43,6 +55,6 @@ fn main() -> ExitCode { Err(e) => { eprintln!("dynix: error: {}", e); ExitCode::FAILURE - } + }, } } diff --git a/src/nixcmd.rs b/src/nixcmd.rs index 3121565..980d8a0 100644 --- a/src/nixcmd.rs +++ b/src/nixcmd.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + #[allow(unused_imports)] use crate::prelude::*; diff --git a/src/source.rs b/src/source.rs index c0099a1..287f72e 100644 --- a/src/source.rs +++ b/src/source.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::{ cell::{Ref, RefCell}, hash::Hash, @@ -36,7 +40,7 @@ pub fn replace_file<'a>( drop(writer); // Rename the temporary file to the new file, which is atomic (TODO: I think). - fs_err::rename(&tmp_path, &path)?; + fs_err::rename(&tmp_path, path)?; Ok(()) } @@ -58,7 +62,7 @@ impl SourceLine { } pub fn text_bytes(&self) -> Arc<[u8]> { - let len: usize = self.text.as_bytes().len(); + let len: usize = self.text.len(); // We need to consume an Arc, but we are &self. let text = Arc::clone(&self.text); diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..1a560ef --- /dev/null +++ b/tests/README.md @@ -0,0 +1,12 @@ + + +# Notes for running the tests + +The VM tests do Nix builds inside the VMs, so they have writable Nix stores. +Writable Nix stores in NixOS VM tests are, by default, tmpfs, but to speed up IO for the in-VM `nixos-rebuild`s, `./module-allow-rebuild-in-vm.nix` instead sets `virtualisation.writableStoreUseTmpfs = false;`, and allocates a much larger root filesystem for the VM. +Specifically, each VM test allocates 20 GiB. +If you are running low on disk space, disable `virtualisation.writableStoreUseTmpfs` in `./module-allow-rebuild-in-vm`. diff --git a/tests/default.nix b/tests/default.nix index 02842fa..57b1c94 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs ? import { }, qpkgs ? let @@ -32,6 +36,8 @@ ./module-allow-rebuild-in-vm.nix # For the VM node, and the in-VM configuration.nix ./dynix-vm-configuration.nix + # NOTE: if `dynix` is a package (which it usually is), then + # this is IFD. dynix.dynix ]; diff --git a/tests/distccd/configuration.nix b/tests/distccd/configuration.nix index b0d90b5..05bea65 100644 --- a/tests/distccd/configuration.nix +++ b/tests/distccd/configuration.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { ... }: { diff --git a/tests/distccd/test-script.py b/tests/distccd/test-script.py index 3678155..a5e35ee 100644 --- a/tests/distccd/test-script.py +++ b/tests/distccd/test-script.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + import argparse import functools import shlex @@ -94,7 +98,7 @@ assert args.job_lifetime == 900, f'{args.job_lifetime} != 900' assert args.log_level == 'warning', f'{args.log_level=} != warning' with machine.nested("must succeed: initial nixos-rebuild switch"): - machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") + machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec --fallback") # Config should not have changed. args = get_cli_args() @@ -122,7 +126,7 @@ assert args.job_lifetime == 900, f'{args.job_lifetime} != 900' assert args.log_level == new_log_level, f'{args.log_level=} != {new_log_level=}' # And this should set everything back. -machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") +machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec --fallback") args = get_cli_args() assert args.jobs == 12, f'{args.jobs=} != 12' assert args.job_lifetime == 900, f'{args.job_lifetime} != 900' diff --git a/tests/distccd/test.nix b/tests/distccd/test.nix index ad9ac73..852eac2 100644 --- a/tests/distccd/test.nix +++ b/tests/distccd/test.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { mkDynixConfigurationDotNix, config, ... }: let testName = config.name; diff --git a/tests/dynix-vm-configuration.nix b/tests/dynix-vm-configuration.nix index fbc6193..2e299c3 100644 --- a/tests/dynix-vm-configuration.nix +++ b/tests/dynix-vm-configuration.nix @@ -1,6 +1,10 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, modulesPath, ... }: let - moduleList = import "${modulesPath}/module-list.nix"; + moduleList = import (modulesPath + "/module-list.nix"); dynixFromSearchPath = let res = builtins.tryEval ; @@ -8,14 +12,13 @@ let in { imports = [ - "${modulesPath}/testing/test-instrumentation.nix" + (modulesPath + "/testing/test-instrumentation.nix") ] ++ lib.concatLists [ dynixFromSearchPath moduleList ]; system.switch.enable = true; - system.includeBuildDependencies = true; documentation.enable = false; boot.loader.grub = { @@ -27,7 +30,7 @@ in nix = { package = pkgs.lixPackageSets.latest.lix; nixPath = [ - "nixpkgs=${pkgs.path}" + ("nixpkgs=" + pkgs.path) "/nix/var/nix/profiles/per-user/root/profile/share/nixos/modules" ]; diff --git a/tests/gotosocial/configuration.nix b/tests/gotosocial/configuration.nix index 8ada5c8..a069b34 100644 --- a/tests/gotosocial/configuration.nix +++ b/tests/gotosocial/configuration.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, modulesPath, ... }: let name = config.networking.hostName; diff --git a/tests/gotosocial/test-script.py b/tests/gotosocial/test-script.py index 51a303f..eca3044 100644 --- a/tests/gotosocial/test-script.py +++ b/tests/gotosocial/test-script.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + from pathlib import Path import shlex import textwrap @@ -76,7 +80,7 @@ dynix_out = machine.succeed("dynix --version") assert "dynix" in dynix_out, f"dynix not in {dynix_out=}" machine.log("REBUILDING configuration inside VM") -machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") +machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec --fallback") machine.wait_for_unit("gotosocial.service") # Make sure the config before any dynamic changes is what we expect. @@ -107,7 +111,7 @@ except StopIteration: assert new_app_name in application_name, f"'{new_app_name}' should be in {application_name=}" machine.log("REBUILDING configuration inside VM") -machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") +machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec --fallback") machine.wait_for_unit("gotosocial.service") diff --git a/tests/gotosocial/test.nix b/tests/gotosocial/test.nix index ccb71f6..9215d1e 100644 --- a/tests/gotosocial/test.nix +++ b/tests/gotosocial/test.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { mkDynixConfigurationDotNix, config, ... }: let testName = config.name; diff --git a/tests/harmonia/configuration.nix b/tests/harmonia/configuration.nix index d5cc833..2fd2bcf 100644 --- a/tests/harmonia/configuration.nix +++ b/tests/harmonia/configuration.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { ... }: { diff --git a/tests/harmonia/test-script.py b/tests/harmonia/test-script.py index bdac573..c40e130 100644 --- a/tests/harmonia/test-script.py +++ b/tests/harmonia/test-script.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + import functools from pathlib import Path import shlex @@ -82,7 +86,7 @@ assert int(config_toml['workers']) == 4, f"{config_toml['workers']=} != 4" assert int(config_toml['max_connection_rate']) == 256, f"{config_toml['max_connection_rate']=} != 256" with machine.nested("must succeed: initial nixos-rebuild switch"): - machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") + machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec -v --fallback") # Config should not have changed. config_toml = get_config_file() @@ -108,7 +112,7 @@ assert int(config_toml['max_connection_rate']) == new_max_connection_rate, f"{co assert int(config_toml['workers']) == new_workers, f"{config_toml['workers']=} != {new_workers}" # And this should set everything back. -machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") +machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec -v --fallback") machine.wait_for_unit("harmonia.service") config_toml = get_config_file() assert int(config_toml['max_connection_rate']) == 256, f'{config_toml["max_connection_rate"]=} != 256' diff --git a/tests/harmonia/test.nix b/tests/harmonia/test.nix index 25fcfbf..8fcc19b 100644 --- a/tests/harmonia/test.nix +++ b/tests/harmonia/test.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { mkDynixConfigurationDotNix, config, ... }: let testName = config.name; diff --git a/tests/mk-test-configuration-dot-nix.nix b/tests/mk-test-configuration-dot-nix.nix index 6b7dc25..fd9c5a8 100644 --- a/tests/mk-test-configuration-dot-nix.nix +++ b/tests/mk-test-configuration-dot-nix.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { lib, stdenvNoCC, diff --git a/tests/module-allow-rebuild-in-vm.nix b/tests/module-allow-rebuild-in-vm.nix index 96280fe..50a002e 100644 --- a/tests/module-allow-rebuild-in-vm.nix +++ b/tests/module-allow-rebuild-in-vm.nix @@ -1,4 +1,8 @@ -{ name, config, ... }: +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + +{ name, lib, config, ... }: { system.includeBuildDependencies = true; @@ -12,6 +16,12 @@ mountHostNixStore = true; installBootLoader = true; + # Moderately improves performance of `nixos-rebuild` inside the VM on my machine, + # (205.48 seconds to 186.42 seconds), but we have to allocate much more space. + writableStoreUseTmpfs = false; + # 20 GiB ought to be enough. + diskSize = lib.mkIf (!config.virtualisation.writableStoreUseTmpfs) (20 * 1024); + # With how much memory Nix eval uses, this is essentially required. memorySize = 8192; cores = 8;