diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..03ae7fb --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{json,yml,yaml}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..cb66d79 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +* text=auto eol=lf + +/.github export-ignore +/docs export-ignore +/tests export-ignore +/.editorconfig export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/phpstan.neon.dist export-ignore +/phpunit.xml.dist export-ignore +/ruleset.xml export-ignore +/stubs export-ignore diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8526c86 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,19 @@ +version: 2 +updates: + - package-ecosystem: composer + directory: / + schedule: + interval: weekly + groups: + composer: + patterns: + - "*" + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions: + patterns: + - "*" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e572d4d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,56 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: PHP ${{ matrix.php }} + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + php: + - "8.2" + - "8.3" + - "8.4" + - "8.5" + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + tools: composer:v2 + + - name: Validate package + run: composer validate --strict + + - name: Install dependencies + run: composer install --no-interaction --prefer-dist --ignore-platform-req=ext-getbiblesword + + - name: Unit tests + run: composer test + + - name: Coding standard + if: matrix.php == '8.4' + run: composer style + + - name: Static analysis + if: matrix.php == '8.4' + run: composer analyse diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..095d25e --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/.phpunit.cache/ +/.phpunit.result.cache +/build/ +/composer.lock +/coverage.xml +/vendor/ +/.idea/ +/.vscode/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..b925d2b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,32 @@ +# Changelog + +All notable changes to this project are documented here. + +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +and the project uses [Semantic Versioning](https://semver.org/). + +## [Unreleased] + +### Added + +- Initial Composer package structure. +- Joomla DI composition root and service provider. +- Native `getbible/sword` engine adapter. +- Independent streaming validator for `getbiblesword.ndjson/v1`. +- Lossless contract and Scripture domain objects. +- Atomic, lazy translation snapshot generation. +- Configurable monthly snapshot rotation and Joomla lifecycle events. +- Explicit provisioning capability discovery. +- Selected/all installation, refresh, and removal contracts. +- Ordered per-module provisioning outcomes. +- Bounded shared/exclusive module-root lifecycle locking. +- Provisioning lifecycle events and atomic process-cache invalidation. +- Durable initialization, refresh, and interval-gated refresh services. +- Per-module maintenance failure isolation and durable failure state. +- Joomla Console initialization, refresh, and status commands. +- Joomla Scheduled Tasks callable integration. +- Production cron, systemd, health-check, and scheduler documentation. + +### Changed + +- Project license aligned with the GPL-2.0-only native dependency. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9a9897b --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,35 @@ +# Contributing + +## Development + +Install the native extension first, then install Composer dependencies: + +```bash +pie install getbible/sword +composer install +composer check +``` + +Unit tests use an injected engine and can run without loading the extension: + +```bash +composer install --ignore-platform-req=ext-getbiblesword +composer check +``` + +## Engineering rules + +- Preserve GPL-2.0-only SPDX headers on source files. +- Keep domain objects immutable and free of container lookups. +- Inject infrastructure through interfaces. +- Never load a complete native module stream into one PHP string. +- Validate the entire v1 stream before activating a snapshot. +- Treat decoded Base64 bytes as authoritative. +- Preserve unknown additive record fields. +- Never treat lexical annotation markup as trusted HTML. +- Do not introduce network activity in constructors. +- Do not modify an active SWORD module root while native extraction is reading + it. + +Contract changes require matching tests and documentation. A breaking public API +change requires an appropriate semantic version increment. diff --git a/LICENSE b/LICENSE index f288702..6651c66 100644 --- a/LICENSE +++ b/LICENSE @@ -1,622 +1,284 @@ +GetBible Scripture +SPDX-License-Identifier: GPL-2.0-only + GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + Version 2, June 1991 - Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software Foundation's +software and to any other program whose authors commit to using it. +(Some other Free Software Foundation software is covered by the GNU +Lesser General Public License instead.) You can apply it to your +programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it in +new free programs; and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as +a special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to this License. - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS @@ -628,47 +290,52 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least +convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) - This program is free software: you can redistribute it and/or modify + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see . + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md index efc904d..616443e 100644 --- a/README.md +++ b/README.md @@ -1 +1,151 @@ -# Scripture \ No newline at end of file +# GetBible Scripture + +[![CI](https://github.com/getbible/scripture/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/getbible/scripture/actions/workflows/ci.yml) +[![PHP](https://img.shields.io/badge/PHP-8.2--8.5-777bb4.svg)](composer.json) +[![Contract](https://img.shields.io/badge/contract-getbiblesword.ndjson%2Fv1-blue.svg)](docs/contract-v1.md) +[![License](https://img.shields.io/badge/license-GPL--2.0--only-blue.svg)](LICENSE) + +`getbible/scripture` is the object-oriented Bible application layer for the +native [`getbible/sword`](https://github.com/getbible/sword) PHP extension. It +validates the complete `getbiblesword.ndjson/v1` stream and exposes immutable, +lazy `Translation`, `Book`, `Chapter`, and `Verse` objects without loading an +entire Bible object graph into every PHP process. + +The package is deliberately Bible-only. Non-Bible SWORD modules remain visible +in the low-level catalog but are not exposed as Scripture translations. + +## Status + +Phases 0–3 are implemented. Installed SWORD modules are production-readable; +the package exposes capability-driven provisioning, bounded reader/writer +locking, durable interval state, per-module outcomes, Joomla Console commands, +and a Joomla Scheduled Tasks bridge. The current native ABI still reports +remote mutation as unavailable until its additive provisioning API is released. +See the +[roadmap](docs/roadmap.md) and [provisioning boundary](docs/provisioning.md). + +## Requirements + +- Linux with PHP 8.2, 8.3, 8.4, or 8.5. +- The `getbiblesword` PHP extension, installed through PIE. +- Joomla Framework Console, DI, Event, Filesystem, and Registry packages, + installed by Composer. +- A readable SWORD module root. + +```bash +pie install getbible/sword +php --ri getbiblesword +composer require getbible/scripture +``` + +## Quick start + +```php + '/var/lib/getbible/sword', + 'cache_path' => '/var/cache/getbible/scripture', +]); + +$container = ContainerFactory::create($configuration); + +/** @var ScriptureInterface $scripture */ +$scripture = $container->get(ScriptureInterface::class); + +$kjv = $scripture->translation('KJV'); +$john316 = $kjv->book('John')->chapter(3)->verse(16); +$text = $john316->stripped(); + +if ($text === null) { + throw new RuntimeException('This module does not provide stripped projections.'); +} + +echo $text->requireUtf8(), PHP_EOL; + +foreach ($kjv->verses('John', 3, 16, 18) as $verse) { + $text = $verse->stripped()?->requireUtf8() ?? $verse->raw()->requireUtf8(); + + printf( + "%s %d:%d %s\n", + $verse->scope()->bookName()->requireUtf8(), + $verse->scope()->chapter(), + $verse->scope()->verse(), + $text, + ); +} +``` + +The first request for an installed translation performs one full native export, +validates it, and creates an immutable indexed generation. Later requests open +that generation and hydrate only the requested objects. + +Initialize configured translations and run interval-based maintenance: + +```php +$initialization = $scripture->initialize(); +$maintenance = $scripture->refreshIfDue(); +``` + +No constructor performs network or full-module work. Both methods return +structured per-module results and continue safely across independent failures. + +## Available data layers + +Every verse retains: + +- authoritative raw bytes; +- SWORD default-rendered bytes; +- stripped text bytes; +- the exact verse key and scope; +- lossless lexical annotation segments; +- SWORD's ordered three-level official attribute map; and +- the original contract record. + +Every byte value verifies canonical Base64, decoded size, and SHA-256 before it +is exposed. The optional `utf8` member is treated only as a verified convenience +projection. + +## Configuration + +Configuration precedence is explicit array values, environment values, and +documented defaults: + +| Key | Environment variable | Default | +|---|---|---| +| `module_path` | `GETBIBLE_SCRIPTURE_MODULE_PATH` | Native extension resolution | +| `cache_path` | `GETBIBLE_SCRIPTURE_CACHE_PATH` | `$XDG_CACHE_HOME/getbible/scripture` | +| `refresh_interval` | `GETBIBLE_SCRIPTURE_REFRESH_INTERVAL` | `P1M` | +| `auto_refresh` | `GETBIBLE_SCRIPTURE_AUTO_REFRESH` | `true` | +| `lock_timeout` | `GETBIBLE_SCRIPTURE_LOCK_TIMEOUT` | `30` seconds | +| `modules` | `GETBIBLE_SCRIPTURE_MODULES` | All installed translations | +| `provisioning_enabled` | `GETBIBLE_SCRIPTURE_PROVISIONING_ENABLED` | `false` | +| `install_all` | `GETBIBLE_SCRIPTURE_INSTALL_ALL` | `false` | + +See [configuration](docs/configuration.md) for operational details. + +## Documentation + +- [Architecture](docs/architecture.md) +- [Public API](docs/api.md) +- [Configuration](docs/configuration.md) +- [Contract v1 mapping](docs/contract-v1.md) +- [Caching and refresh](docs/caching.md) +- [Module provisioning](docs/provisioning.md) +- [Production operations](docs/operations.md) +- [Roadmap](docs/roadmap.md) +- [Releasing](docs/releasing.md) + +## License + +GPL-2.0-only, matching the native `getBibleSword` and `getbible/sword` +foundation. Individual CrossWire modules retain their own licenses and +distribution terms. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..6d087cf --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,33 @@ +# Security policy + +## Supported versions + +Security fixes are applied to the latest released minor line. Until `1.0.0`, +only the most recent `0.x` release is supported. + +## Reporting + +Do not disclose a suspected vulnerability in a public issue. Use GitHub's +private vulnerability reporting for `getbible/scripture`. + +Include: + +- affected package and native extension versions; +- operating system and PHP version; +- a minimal reproducer; +- whether untrusted NDJSON, module archives, or module paths are involved; and +- the expected and observed behavior. + +## Trust boundaries + +SWORD modules and their metadata are untrusted input. This package verifies the +v1 stream, byte envelopes, artifact framing, sequence values, footer digest, and +success state before activating a snapshot. + +Raw and rendered markup is data, not trusted HTML. Callers must escape or +sanitize it for the destination context. + +Module installation is intentionally not implemented through ABI v1. A future +provisioner must add explicit repository policy, TLS requirements, archive +validation, licensing decisions, interprocess locks, staging, and atomic +activation. diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..0d91a54 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.3.0 diff --git a/bin/getbible-scripture b/bin/getbible-scripture new file mode 100755 index 0000000..c96aaf6 --- /dev/null +++ b/bin/getbible-scripture @@ -0,0 +1,21 @@ +#!/usr/bin/env php +execute(); diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..8f880cf --- /dev/null +++ b/composer.json @@ -0,0 +1,75 @@ +{ + "name": "getbible/scripture", + "description": "Validated, lazy Bible objects backed by CrossWire SWORD modules", + "type": "library", + "license": "GPL-2.0-only", + "homepage": "https://github.com/getbible/scripture", + "support": { + "issues": "https://github.com/getbible/scripture/issues", + "source": "https://github.com/getbible/scripture" + }, + "authors": [ + { + "name": "GetBible", + "homepage": "https://getbible.life" + } + ], + "keywords": [ + "bible", + "crosswire", + "getbible", + "joomla", + "scripture", + "sword" + ], + "require": { + "php": ">=8.2 <8.6", + "ext-getbiblesword": ">=0.1.0", + "ext-hash": "*", + "ext-json": "*", + "joomla/di": "^3.1.1 || ^4.0", + "joomla/console": "^3.0 || ^4.0", + "joomla/event": "^3.0.2 || ^4.0", + "joomla/filesystem": "^3.0 || ^4.0", + "joomla/registry": "^3.0.2 || ^4.0" + }, + "require-dev": { + "phpstan/phpstan": "^2.1", + "phpunit/phpunit": "^10.5 || ^11.5 || ^12.0", + "squizlabs/php_codesniffer": "^3.13" + }, + "suggest": { + "getbible/sword": "Install the native PHP extension with: pie install getbible/sword" + }, + "autoload": { + "psr-4": { + "GetBible\\Scripture\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GetBible\\Scripture\\Tests\\": "tests/" + } + }, + "bin": [ + "bin/getbible-scripture" + ], + "scripts": { + "check": [ + "@package-validate", + "@style", + "@analyse", + "@test" + ], + "package-validate": "composer validate --strict", + "style": "phpcs -p --standard=ruleset.xml src tests", + "analyse": "phpstan analyse --no-progress", + "test": "phpunit" + }, + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + }, + "sort-packages": true + } +} diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..1510557 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,146 @@ +# Public API + +## Composition + +```php +$configuration = Configuration::fromEnvironment([ + 'module_path' => '/var/lib/getbible/sword', + 'cache_path' => '/var/cache/getbible/scripture', +]); + +$container = ContainerFactory::create($configuration); +$scripture = $container->get(ScriptureInterface::class); +``` + +Applications already using Joomla DI can register `ScriptureServiceProvider` +with their own container and pre-register `Configuration` when they need custom +values. + +## Scripture service + +```php +$translations = $scripture->translations(); +$translation = $scripture->translation('KJV'); +$verse = $scripture->verse('KJV', 'John', 3, 16); +$range = $scripture->verses('KJV', 'John', 3, 16, 18); +$scripture->refreshTranslation('KJV'); +$scripture->provisioningCapabilities(); +$scripture->installTranslations(['KJV', 'WEB']); +$scripture->installAllTranslations(); +$scripture->refreshSelectedModules(['KJV']); +$scripture->refreshModules(); +$scripture->removeTranslation('KJV'); +$scripture->initialize(); +$scripture->refresh(); +$scripture->refreshIfDue(); +$scripture->maintenanceStatus(); +``` + +`translations()` lists installed Bible modules. `translation()` opens the +current valid snapshot or performs one full warm-up. A forced refresh re-exports +the installed module and activates a new generation only after validation. + +Provisioning methods are stable even when the injected native backend cannot +perform them. Inspect `provisioningCapabilities()` first. The default +getBibleSword ABI v1 adapter accurately reports every mutating capability as +unavailable and throws `ProvisioningUnavailableException` when called. + +`initialize()`, `refresh()`, and `refreshIfDue()` return `MaintenanceResult` +objects with ordered snapshot outcomes, the optional native provisioning +result, operation errors, timestamps, and interval status. These operations +continue across independent module failures and report partial failure through +`succeeded()`. + +## Translation + +```php +$translation->moduleName(); +$translation->metadata(); +$translation->books(); +$translation->book('John'); +$translation->bookByPosition(testament: 2, book: 4); +$translation->verses('John', 3, 16, 18); +$translation->configEntries('DistributionLicense'); +$translation->rawExportPath(); +``` + +Configuration entries are ordered and repeated keys are preserved. + +## Book + +```php +$book->testament(); +$book->position(); +$book->name(); +$book->abbreviation(); +$book->versification(); +$book->chapters(); +$book->chapter(3); +``` + +`position()` is the SWORD `VerseKey` book position within its versification and +testament. It is not assumed to be a universal 1-66 number. + +## Chapter + +```php +$chapter->number(); +$chapter->verse(16); +$chapter->verses(); +$chapter->verses(16, 18); +$chapter->introductions(); +``` + +Ranges are inclusive. A reversed or invalid range throws +`InvalidReferenceException`. + +## Verse + +```php +$verse->scope(); +$verse->key(); +$verse->raw(); +$verse->rendered(); +$verse->stripped(); +$verse->annotationSegments(); +$verse->officialAttributes(); +$verse->contractRecord(); +``` + +`raw()`, `rendered()`, and `stripped()` return verified `ByteValue` objects. +`rendered()` and `stripped()` may be `null` only when the native producer could +not create projections. + +## Byte values + +```php +$bytes = $value->bytes(); +$utf8 = $value->utf8(); +$requiredUtf8 = $value->requireUtf8(); +$hash = $value->sha256(); +$size = $value->size(); +$originalEnvelope = $value->toArray(); +``` + +`requireUtf8()` throws when no exact UTF-8 projection exists. It never attempts a +lossy conversion. + +## Events + +The default Joomla dispatcher emits: + +- `onGetBibleScriptureWarmStarted` +- `onGetBibleScriptureWarmCompleted` +- `onGetBibleScriptureWarmFailed` +- `onGetBibleScriptureRefreshStarted` +- `onGetBibleScriptureRefreshCompleted` +- `onGetBibleScriptureRefreshFailed` +- `onGetBibleScriptureProvisioningStarted` +- `onGetBibleScriptureProvisioningCompleted` +- `onGetBibleScriptureProvisioningFailed` +- `onGetBibleScriptureMaintenanceStarted` +- `onGetBibleScriptureMaintenanceCompleted` +- `onGetBibleScriptureMaintenanceFailed` + +Each event contains the module name and the relevant snapshot or exception. +Listeners must not mutate an active generation. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..3a17174 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,153 @@ +# Architecture + +## Objective + +GetBible Scripture is the reusable Bible application layer above +`getbible/sword`. It turns a validated, deterministic native export into fast, +immutable, lazily hydrated Scripture objects. + +```text +Application + -> ScriptureInterface + -> MaintenanceService + -> ProvisioningCoordinatorInterface + -> TranslationSnapshotManager + -> ContractV1Validator + -> ModuleExtractorInterface + -> SwordEngineAdapter + -> GetBible\Sword\Engine + -> getBibleSword 0.3.0 / SWORD 1.9.0 +``` + +The Joomla DI container is the composition root. Domain objects never fetch +dependencies from it; each dependency is passed explicitly. + +## Design boundaries + +### Native extraction + +`GetBible\Sword\Engine` is final and exposes only complete streamed module lists +and complete streamed module exports. `SwordEngineAdapter` isolates that final +extension class behind `ModuleExtractorInterface`. + +### Contract validation + +`ContractV1Validator` incrementally checks: + +- LF framing; +- consecutive sequence numbers; +- record phase order; +- required record shapes; +- canonical and hashed byte envelopes; +- ordered annotation reconstruction; +- ordered official attributes; +- artifact identifiers, chunks, sizes, and hashes; +- record and diagnostic counts; +- the exact pre-footer SHA-256; and +- a successful footer. + +An observer receives validated records and exact file offsets. It never receives +unvalidated domain objects. + +### Snapshots + +A complete module export is written to a staging generation. Validation builds a +small JSON index containing verse offsets and module/configuration metadata. The +generation directory is renamed into its content hash, and an atomic `current.json` +pointer activates it. + +```text +cache/ + translations/ + KJV/ + current.json + warm.lock + generations/ + / + module.ndjson + index.json +``` + +Old generations are immutable. A process that already opened one can continue +reading while a later process activates another generation. + +### Domain model + +`Translation`, `Book`, and `Chapter` contain compact coordinates and a shared +snapshot reader. `Verse` is hydrated only when requested. A translation object +therefore represents the complete translation without allocating every verse, +annotation, and attribute in memory. + +Book identity is the module-specific tuple of versification, testament, and book +position. Names and abbreviations are lookup aliases, not universal IDs. + +Introductions are indexed separately and never represented as verse zero. + +### Provisioning + +Native ABI v1 cannot install or update modules. `ModuleProvisionerInterface` +and `ProvisioningCoordinatorInterface` allow the eventual native provisioning +implementation to be injected without changing the Scripture API. Capability +discovery keeps ABI limitations explicit. See [provisioning](provisioning.md). + +### Automated maintenance + +`MaintenanceServiceInterface` is the sole orchestration boundary for +initialization, forced refresh, interval-gated refresh, and health status. A +whole-run lock prevents overlapping scheduler executions. Within one run, +translation failures are isolated and returned as immutable per-module +outcomes. + +The durable `maintenance/state.json` records the last attempt, last complete +success, last failure, failure summary, and consecutive failure count. Only a +complete success advances the interval anchor. State is written to a +synchronized temporary file and atomically renamed into place. + +Joomla Console commands, Joomla Scheduled Tasks integrations, cron, and systemd +all invoke this same service. They do not reproduce lifecycle policy. + +## SOLID application + +- Single responsibility: native extraction, validation, indexing, querying, + refresh policy, and events are separate services. +- Open/closed: ABI or persistence implementations can be added behind existing + interfaces. +- Liskov substitution: test engines and future native engines obey the same + streaming contract. +- Interface segregation: callers depend on query, extraction, or provisioning + contracts instead of one large manager. +- Dependency inversion: application services depend on interfaces; Joomla DI + creates concrete infrastructure. + +## Concurrency + +Snapshot warming uses an interprocess `flock`. The active generation is checked +again after acquiring the lock so only one process performs an extraction. + +Every native export also holds a bounded shared module-root lifecycle lock. +Provisioning holds the matching exclusive lock, so cooperating application +processes cannot replace module files while the native engine reads them. + +A separate bounded maintenance lock serializes complete scheduled runs. Lock +acquisition has a configurable timeout; it never waits indefinitely. + +The native extension serializes SWORD access within one PHP process. Different +processes remain independent. + +A future native module provisioner must additionally enforce repository, +staging, atomic-install, and rollback policy within its own boundary. Snapshot +immutability does not make an in-place native install safe. + +## Failure behavior + +A failed export, failed validation, failed index write, or failed activation +removes its staging directory and leaves the active generation unchanged. +Native exceptions retain their original status code as the previous exception. + +A partially failed maintenance run preserves the prior `last_success_at`, stores +the new failure, and returns a non-zero console exit code. Healthy modules still +complete, which prevents one malformed translation from starving every other +translation. + +No constructor performs network I/O, module installation, or a full translation +export. diff --git a/docs/caching.md b/docs/caching.md new file mode 100644 index 0000000..d3fa7c4 --- /dev/null +++ b/docs/caching.md @@ -0,0 +1,55 @@ +# Caching and refresh + +## Warm-on-first-query + +When a translation is requested: + +1. resolve its active generation; +2. reuse it when it exists and is fresh; +3. acquire the module warm lock when it is absent or stale; +4. check the active generation again; +5. stream the complete native module into staging; +6. validate and index the staged stream; +7. rename staging into its stream-hash generation; +8. atomically replace the `current.json` pointer; and +9. open the immutable index. + +Only the compact index is loaded into memory. Verse records are read by exact +offset from `module.ndjson`. + +## Generation identity + +The validated footer `stream_sha256` names the generation. The generated time is +operational metadata and is not part of the native deterministic contract. + +Different absolute SWORD roots can affect preserved configuration values. +Generation identity must therefore be treated as an export identity, not as an +upstream module-version number. + +## Refresh types + +`refreshTranslation()` re-exports an already installed module and rebuilds its +snapshot. + +A module update is a different operation: it changes the source SWORD root and +must be implemented by `ModuleProvisionerInterface` under an exclusive root +lock. ABI v1 does not currently provide that operation. + +## Scheduling + +Instantiation does not start a background process. Reliable execution belongs +to an external scheduler: + +```php +$scripture->refreshIfDue(); +``` + +Joomla CMS integrations can inject `ScheduledRefreshHandler`. CLI applications +can run `scripture:refresh --if-due` from cron or a systemd timer. See +[production operations](operations.md). + +## Cleanup + +The first release retains prior immutable generations so active readers cannot +lose files. Bounded generation cleanup is a later hardening phase and must use +reader-aware retention. diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..695661a --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,112 @@ +# Configuration + +## Sources and precedence + +`Configuration::fromEnvironment()` applies: + +1. explicit array values; +2. environment variables; +3. defaults. + +A userland Composer package cannot register PHP INI directives. The package does +not claim custom `ini_set()` support. + +## Settings + +### `module_path` + +Environment: `GETBIBLE_SCRIPTURE_MODULE_PATH` + +An absolute SWORD installation root. When omitted, the native extension resolves +its configured `getbiblesword.module_path`, `SWORD_PATH`, or effective-user +default. Production applications should provide an explicit path. + +### `cache_path` + +Environment: `GETBIBLE_SCRIPTURE_CACHE_PATH` + +The durable snapshot root. The default is: + +1. `$XDG_CACHE_HOME/getbible/scripture`; +2. `$HOME/.cache/getbible/scripture`; or +3. the operating-system temporary directory plus + `/getbible-scripture-`. + +The PHP worker must be able to create directories, lock files, staged exports, +indexes, and atomic pointer files below this path. + +### `refresh_interval` + +Environment: `GETBIBLE_SCRIPTURE_REFRESH_INTERVAL` + +An ISO-8601 duration accepted by `DateInterval`, default `P1M`. + +Examples: + +```text +P1D +P1W +P1M +P3M +``` + +### `auto_refresh` + +Environment: `GETBIBLE_SCRIPTURE_AUTO_REFRESH` + +Accepted true values are `1`, `true`, `yes`, and `on`. Accepted false values are +`0`, `false`, `no`, and `off`. The default is true. + +Automatic refresh means a stale installed-module snapshot is rebuilt when it is +next requested. It does not mean that a PHP process creates a background timer, +and it does not download newer module files under ABI v1. + +## Monthly rotation + +The active snapshot records its generation time. When auto refresh is enabled +and that time plus the configured interval is in the past, the next query warms +a replacement generation under the interprocess lock. + +For predictable maintenance windows, call `refreshTranslation()` from a Joomla +Scheduled Task, cron command, or systemd timer. + +### `lock_timeout` + +Environment: `GETBIBLE_SCRIPTURE_LOCK_TIMEOUT` + +A positive integer number of seconds, default `30`. Native extraction uses a +shared application lock and provisioning uses the matching exclusive lock. A +bounded timeout prevents PHP workers from waiting indefinitely behind a failed +or overloaded maintenance process. + +### `modules` + +Environment: `GETBIBLE_SCRIPTURE_MODULES` + +An explicit PHP list or comma-separated environment value containing exact +translation module identifiers. Maintenance CLI options override this list for +one run. An empty list means every currently installed Bible translation. + +### `provisioning_enabled` + +Environment: `GETBIBLE_SCRIPTURE_PROVISIONING_ENABLED` + +Defaults to false. When false, initialization and refresh may read installed +modules and rebuild snapshots but cannot mutate the SWORD root. When true, the +injected backend must still advertise each requested capability. + +### `install_all` + +Environment: `GETBIBLE_SCRIPTURE_INSTALL_ALL` + +Defaults to false. Enabling it makes parameterless `initialize()` request every +policy-approved translation. Configuration rejects this setting unless +`provisioning_enabled` is also true. + +## Durable maintenance state + +Maintenance state is stored at `/maintenance/state.json` through a +synchronized temporary file and atomic rename. It records the last attempt, +complete success, failure, error summary, and consecutive failure count. + +`refreshIfDue()` advances its interval only after a completely successful run. diff --git a/docs/contract-v1.md b/docs/contract-v1.md new file mode 100644 index 0000000..a84eb36 --- /dev/null +++ b/docs/contract-v1.md @@ -0,0 +1,102 @@ +# getBibleSword contract v1 mapping + +## Compatibility gate + +The package accepts only: + +```text +contract: getbiblesword.ndjson/v1 +contract_version: 1 +native ABI: 1 +``` + +The native product version is reported separately and is not used to infer the +contract. + +## Record mapping + +| v1 record | Scripture use | +|---|---| +| `header` | producer, contract, command, and SWORD provenance | +| `module` | `TranslationMetadata` for `classification=bible` | +| `config_source` | retained in the raw export | +| `config_entry` | ordered `ConfigEntry` metadata | +| `entry` | `Verse`, or separately indexed introduction | +| `artifact_*` | fully validated and retained in the raw export | +| `diagnostic` | retained and counted | +| `footer` | activation gate and generation identity | + +## Byte values + +Every source-derived byte value is represented by Base64, size, and SHA-256. +`ByteValue::fromArray()`: + +1. requires `encoding=base64`; +2. performs strict Base64 decoding; +3. requires canonical re-encoding; +4. verifies decoded size; +5. verifies SHA-256; and +6. verifies that optional `utf8` is byte-identical to the decoded value. + +Decoded bytes are authoritative. + +## Scope + +Bible entries use `scope.type=verse_key`. The package retains: + +- testament; +- book position; +- chapter and verse; +- suffix; +- entry index; +- introduction scope; +- OSIS reference; +- book name and abbreviation; and +- versification. + +An ordinary verse requires positive book, chapter, and verse values and +`intro_scope=verse`. Module, testament, book, and chapter introductions are +indexed separately. + +## Annotation segments + +The producer's annotation segments are lexical `text`, `markup`, or `entity` +slices. Markup and entities are `uninterpreted`; this package does not relabel +them as semantic spans. + +The validator requires concatenated segment bytes to reproduce `entry.raw` +exactly. Applications may add markup-specific adapters above this lossless layer. + +## Official attributes + +SWORD official attributes are retained as ordered: + +```text +OfficialAttributeType + -> OfficialAttributeList + -> OfficialAttributeValue +``` + +Repeated names and source order are not collapsed into associative arrays. + +## Whole-stream validation + +JSON Schema validation alone is insufficient. The package independently checks +sequence, phase order, framing, byte envelopes, annotation reconstruction, +artifact state, counts, footer success, and the exact stream digest. + +The current reference Python validator can return process exit zero for a +structurally valid `success:false` footer. This package inspects the footer +itself and rejects it. + +## Unknown data + +Unknown additive record members remain present in the original record. Unknown +record types are rejected within contract v1 because their ordering and hashing +semantics are not defined by the accepted validator. + +Normative upstream documentation: + +- https://github.com/getbible/getbiblesword/blob/main/docs/contract-v1.md +- https://github.com/getbible/getbiblesword/blob/main/schema/v1/contract.schema.json +- https://github.com/getbible/getbiblesword/blob/main/docs/downstream-integration.md diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..7212241 --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,177 @@ +# Production operations + +## Lifecycle semantics + +The public service exposes three explicit maintenance operations: + +```php +$scripture->initialize(); +$scripture->refresh(); +$scripture->refreshIfDue(); +``` + +`initialize()` installs missing configured translations only when runtime policy +enables provisioning and the injected backend advertises the required +capability. It then opens or warms validated snapshots for every target. + +`refresh()` invokes remote module refresh only when `provisioning_enabled` is +true. It always rebuilds snapshots for installed targets. Under getBibleSword +ABI v1, leave provisioning disabled and manage the SWORD module root through a +separate trusted deployment process. + +`refreshIfDue()` compares durable last-success state with `refresh_interval`. +The default is one calendar month. A failed or partially failed run does not +advance last-success time, so the next scheduler invocation retries. + +All operations: + +- take one bounded whole-run maintenance lock; +- isolate snapshot failures by module; +- preserve the last active snapshot on export or validation failure; +- write maintenance state through a synchronized temporary file and atomic + rename; +- emit Joomla lifecycle events; and +- return a structured `MaintenanceResult`. + +## CLI + +Composer exposes the Joomla Console application as +`vendor/bin/getbible-scripture`. + +```bash +vendor/bin/getbible-scripture scripture:status +vendor/bin/getbible-scripture scripture:initialize --module=KJV --module=WEB +vendor/bin/getbible-scripture scripture:initialize --all +vendor/bin/getbible-scripture scripture:refresh --module=KJV +vendor/bin/getbible-scripture scripture:refresh --if-due +``` + +Every command writes deterministic JSON. Initialization and refresh return exit +code `0` only when the complete result succeeds, and `1` for partial or complete +failure. Bootstrap and uncaught application failures use a non-zero Joomla +Console exit code. + +`--all` remains an explicit operation. It also requires +`GETBIBLE_SCRIPTURE_PROVISIONING_ENABLED=true` and a native backend that +advertises all-module installation. + +## Environment + +A production deployment can use: + +```dotenv +GETBIBLE_SCRIPTURE_MODULE_PATH=/var/lib/getbible/sword +GETBIBLE_SCRIPTURE_CACHE_PATH=/var/cache/getbible/scripture +GETBIBLE_SCRIPTURE_MODULES=KJV,WEB +GETBIBLE_SCRIPTURE_REFRESH_INTERVAL=P1M +GETBIBLE_SCRIPTURE_AUTO_REFRESH=true +GETBIBLE_SCRIPTURE_PROVISIONING_ENABLED=false +GETBIBLE_SCRIPTURE_INSTALL_ALL=false +GETBIBLE_SCRIPTURE_LOCK_TIMEOUT=30 +``` + +The PHP-FPM and scheduler users must share read access to the SWORD root and +read/write access to the cache root. Run maintenance as the same operating +system identity as the application whenever possible. + +## Cron + +The command contains its own bounded interprocess lock, so overlapping cron +runs safely serialize: + +```cron +17 3 * * * cd /srv/getbible-app && /usr/bin/php vendor/bin/getbible-scripture scripture:refresh --if-due >> /var/log/getbible-scripture.log 2>&1 +``` + +Run the cron entry daily or weekly; durable interval state decides whether the +monthly work is due. + +## systemd + +`/etc/systemd/system/getbible-scripture.service`: + +```ini +[Unit] +Description=GetBible Scripture maintenance +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +User=www-data +Group=www-data +WorkingDirectory=/srv/getbible-app +EnvironmentFile=/etc/getbible/scripture.env +ExecStart=/usr/bin/php vendor/bin/getbible-scripture scripture:refresh --if-due +PrivateTmp=true +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/var/cache/getbible/scripture +ReadOnlyPaths=/var/lib/getbible/sword +``` + +`/etc/systemd/system/getbible-scripture.timer`: + +```ini +[Unit] +Description=Run GetBible Scripture maintenance daily + +[Timer] +OnCalendar=*-*-* 03:17:00 +Persistent=true +RandomizedDelaySec=15m +Unit=getbible-scripture.service + +[Install] +WantedBy=timers.target +``` + +Enable the timer: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now getbible-scripture.timer +systemctl list-timers getbible-scripture.timer +``` + +If the future native provisioner writes to the SWORD root, change its systemd +path allowance from `ReadOnlyPaths` to the narrow required `ReadWritePaths`. + +## Joomla Scheduled Tasks + +`ScheduledRefreshHandler` is registered in the same Joomla DI container as the +Scripture service: + +```php +use GetBible\Scripture\Integration\Joomla\ScheduledRefreshHandler; + +$handler = $container->get(ScheduledRefreshHandler::class); +$result = $handler(); +``` + +A Joomla CMS scheduler plugin can call this service from its task execution +callback, log `MaintenanceResult::toArray()`, and map `succeeded()` to the CMS +task success/failure status. The handler performs interval gating itself, so +the CMS task can run daily without forcing a monthly refresh on every run. + +## Health checks + +Use: + +```bash +vendor/bin/getbible-scripture scripture:status +``` + +The JSON includes: + +- whether maintenance is due; +- the next due time; +- last attempt, success, and failure timestamps; +- consecutive failures and the last error; +- configured and installed translations; +- runtime provisioning policy; and +- exact native backend capabilities. + +Alert on a non-null `last_error`, increasing `consecutive_failures`, or a due +state that remains unchanged across multiple scheduler invocations. diff --git a/docs/provisioning.md b/docs/provisioning.md new file mode 100644 index 0000000..96cc3cb --- /dev/null +++ b/docs/provisioning.md @@ -0,0 +1,92 @@ +# Module provisioning + +## Current boundary + +`getbible/sword` 0.1.0 embeds getBibleSword 0.3.0 ABI v1. It can list and export +local modules. It cannot: + +- enumerate remote repositories; +- download or install a module; +- accept repository disclaimers; +- update or remove a module; +- verify a remote package; +- lock and atomically replace a module root; or +- query a single remote reference. + +GetBible Scripture does not disguise a direct archive download as equivalent +native installation. `ModuleProvisionerInterface` is injectable, and +`ProvisioningCoordinatorInterface` provides the stable application boundary. +The default ABI-v1 implementation reports exact unavailable capabilities. + +```php +$capabilities = $scripture->provisioningCapabilities(); + +if ($capabilities->canInstallSelected()) { + $result = $scripture->installTranslations(['KJV', 'WEB']); +} +``` + +The public boundary supports selected and all-module installation, selected or +all-installed refresh, and removal. Each completed backend operation returns +ordered `ModuleProvisioningResult` objects with changed, skipped, or failed +status. Partial failure is therefore never hidden in a single boolean. + +The library takes a bounded exclusive application lock around provisioning. +Native extraction takes the matching shared lock. This prevents cooperating +Scripture processes from reading the module root during mutation. The future +native backend must still provide repository validation, staged installation, +atomic activation, and rollback guarantees. + +## Required production workflow + +The planned native provisioner must: + +1. select an explicit repository; +2. enforce HTTPS/TLS policy; +3. refresh and validate its catalog; +4. expose module license and disclaimer data; +5. record explicit acceptance where required; +6. download into a size-bounded staging area; +7. verify checksums or signed provenance when available; +8. reject traversal, links, devices, and unsafe archive entries; +9. acquire an exclusive interprocess module-root lock; +10. install into a versioned root; +11. validate the installed root with native `streamModules()`; +12. build Scripture snapshots; +13. atomically activate the root and snapshots together; and +14. retain the previous generation for rollback. + +All-module installation must remain an explicit operation because translations +have independent licenses and can consume substantial disk and network +resources. + +## Proposed additive native API + +Provisioning should be added without changing ABI v1 extraction symbols: + +```text +gbs_list_remote_modules_v2 +gbs_sync_repository_v2 +gbs_install_module_v2 +gbs_update_module_v2 +gbs_remove_module_v2 +``` + +The PHP extension should expose a separate installer/manager object rather than +adding network side effects to `GetBible\Sword\Engine`. + +## Public lifecycle + +```php +$scripture->initialize(); // explicit install of configured Bible modules +$scripture->refresh(); // explicit remote sync + atomic update +$scripture->refreshIfDue(); +``` + +These methods are implemented by `MaintenanceServiceInterface`. Under ABI v1, +initialization warms installed modules and reports missing modules precisely. +Remote mutation occurs only when configuration explicitly enables it and the +injected backend advertises the matching capability. + +The default interval is `P1M`, overridable through configuration. Durable +last-success state ensures a failure never postpones the next retry. diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 0000000..67c925b --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,39 @@ +# Releasing + +## Before `0.1.0` + +1. Complete the Phase 1 release gates in the roadmap. +2. Install `getbible/sword` through PIE in the integration job. +3. Verify the package name `getbible/scripture` on Packagist. +4. Configure Packagist's GitHub hook. +5. Confirm the repository ruleset protects `main` and release tags. + +## Release preparation + +1. Update `VERSION`. +2. Move applicable changelog entries from `Unreleased` into the version. +3. Run: + + ```bash + composer check + ``` + +4. Verify the installed-module integration workflow and retained evidence. +5. Merge through a maintainer-reviewed pull request. +6. Create an annotated `vVERSION` tag. + +Packagist consumes the Composer package from the Git tag. The native extension +remains a separate PIE installation. + +## Compatibility declarations + +A release must state: + +- PHP versions; +- Joomla Framework major versions; +- `getbible/sword` extension version; +- getBibleSword product and ABI versions; +- NDJSON contract identifier; and +- SWORD engine version. + +Do not infer contract compatibility from the package tag alone. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..0f0835d --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,61 @@ +# Roadmap + +## Phase 0 — foundation + +- GPL-compatible package identity. +- Composer and Joomla Framework dependencies. +- DI composition root. +- Configuration, exceptions, contracts, events, CI, and documentation. + +## Phase 1 — installed-module MVP (`0.1.0`) + +- Native engine adapter. +- Independent streaming v1 validator. +- Atomic indexed generations. +- Lazy Translation, Book, Chapter, Verse, range, metadata, annotation, and + attribute APIs. +- Monthly configurable snapshot rotation. +- Deterministic unit fixtures and KJV integration evidence. +- Packagist registration and first release. + +## Phase 2 — production provisioning boundary (`0.2.0`) + +- Explicit provisioning capability discovery. +- Selected/all-translation installation, refresh, and removal contracts. +- Per-module operation results and lifecycle events. +- Bounded shared/exclusive application locking around native readers and writers. +- Atomic catalog and snapshot invalidation after mutation. +- Exact ABI v1 unavailable adapter instead of unsafe archive downloading. + +The matching additive getBibleSword provisioning ABI and `getbible/sword` +installer object are external integration gates. Once released, their adapter +can replace `AbiV1ModuleProvisioner` without changing the public Scripture API. + +## Phase 3 — automated maintenance (`0.3.0`) + +- `initialize()`, `refresh()`, and `refreshIfDue()` over the native provisioner. +- Durable last-attempt, success, failure, and interval state. +- Non-overlapping maintenance runs with per-module failure isolation. +- Joomla Console initialization, refresh, and status commands. +- Joomla Scheduled Tasks callable integration. +- Systemd and cron deployment examples. +- Deterministic JSON results, exit codes, and lifecycle events. + +## Phase 4 — production hardening and `1.0.0` + +- Bounded APCu/LRU adapters and benchmarks. +- Reader-aware generation cleanup. +- Corruption and crash recovery. +- Concurrency, fuzz, and hostile-module tests. +- Multilingual and alternate-versification corpus. +- Stable public API and schema review. + +## Release gates + +The first stable release requires: + +- the upstream v1 schema classification review to be accepted; +- no failed contract, static-analysis, style, or unit checks; +- real KJV Revelation 1 and 22 parity; +- at least one full installed translation query test; and +- maintainer approval of module licensing behavior. diff --git a/llms.txt b/llms.txt new file mode 100644 index 0000000..0fbfe43 --- /dev/null +++ b/llms.txt @@ -0,0 +1,34 @@ +# GetBible Scripture + +Canonical repository: https://github.com/getbible/scripture +Package: getbible/scripture +Namespace: GetBible\Scripture +License: GPL-2.0-only + +Purpose: validate getBibleSword NDJSON v1 and expose lazy Translation, Book, +Chapter, and Verse objects over installed CrossWire SWORD Bible modules. + +Native dependency: +- PIE package: getbible/sword +- PHP extension: getbiblesword +- PHP namespace: GetBible\Sword +- native engine: getBibleSword 0.3.0 +- C ABI: 1 +- NDJSON contract: getbiblesword.ndjson/v1 +- SWORD engine: 1.9.0 + +Start with README.md and docs/architecture.md. The normative protocol source is +https://github.com/getbible/getbiblesword/blob/main/docs/contract-v1.md. + +Important rules: +- decoded Base64 bytes are authoritative; +- validate complete streams before using records; +- do not eagerly materialize an entire Bible; +- book positions are module-versification-specific, not universal 1-66 IDs; +- introductions are not verse zero; +- raw annotation markup is untrusted and lexically segmented, not interpreted; +- ABI v1 cannot install or update modules; +- constructors must not perform network operations. +- scheduled work must enter through MaintenanceServiceInterface; +- only a completely successful maintenance run advances last_success_at; +- remote module mutation requires both runtime policy and backend capability. diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 0000000..f2fa838 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,10 @@ +parameters: + level: max + paths: + - src + - tests + tmpDir: build/phpstan + treatPhpDocTypesAsCertain: true + reportUnmatchedIgnoredErrors: true + scanFiles: + - stubs/getbible-sword.php diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..7878707 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,19 @@ + + + + + tests + + + + + src + + + diff --git a/ruleset.xml b/ruleset.xml new file mode 100644 index 0000000..b09582f --- /dev/null +++ b/ruleset.xml @@ -0,0 +1,9 @@ + + + GetBible Scripture coding standard. + src + tests + + + + diff --git a/src/Catalog/ModuleCatalog.php b/src/Catalog/ModuleCatalog.php new file mode 100644 index 0000000..fedfffb --- /dev/null +++ b/src/Catalog/ModuleCatalog.php @@ -0,0 +1,124 @@ +|null + * @since 0.1.0 + */ + private ?array $translations = null; + + /** + * Creates the catalog service. + * + * @param ModuleExtractorInterface $extractor Native stream adapter. + * @param ContractV1ValidatorInterface $validator Stream validator. + * + * @since 0.1.0 + */ + public function __construct( + private ModuleExtractorInterface $extractor, + private ContractV1ValidatorInterface $validator, + ) { + } + + /** + * Returns all installed Bible modules. + * + * @return list + * @since 0.1.0 + */ + public function translations(): array + { + if ($this->translations !== null) { + return $this->translations; + } + + $stream = tmpfile(); + + if (!is_resource($stream)) { + throw new \RuntimeException('Unable to create a temporary module-list stream.'); + } + + try { + $written = $this->extractor->streamModules($stream); + + if (fflush($stream) === false || fseek($stream, 0) !== 0) { + throw new \RuntimeException('Unable to rewind the native module-list stream.'); + } + + $stats = fstat($stream); + + if (!is_array($stats) || $stats['size'] !== $written) { + throw new ContractException('Native module-list byte count does not match its stream.'); + } + + $result = $this->validator->validate($stream); + } finally { + fclose($stream); + } + + if ($result->command() !== 'list') { + throw new ContractException('The native module catalog emitted a non-list stream.'); + } + + $this->translations = array_values(array_filter( + $result->modules(), + static fn (TranslationMetadata $metadata): bool => $metadata->isBible(), + )); + + return $this->translations; + } + + /** + * Returns one exact installed Bible module. + * + * @param string $module Exact native module identifier. + * + * @return TranslationMetadata + * @since 0.1.0 + */ + public function translation(string $module): TranslationMetadata + { + foreach ($this->translations() as $translation) { + if ($translation->name()->bytes() === $module) { + return $translation; + } + } + + throw new TranslationNotFoundException(sprintf( + 'Installed Bible translation "%s" was not found.', + $module, + )); + } + + /** + * Clears the process-local catalog. + * + * @return void + * @since 0.1.0 + */ + public function clear(): void + { + $this->translations = null; + } +} diff --git a/src/Catalog/ModuleCatalogInterface.php b/src/Catalog/ModuleCatalogInterface.php new file mode 100644 index 0000000..b58aff5 --- /dev/null +++ b/src/Catalog/ModuleCatalogInterface.php @@ -0,0 +1,43 @@ + + * @since 0.1.0 + */ + public function translations(): array; + + /** + * Returns one installed Bible module by its exact identifier. + * + * @param string $module Exact native module identifier. + * + * @return TranslationMetadata + * @since 0.1.0 + */ + public function translation(string $module): TranslationMetadata; + + /** + * Clears the process-local module list. + * + * @return void + * @since 0.1.0 + */ + public function clear(): void; +} diff --git a/src/Clock/ClockInterface.php b/src/Clock/ClockInterface.php new file mode 100644 index 0000000..831acc4 --- /dev/null +++ b/src/Clock/ClockInterface.php @@ -0,0 +1,23 @@ +registry = $registry; + } + + /** + * Creates configuration from explicit values, environment, and defaults. + * + * @param array|null> $values Explicit configuration. + * + * @return self + * @since 0.1.0 + */ + public static function fromEnvironment(array $values = []): self + { + $modulePath = self::firstString( + $values['module_path'] ?? null, + self::environment('GETBIBLE_SCRIPTURE_MODULE_PATH'), + ); + $cachePath = self::firstString( + $values['cache_path'] ?? null, + self::environment('GETBIBLE_SCRIPTURE_CACHE_PATH'), + self::defaultCachePath(), + ); + $refreshInterval = self::firstString( + $values['refresh_interval'] ?? null, + self::environment('GETBIBLE_SCRIPTURE_REFRESH_INTERVAL'), + self::DEFAULT_REFRESH_INTERVAL, + ); + $autoRefresh = self::booleanValue( + $values['auto_refresh'] ?? self::environment('GETBIBLE_SCRIPTURE_AUTO_REFRESH'), + true, + ); + $lockTimeout = self::positiveInteger( + $values['lock_timeout'] ?? self::environment('GETBIBLE_SCRIPTURE_LOCK_TIMEOUT'), + self::DEFAULT_LOCK_TIMEOUT, + 'lock timeout', + ); + $modules = self::moduleList( + $values['modules'] ?? self::environment('GETBIBLE_SCRIPTURE_MODULES'), + ); + $provisioningEnabled = self::booleanValue( + $values['provisioning_enabled'] ?? self::environment('GETBIBLE_SCRIPTURE_PROVISIONING_ENABLED'), + false, + ); + $installAll = self::booleanValue( + $values['install_all'] ?? self::environment('GETBIBLE_SCRIPTURE_INSTALL_ALL'), + false, + ); + + if ($cachePath === null) { + throw new \InvalidArgumentException('A non-empty Scripture cache path is required.'); + } + + if ($refreshInterval === null) { + throw new \InvalidArgumentException('A non-empty refresh interval is required.'); + } + + try { + $interval = new \DateInterval($refreshInterval); + } catch (\Exception $exception) { + throw new \InvalidArgumentException( + sprintf('Invalid ISO-8601 refresh interval "%s".', $refreshInterval), + 0, + $exception, + ); + } + + $epoch = new \DateTimeImmutable('@0'); + + if ($interval->invert === 1 || $epoch->add($interval) <= $epoch) { + throw new \InvalidArgumentException('The refresh interval must advance time.'); + } + + if ($installAll && !$provisioningEnabled) { + throw new \InvalidArgumentException( + 'All-module installation requires explicit provisioning_enabled configuration.', + ); + } + + return new self(new Registry([ + 'module_path' => $modulePath, + 'cache_path' => self::normalizePath($cachePath), + 'refresh_interval' => $refreshInterval, + 'auto_refresh' => $autoRefresh, + 'lock_timeout' => $lockTimeout, + 'modules' => $modules, + 'provisioning_enabled' => $provisioningEnabled, + 'install_all' => $installAll, + ])); + } + + /** + * Returns the explicit SWORD root or null for native resolution. + * + * @return string|null + * @since 0.1.0 + */ + public function modulePath(): ?string + { + $value = $this->registry->get('module_path'); + + return is_string($value) && $value !== '' ? $value : null; + } + + /** + * Returns the durable snapshot cache root. + * + * @return string + * @since 0.1.0 + */ + public function cachePath(): string + { + $value = $this->registry->get('cache_path'); + + if (!is_string($value) || $value === '') { + throw new \LogicException('Normalized cache path configuration is invalid.'); + } + + return $value; + } + + /** + * Returns the configured ISO-8601 refresh interval. + * + * @return string + * @since 0.1.0 + */ + public function refreshIntervalSpec(): string + { + $value = $this->registry->get('refresh_interval'); + + if (!is_string($value) || $value === '') { + throw new \LogicException('Normalized refresh interval configuration is invalid.'); + } + + return $value; + } + + /** + * Returns a new interval instance for freshness calculations. + * + * @return \DateInterval + * @since 0.1.0 + */ + public function refreshInterval(): \DateInterval + { + return new \DateInterval($this->refreshIntervalSpec()); + } + + /** + * Indicates whether stale snapshots warm on their next query. + * + * @return bool + * @since 0.1.0 + */ + public function autoRefresh(): bool + { + $value = $this->registry->get('auto_refresh'); + + if (!is_bool($value)) { + throw new \LogicException('Normalized automatic refresh configuration is invalid.'); + } + + return $value; + } + + /** + * Returns the maximum number of seconds spent waiting for a lifecycle lock. + * + * @return int + * @since 0.2.0 + */ + public function lockTimeout(): int + { + $value = $this->registry->get('lock_timeout'); + + if (!is_int($value) || $value < 1) { + throw new \LogicException('Normalized lock timeout configuration is invalid.'); + } + + return $value; + } + + /** + * Returns explicitly configured translation module identifiers. + * + * @return list + * @since 0.3.0 + */ + public function modules(): array + { + $modules = $this->registry->get('modules', []); + + if (!is_array($modules)) { + throw new \LogicException('Normalized module configuration is not an array.'); + } + + $validated = []; + + foreach ($modules as $module) { + if (!is_string($module)) { + throw new \LogicException('Normalized module configuration contains a non-string value.'); + } + + $validated[] = $module; + } + + return $validated; + } + + /** + * Reports whether maintenance may invoke mutating native provisioning. + * + * @return bool + * @since 0.3.0 + */ + public function provisioningEnabled(): bool + { + $value = $this->registry->get('provisioning_enabled'); + + if (!is_bool($value)) { + throw new \LogicException('Normalized provisioning policy is invalid.'); + } + + return $value; + } + + /** + * Reports whether initialization should install every approved translation. + * + * @return bool + * @since 0.3.0 + */ + public function installAll(): bool + { + $value = $this->registry->get('install_all'); + + if (!is_bool($value)) { + throw new \LogicException('Normalized all-module installation policy is invalid.'); + } + + return $value; + } + + /** + * Returns the durable maintenance state path. + * + * @return string + * @since 0.3.0 + */ + public function maintenanceStatePath(): string + { + return $this->cachePath() . '/maintenance/state.json'; + } + + /** + * Returns a defensive copy of the underlying Joomla registry. + * + * @return Registry + * @since 0.1.0 + */ + public function registry(): Registry + { + return clone $this->registry; + } + + /** + * Returns the first non-empty scalar string. + * + * @param bool|int|string|array|null ...$values Candidate values. + * + * @return string|null + * @since 0.1.0 + */ + private static function firstString(bool|int|string|array|null ...$values): ?string + { + foreach ($values as $value) { + if (is_string($value) && trim($value) !== '') { + return trim($value); + } + } + + return null; + } + + /** + * Reads a non-empty environment variable. + * + * @param string $name Environment variable name. + * + * @return string|null + * @since 0.1.0 + */ + private static function environment(string $name): ?string + { + $value = getenv($name); + + return is_string($value) && trim($value) !== '' ? trim($value) : null; + } + + /** + * Parses a strict boolean configuration value. + * + * @param bool|int|string|array|null $value Candidate value. + * @param bool $default Default when no value is supplied. + * + * @return bool + * @since 0.1.0 + */ + private static function booleanValue(bool|int|string|array|null $value, bool $default): bool + { + if ($value === null) { + return $default; + } + + if (is_bool($value)) { + return $value; + } + + if (is_array($value)) { + throw new \InvalidArgumentException('A boolean configuration value cannot be an array.'); + } + + if (is_int($value)) { + return match ($value) { + 1 => true, + 0 => false, + default => throw new \InvalidArgumentException( + sprintf('Invalid boolean configuration value "%d".', $value), + ), + }; + } + + $normalized = strtolower(trim($value)); + + return match ($normalized) { + '1', 'true', 'yes', 'on' => true, + '0', 'false', 'no', 'off' => false, + default => throw new \InvalidArgumentException( + sprintf('Invalid boolean configuration value "%s".', $value), + ), + }; + } + + /** + * Parses a strictly positive integer configuration value. + * + * @param bool|int|string|array|null $value Candidate value. + * @param int $default Default when no value is supplied. + * @param string $label Human-readable setting label. + * + * @return int + * @since 0.2.0 + */ + private static function positiveInteger( + bool|int|string|array|null $value, + int $default, + string $label, + ): int { + if ($value === null) { + return $default; + } + + if ( + is_array($value) + || is_bool($value) + || (is_string($value) && preg_match('/^[1-9][0-9]*$/D', trim($value)) !== 1) + ) { + throw new \InvalidArgumentException(sprintf('Invalid %s value.', $label)); + } + + $integer = (int) $value; + + if ($integer < 1) { + throw new \InvalidArgumentException(sprintf('The %s must be greater than zero.', $label)); + } + + return $integer; + } + + /** + * Parses, validates, and de-duplicates configured module identifiers. + * + * @param bool|int|string|array|null $value Candidate module configuration. + * + * @return list + * @since 0.3.0 + */ + private static function moduleList(bool|int|string|array|null $value): array + { + if ($value === null || $value === '') { + return []; + } + + if (is_bool($value) || is_int($value)) { + throw new \InvalidArgumentException('Configured modules must be an array or comma-separated string.'); + } + + $modules = is_string($value) ? explode(',', $value) : $value; + $normalized = []; + + foreach ($modules as $module) { + if (!is_string($module)) { + throw new \InvalidArgumentException('Every configured module identifier must be a string.'); + } + + $module = trim($module); + + if ($module === '' || str_contains($module, "\0")) { + throw new \InvalidArgumentException( + 'Configured module identifiers must be non-empty and contain no NUL bytes.', + ); + } + + $normalized[$module] = $module; + } + + return array_values($normalized); + } + + /** + * Resolves a safe per-user default cache path. + * + * @return string + * @since 0.1.0 + */ + private static function defaultCachePath(): string + { + $xdg = self::environment('XDG_CACHE_HOME'); + + if ($xdg !== null) { + return $xdg . '/getbible/scripture'; + } + + $home = self::environment('HOME'); + + if ($home !== null) { + return $home . '/.cache/getbible/scripture'; + } + + $userId = function_exists('posix_geteuid') ? (string) posix_geteuid() : 'unknown'; + + return sys_get_temp_dir() . '/getbible-scripture-' . $userId; + } + + /** + * Removes trailing separators without changing a filesystem root. + * + * @param string $path Filesystem path. + * + * @return string + * @since 0.1.0 + */ + private static function normalizePath(string $path): string + { + $normalized = rtrim($path, '/\\'); + + return $normalized === '' ? DIRECTORY_SEPARATOR : $normalized; + } +} diff --git a/src/Console/ConsoleApplicationFactory.php b/src/Console/ConsoleApplicationFactory.php new file mode 100644 index 0000000..7e6d769 --- /dev/null +++ b/src/Console/ConsoleApplicationFactory.php @@ -0,0 +1,66 @@ +setName('GetBible Scripture'); + $application->setVersion(self::version()); + $application->setDispatcher(ContainerService::get($container, DispatcherInterface::class)); + $maintenance = ContainerService::get($container, MaintenanceServiceInterface::class); + + $application->addCommand(new InitializeCommand($maintenance)); + $application->addCommand(new RefreshCommand($maintenance)); + $application->addCommand(new StatusCommand($maintenance)); + + return $application; + } + + /** + * Reads the package version without introducing generated constants. + * + * @return string + * @since 0.3.0 + */ + private static function version(): string + { + $version = @file_get_contents(dirname(__DIR__, 2) . '/VERSION'); + + return is_string($version) && trim($version) !== '' ? trim($version) : 'unknown'; + } + + /** + * Prevents instantiation of this factory. + * + * @since 0.3.0 + */ + private function __construct() + { + } +} diff --git a/src/Console/InitializeCommand.php b/src/Console/InitializeCommand.php new file mode 100644 index 0000000..299bb72 --- /dev/null +++ b/src/Console/InitializeCommand.php @@ -0,0 +1,87 @@ +setDescription('Install missing Bible modules when permitted and warm validated snapshots.'); + $this->addOption( + 'module', + 'm', + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'Exact translation module to initialize; repeat the option for multiple modules.', + ); + $this->addOption( + 'all', + 'a', + InputOption::VALUE_NONE, + 'Explicitly request every policy-approved translation from the native provisioner.', + ); + } + + /** + * Executes initialization and emits deterministic JSON. + * + * @param InputInterface $input Bound command input. + * @param OutputInterface $output Console output. + * + * @return int + * @since 0.3.0 + */ + protected function doExecute(InputInterface $input, OutputInterface $output): int + { + $result = $this->maintenance->initialize( + ModuleOption::normalize($input->getOption('module')), + $input->getOption('all') === true, + ); + $output->writeln((string) json_encode( + $result->toArray(), + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + )); + + return $result->succeeded() ? 0 : 1; + } +} diff --git a/src/Console/ModuleOption.php b/src/Console/ModuleOption.php new file mode 100644 index 0000000..c71695f --- /dev/null +++ b/src/Console/ModuleOption.php @@ -0,0 +1,51 @@ + + * @since 0.3.0 + */ + public static function normalize(mixed $value): array + { + if (!is_array($value)) { + throw new \UnexpectedValueException('The module option must resolve to a list.'); + } + + $modules = []; + + foreach ($value as $module) { + if (!is_string($module)) { + throw new \UnexpectedValueException('Every module option must be a string.'); + } + + $modules[] = $module; + } + + return $modules; + } + + /** + * Prevents instantiation of this utility. + * + * @since 0.3.0 + */ + private function __construct() + { + } +} diff --git a/src/Console/RefreshCommand.php b/src/Console/RefreshCommand.php new file mode 100644 index 0000000..2c4e917 --- /dev/null +++ b/src/Console/RefreshCommand.php @@ -0,0 +1,88 @@ +setDescription('Refresh native modules when enabled and rebuild validated snapshots.'); + $this->addOption( + 'module', + 'm', + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'Exact translation module to refresh; repeat the option for multiple modules.', + ); + $this->addOption( + 'if-due', + null, + InputOption::VALUE_NONE, + 'Skip successfully when the configured durable refresh interval has not elapsed.', + ); + } + + /** + * Executes refresh and emits deterministic JSON. + * + * @param InputInterface $input Bound command input. + * @param OutputInterface $output Console output. + * + * @return int + * @since 0.3.0 + */ + protected function doExecute(InputInterface $input, OutputInterface $output): int + { + $modules = ModuleOption::normalize($input->getOption('module')); + + $result = $input->getOption('if-due') === true + ? $this->maintenance->refreshIfDue($modules) + : $this->maintenance->refresh($modules); + $output->writeln((string) json_encode( + $result->toArray(), + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + )); + + return $result->succeeded() ? 0 : 1; + } +} diff --git a/src/Console/StatusCommand.php b/src/Console/StatusCommand.php new file mode 100644 index 0000000..6e7fc34 --- /dev/null +++ b/src/Console/StatusCommand.php @@ -0,0 +1,70 @@ +setDescription('Report Scripture maintenance state and native provisioning capabilities.'); + } + + /** + * Emits deterministic JSON status. + * + * @param InputInterface $input Bound command input. + * @param OutputInterface $output Console output. + * + * @return int + * @since 0.3.0 + */ + protected function doExecute(InputInterface $input, OutputInterface $output): int + { + $output->writeln((string) json_encode( + $this->maintenance->status()->toArray(), + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + )); + + return 0; + } +} diff --git a/src/Contract/AnnotationSegment.php b/src/Contract/AnnotationSegment.php new file mode 100644 index 0000000..d962a79 --- /dev/null +++ b/src/Contract/AnnotationSegment.php @@ -0,0 +1,106 @@ + $segment Candidate segment. + * @param int $index Segment index for diagnostics. + * + * @return self + * @since 0.1.0 + */ + public static function fromArray(array $segment, int $index): self + { + $segment = StructuredData::object( + $segment, + sprintf('Annotation segment %d', $index), + ); + $kind = $segment['kind'] ?? null; + $interpretation = $segment['interpretation'] ?? null; + $raw = $segment['raw'] ?? null; + + if (!is_string($kind) || !in_array($kind, ['text', 'markup', 'entity'], true)) { + throw new ContractException(sprintf('Annotation segment %d has an invalid kind.', $index)); + } + + $expected = $kind === 'text' ? 'not_applicable' : 'uninterpreted'; + + if ($interpretation !== $expected) { + throw new ContractException(sprintf( + 'Annotation segment %d has invalid interpretation "%s".', + $index, + is_scalar($interpretation) ? (string) $interpretation : get_debug_type($interpretation), + )); + } + + if (!is_array($raw)) { + throw new ContractException(sprintf('Annotation segment %d has no byte value.', $index)); + } + + return new self($kind, $expected, ByteValue::fromArray($raw, "annotation_segments[$index].raw")); + } + + /** + * Returns `text`, `markup`, or `entity`. + * + * @return string + * @since 0.1.0 + */ + public function kind(): string + { + return $this->kind; + } + + /** + * Returns the producer's interpretation classification. + * + * @return string + * @since 0.1.0 + */ + public function interpretation(): string + { + return $this->interpretation; + } + + /** + * Returns the exact segment bytes. + * + * @return ByteValue + * @since 0.1.0 + */ + public function raw(): ByteValue + { + return $this->raw; + } +} diff --git a/src/Contract/ByteValue.php b/src/Contract/ByteValue.php new file mode 100644 index 0000000..79f4cf1 --- /dev/null +++ b/src/Contract/ByteValue.php @@ -0,0 +1,207 @@ +bytes = $bytes; + $this->sha256 = $sha256; + $this->utf8 = $utf8; + $this->envelope = $envelope; + } + + /** + * Validates and creates a byte value from a decoded JSON object. + * + * @param array $value Candidate envelope. + * @param string $context Human-readable field context. + * + * @return self + * @since 0.1.0 + */ + public static function fromArray(array $value, string $context = 'byte value'): self + { + $value = StructuredData::object($value, $context); + $allowed = ['base64', 'encoding', 'sha256', 'size', 'utf8']; + $unknown = array_diff(array_keys($value), $allowed); + + if ($unknown !== []) { + throw new ContractException(sprintf( + '%s contains unsupported member(s): %s.', + $context, + implode(', ', $unknown), + )); + } + + $base64 = $value['base64'] ?? null; + $encoding = $value['encoding'] ?? null; + $sha256 = $value['sha256'] ?? null; + $size = $value['size'] ?? null; + $utf8 = $value['utf8'] ?? null; + + if (!is_string($base64) || $encoding !== 'base64') { + throw new ContractException(sprintf('%s has an invalid Base64 encoding envelope.', $context)); + } + + if (!is_string($sha256) || preg_match('/^[0-9a-f]{64}$/D', $sha256) !== 1) { + throw new ContractException(sprintf('%s has an invalid SHA-256 digest.', $context)); + } + + if (!is_int($size) || $size < 0) { + throw new ContractException(sprintf('%s has an invalid decoded size.', $context)); + } + + if ($utf8 !== null && !is_string($utf8)) { + throw new ContractException(sprintf('%s has a non-string UTF-8 projection.', $context)); + } + + $bytes = base64_decode($base64, true); + + if ($bytes === false || base64_encode($bytes) !== $base64) { + throw new ContractException(sprintf('%s is not canonical Base64.', $context)); + } + + if (strlen($bytes) !== $size) { + throw new ContractException(sprintf('%s decoded size does not match its envelope.', $context)); + } + + $actualHash = hash('sha256', $bytes); + + if (!hash_equals($sha256, $actualHash)) { + throw new ContractException(sprintf('%s decoded digest does not match its envelope.', $context)); + } + + if ($utf8 !== null && $utf8 !== $bytes) { + throw new ContractException(sprintf('%s UTF-8 projection is not byte-identical.', $context)); + } + + /** @var array{base64: string, encoding: string, sha256: string, size: int, utf8?: string} $value */ + return new self($bytes, $sha256, $utf8, $value); + } + + /** + * Returns the authoritative decoded bytes. + * + * @return string + * @since 0.1.0 + */ + public function bytes(): string + { + return $this->bytes; + } + + /** + * Returns the optional exact UTF-8 projection. + * + * @return string|null + * @since 0.1.0 + */ + public function utf8(): ?string + { + return $this->utf8; + } + + /** + * Returns the exact UTF-8 projection or throws when it is unavailable. + * + * @return string + * @since 0.1.0 + */ + public function requireUtf8(): string + { + if ($this->utf8 === null) { + throw new \UnexpectedValueException('This byte value has no exact UTF-8 projection.'); + } + + return $this->utf8; + } + + /** + * Returns the decoded byte length. + * + * @return int + * @since 0.1.0 + */ + public function size(): int + { + return strlen($this->bytes); + } + + /** + * Returns the verified SHA-256 digest. + * + * @return string + * @since 0.1.0 + */ + public function sha256(): string + { + return $this->sha256; + } + + /** + * Returns the original verified envelope. + * + * @return array{base64: string, encoding: string, sha256: string, size: int, utf8?: string} + * @since 0.1.0 + */ + public function toArray(): array + { + return $this->envelope; + } +} diff --git a/src/Contract/ContractV1Validator.php b/src/Contract/ContractV1Validator.php new file mode 100644 index 0000000..79239a3 --- /dev/null +++ b/src/Contract/ContractV1Validator.php @@ -0,0 +1,849 @@ + + * @since 0.1.0 + */ + private const PHASES = [ + 'header' => 0, + 'module' => 1, + 'config_source' => 2, + 'config_entry' => 3, + 'entry' => 4, + 'artifact_begin' => 5, + 'artifact_chunk' => 5, + 'artifact_end' => 5, + 'footer' => 6, + ]; + + /** + * Validates one complete operation stream. + * + * @param resource $stream Readable stream. + * @param RecordObserverInterface|null $observer Optional validated-record observer. + * + * @return ValidationResult + * @since 0.1.0 + */ + public function validate(mixed $stream, ?RecordObserverInterface $observer = null): ValidationResult + { + if (!is_resource($stream) || get_resource_type($stream) !== 'stream') { + throw new \InvalidArgumentException('Contract validation requires a PHP stream resource.'); + } + + $metadata = stream_get_meta_data($stream); + + if ($metadata['mode'] === '' || !strpbrk($metadata['mode'], 'r+')) { + throw new \InvalidArgumentException('Contract validation requires a readable stream.'); + } + + $streamHash = hash_init('sha256'); + $expectedSequence = 0; + $phase = -1; + $command = null; + $footer = null; + $modules = []; + $recordCounts = []; + /** @var array{error: int, info: int, warning: int} $diagnostics */ + $diagnostics = ['error' => 0, 'info' => 0, 'warning' => 0]; + $entryOrdinal = 0; + $configSourceOrdinal = 0; + $configEntryOrdinal = 0; + $artifactId = 0; + $artifactBytes = 0; + $activeArtifact = null; + $artifactChunkSize = null; + $artifactPaths = []; + + while (!feof($stream)) { + $offset = ftell($stream); + + if (!is_int($offset)) { + throw new ContractException('Unable to determine the NDJSON stream position.'); + } + + $line = fgets($stream, self::MAX_LINE_BYTES + 1); + + if ($line === false) { + if (feof($stream)) { + break; + } + + throw new ContractException('Unable to read the NDJSON stream.'); + } + + $length = strlen($line); + + if ($length === 0 || $line[$length - 1] !== "\n") { + throw new ContractException(sprintf( + 'NDJSON record at byte %d is truncated or exceeds %d bytes.', + $offset, + self::MAX_LINE_BYTES, + )); + } + + try { + $record = json_decode($line, true, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ContractException( + sprintf('Invalid JSON record at byte %d: %s', $offset, $exception->getMessage()), + 0, + $exception, + ); + } + + $record = StructuredData::object( + $record, + sprintf('Record at byte %d', $offset), + ); + + $type = $record['type'] ?? null; + $sequence = $record['sequence'] ?? null; + + if (!is_string($type) || !is_int($sequence) || $sequence !== $expectedSequence) { + throw new ContractException(sprintf( + 'Record at byte %d has invalid sequence or type; expected sequence %d.', + $offset, + $expectedSequence, + )); + } + + if (!isset(self::PHASES[$type]) && $type !== 'diagnostic') { + throw new ContractException(sprintf('Unsupported v1 record type "%s".', $type)); + } + + if ($footer !== null) { + throw new ContractException('A record appears after the footer.'); + } + + if ($type !== 'diagnostic') { + $nextPhase = self::PHASES[$type]; + + if ($nextPhase < $phase) { + throw new ContractException(sprintf('Record type "%s" appears out of phase.', $type)); + } + + $phase = $nextPhase; + } + + if ($expectedSequence === 0 && $type !== 'header') { + throw new ContractException('The first record must be a header.'); + } + + switch ($type) { + case 'header': + if ($expectedSequence !== 0) { + throw new ContractException('The stream contains more than one header.'); + } + + $command = $this->validateHeader($record); + $artifactChunkSize = $command === 'extract' ? $record['artifact_chunk_size'] : null; + break; + + case 'module': + if ($command === 'extract' && $modules !== []) { + throw new ContractException('An extract stream contains more than one module record.'); + } + + $modules[] = TranslationMetadata::fromRecord($record); + break; + + case 'config_source': + $this->requireExtractRecord($command, count($modules), $type); + $this->validateConfigSource($record, $configSourceOrdinal); + ++$configSourceOrdinal; + break; + + case 'config_entry': + $this->requireExtractRecord($command, count($modules), $type); + $entry = ConfigEntry::fromRecord($record); + + if ($entry->ordinal() !== $configEntryOrdinal) { + throw new ContractException('Configuration entry ordinals are not consecutive.'); + } + + ++$configEntryOrdinal; + break; + + case 'entry': + $this->requireExtractRecord($command, count($modules), $type); + $this->validateEntry($record, $entryOrdinal); + ++$entryOrdinal; + break; + + case 'artifact_begin': + $this->requireExtractRecord($command, count($modules), $type); + + if ($activeArtifact !== null) { + throw new ContractException('An artifact begins before the active artifact ends.'); + } + + if (!is_int($artifactChunkSize)) { + throw new ContractException('An artifact appears without an extract chunk size.'); + } + + $activeArtifact = $this->validateArtifactBegin( + $record, + $artifactId, + $artifactChunkSize, + ); + + if (isset($artifactPaths[$activeArtifact['path']])) { + throw new ContractException('Artifact paths must be unique.'); + } + + $artifactPaths[$activeArtifact['path']] = true; + break; + + case 'artifact_chunk': + if ($activeArtifact === null) { + throw new ContractException('An artifact chunk appears without an active artifact.'); + } + + $bytes = $this->validateArtifactChunk($record, $activeArtifact); + hash_update($activeArtifact['hash'], $bytes); + $activeArtifact['size'] += strlen($bytes); + $activeArtifact['chunk']++; + + if (strlen($bytes) < $activeArtifact['chunk_size']) { + $activeArtifact['short_chunk_seen'] = true; + } + break; + + case 'artifact_end': + if ($activeArtifact === null) { + throw new ContractException('An artifact ends without an active artifact.'); + } + + $this->validateArtifactEnd($record, $activeArtifact); + $artifactBytes += $activeArtifact['size']; + $activeArtifact = null; + ++$artifactId; + break; + + case 'diagnostic': + if ($activeArtifact !== null) { + throw new ContractException('A diagnostic splits an active artifact group.'); + } + + $severity = $this->validateDiagnostic($record); + ++$diagnostics[$severity]; + break; + + case 'footer': + if ($activeArtifact !== null) { + throw new ContractException('The footer interrupts an active artifact.'); + } + + $this->validateFooterShape($record); + $footer = $record; + break; + } + + if ($type !== 'footer') { + $this->validateEmbeddedByteValues($record, $type); + hash_update($streamHash, $line); + $recordCounts[$type] = ($recordCounts[$type] ?? 0) + 1; + } + + $observer?->onRecord($record, $offset, $length); + ++$expectedSequence; + } + + if ($command === null || $footer === null) { + throw new ContractException('The NDJSON stream is missing its header or footer.'); + } + + if ($command === 'extract' && $footer['success'] === true && count($modules) !== 1) { + throw new ContractException('A successful extract stream requires exactly one module record.'); + } + + $this->validateFooterTotals( + $footer, + $recordCounts, + $diagnostics, + $entryOrdinal, + $artifactId, + $artifactBytes, + hash_final($streamHash), + ); + + if ($footer['success'] !== true) { + throw new ContractException(sprintf( + 'The native operation completed with success=false and %d error diagnostic(s).', + $diagnostics['error'], + )); + } + + return new ValidationResult($command, $modules, $footer); + } + + /** + * Validates the header and returns its command. + * + * @param array $record Header record. + * + * @return 'extract'|'list' + * @since 0.1.0 + */ + private function validateHeader(array $record): string + { + $command = $record['command'] ?? null; + + if (!is_string($command) || !in_array($command, ['list', 'extract'], true)) { + throw new ContractException('Header command must be "list" or "extract".'); + } + + if ( + ($record['contract'] ?? null) !== self::CONTRACT + || ($record['contract_version'] ?? null) !== 1 + || ($record['deterministic'] ?? null) !== true + || ($record['producer'] ?? null) !== 'getBibleSword' + || !is_string($record['producer_version'] ?? null) + || !is_string($record['sword_version'] ?? null) + ) { + throw new ContractException('Header compatibility or producer metadata is invalid.'); + } + + if ($command === 'extract') { + $chunkSize = $record['artifact_chunk_size'] ?? null; + + if (!is_int($chunkSize) || $chunkSize < 4096 || $chunkSize > 16777216) { + throw new ContractException('Extract header artifact chunk size is invalid.'); + } + } + + return $command; + } + + /** + * Requires an extract-only record to follow exactly one module record. + * + * @param string|null $command Active stream command. + * @param int $moduleCount Observed module records. + * @param string $recordType Candidate record type. + * + * @return void + * @since 0.1.0 + */ + private function requireExtractRecord(?string $command, int $moduleCount, string $recordType): void + { + if ($command !== 'extract') { + throw new ContractException(sprintf('%s is not permitted in a list stream.', $recordType)); + } + + if ($moduleCount !== 1) { + throw new ContractException(sprintf('%s requires one preceding module record.', $recordType)); + } + } + + /** + * Validates a raw configuration source record. + * + * @param array $record Configuration source. + * @param int $expectedOrdinal Expected source order. + * + * @return void + * @since 0.1.0 + */ + private function validateConfigSource(array $record, int $expectedOrdinal): void + { + if ( + ($record['ordinal'] ?? null) !== $expectedOrdinal + || !is_array($record['path'] ?? null) + || !is_array($record['raw'] ?? null) + ) { + throw new ContractException('Configuration source record is invalid or out of order.'); + } + + $path = ByteValue::fromArray($record['path'], 'config_source.path')->bytes(); + $this->validateRelativePath($path, false, 'config_source.path'); + ByteValue::fromArray($record['raw'], 'config_source.raw'); + } + + /** + * Validates one logical entry record. + * + * @param array $record Entry record. + * @param int $expectedOrdinal Expected traversal ordinal. + * + * @return void + * @since 0.1.0 + */ + private function validateEntry(array $record, int $expectedOrdinal): void + { + if ( + ($record['ordinal'] ?? null) !== $expectedOrdinal + || !is_array($record['key'] ?? null) + || !is_array($record['raw'] ?? null) + || !is_array($record['scope'] ?? null) + || !is_array($record['annotation_segments'] ?? null) + || !is_array($record['official_attributes'] ?? null) + || !is_bool($record['projections_available'] ?? null) + ) { + throw new ContractException('Entry record is invalid or out of order.'); + } + + ByteValue::fromArray($record['key'], 'entry.key'); + $raw = ByteValue::fromArray($record['raw'], 'entry.raw'); + $scope = $record['scope']; + + if (($scope['type'] ?? null) === 'verse_key') { + VerseScope::fromArray($scope); + } elseif (($scope['type'] ?? null) === 'sword_key') { + if (!is_int($scope['index'] ?? null) || $scope['index'] < 0) { + throw new ContractException('Generic SWORD scope index is invalid.'); + } + } else { + throw new ContractException('Entry scope type is invalid.'); + } + + $reconstructed = ''; + + foreach ($record['annotation_segments'] as $index => $segment) { + if (!is_array($segment)) { + throw new ContractException(sprintf('Annotation segment %d is invalid.', $index)); + } + + $reconstructed .= AnnotationSegment::fromArray($segment, $index)->raw()->bytes(); + } + + if ($reconstructed !== $raw->bytes()) { + throw new ContractException('Annotation segments do not reconstruct entry.raw.'); + } + + OfficialAttributes::fromArray($record['official_attributes']); + $available = $record['projections_available']; + + foreach (['rendered_default', 'stripped'] as $field) { + $value = $record[$field] ?? null; + + if ($available && !is_array($value)) { + throw new ContractException(sprintf('entry.%s must be a byte value.', $field)); + } + + if (!$available && $value !== null) { + throw new ContractException(sprintf('entry.%s must be null.', $field)); + } + + if (is_array($value)) { + ByteValue::fromArray($value, 'entry.' . $field); + } + } + } + + /** + * Validates an artifact begin record and creates active state. + * + * @param array $record Artifact begin. + * @param int $expectedId Expected artifact identifier. + * @param int $chunkSize Header-declared maximum artifact chunk size. + * + * @return array{ + * id: int, + * type: string, + * hash: \HashContext, + * path: string, + * size: int, + * expected_size: int|null, + * chunk_size: int, + * short_chunk_seen: bool, + * chunk: int + * } + * @since 0.1.0 + */ + private function validateArtifactBegin(array $record, int $expectedId, int $chunkSize): array + { + $type = $record['file_type'] ?? null; + $mode = $record['mode'] ?? null; + $role = $record['role'] ?? null; + + if ( + ($record['artifact_id'] ?? null) !== $expectedId + || !is_string($type) + || !in_array($type, ['regular', 'directory', 'symlink'], true) + || !is_int($mode) + || $mode < 0 + || $mode > 4095 + || !is_string($role) + || !is_array($record['path'] ?? null) + ) { + throw new ContractException('Artifact begin record is invalid or out of order.'); + } + + $path = ByteValue::fromArray($record['path'], 'artifact_begin.path')->bytes(); + $pathKey = $this->validateRelativePath( + $path, + $type === 'directory', + 'artifact_begin.path', + ); + $hash = hash_init('sha256'); + $size = 0; + $expectedSize = null; + + if ($type === 'regular') { + if (!is_int($record['size_expected'] ?? null) || $record['size_expected'] < 0) { + throw new ContractException('Regular artifact expected size is invalid.'); + } + + $expectedSize = $record['size_expected']; + } elseif ($type === 'symlink') { + if (!is_array($record['target'] ?? null)) { + throw new ContractException('Symlink artifact target is invalid.'); + } + + $target = ByteValue::fromArray($record['target'], 'artifact_begin.target')->bytes(); + + if (str_contains($target, "\0")) { + throw new ContractException('Symlink artifact target contains a NUL byte.'); + } + + hash_update($hash, $target); + $size = strlen($target); + } + + return [ + 'id' => $expectedId, + 'type' => $type, + 'hash' => $hash, + 'path' => $pathKey, + 'size' => $size, + 'expected_size' => $expectedSize, + 'chunk_size' => $chunkSize, + 'short_chunk_seen' => false, + 'chunk' => 0, + ]; + } + + /** + * Validates an artifact data chunk. + * + * @param array $record Artifact chunk. + * @param array{ + * id: int, + * type: string, + * hash: \HashContext, + * path: string, + * size: int, + * expected_size: int|null, + * chunk_size: int, + * short_chunk_seen: bool, + * chunk: int + * } $state Active artifact. + * + * @return string Decoded chunk bytes. + * @since 0.1.0 + */ + private function validateArtifactChunk(array $record, array $state): string + { + if ( + $state['type'] !== 'regular' + || ($record['artifact_id'] ?? null) !== $state['id'] + || ($record['index'] ?? null) !== $state['chunk'] + || !is_array($record['data'] ?? null) + || $state['short_chunk_seen'] + ) { + throw new ContractException('Artifact chunk is invalid or out of order.'); + } + + $bytes = ByteValue::fromArray($record['data'], 'artifact_chunk.data')->bytes(); + + if ($bytes === '') { + throw new ContractException('Artifact chunks must not be empty.'); + } + + if (strlen($bytes) > $state['chunk_size']) { + throw new ContractException('Artifact chunk exceeds the extract chunk size.'); + } + + return $bytes; + } + + /** + * Validates an artifact end record against accumulated state. + * + * @param array $record Artifact end. + * @param array{ + * id: int, + * type: string, + * hash: \HashContext, + * path: string, + * size: int, + * expected_size: int|null, + * chunk_size: int, + * short_chunk_seen: bool, + * chunk: int + * } $state Active artifact. + * + * @return void + * @since 0.1.0 + */ + private function validateArtifactEnd(array $record, array $state): void + { + $size = $record['size'] ?? null; + $sha256 = $record['sha256'] ?? null; + + if ( + ($record['artifact_id'] ?? null) !== $state['id'] + || !is_int($size) + || $size < 0 + || !is_string($sha256) + || preg_match('/^[0-9a-f]{64}$/D', $sha256) !== 1 + ) { + throw new ContractException('Artifact end record is invalid.'); + } + + $stable = null; + + if ($state['type'] === 'regular') { + $stable = $record['stable'] ?? null; + + if (!is_bool($stable)) { + throw new ContractException('Regular artifact stability flag is invalid.'); + } + } + + $actualHash = hash_final($state['hash']); + + if ($size !== $state['size']) { + throw new ContractException('Artifact end size does not match accumulated data.'); + } + + if ($stable === true && $size !== $state['expected_size']) { + throw new ContractException('Stable artifact size does not match its expected size.'); + } + + if (!hash_equals($sha256, $actualHash)) { + throw new ContractException('Artifact end digest does not match accumulated data.'); + } + } + + /** + * Validates a diagnostic and returns its severity. + * + * @param array $record Diagnostic record. + * + * @return 'error'|'info'|'warning' + * @since 0.1.0 + */ + private function validateDiagnostic(array $record): string + { + $severity = $record['severity'] ?? null; + + if ( + !is_string($record['code'] ?? null) + || !is_string($severity) + || !in_array($severity, ['error', 'info', 'warning'], true) + || !is_array($record['message'] ?? null) + ) { + throw new ContractException('Diagnostic record is invalid.'); + } + + ByteValue::fromArray($record['message'], 'diagnostic.message'); + + return $severity; + } + + /** + * Validates the footer's standalone member shapes. + * + * @param array $footer Footer record. + * + * @return void + * @since 0.1.0 + */ + private function validateFooterShape(array $footer): void + { + if ( + !is_array($footer['counts'] ?? null) + || !is_array($footer['diagnostics'] ?? null) + || !is_int($footer['entries'] ?? null) + || $footer['entries'] < 0 + || !is_int($footer['artifacts'] ?? null) + || $footer['artifacts'] < 0 + || !is_int($footer['artifact_bytes'] ?? null) + || $footer['artifact_bytes'] < 0 + || !is_bool($footer['success'] ?? null) + || !is_string($footer['stream_sha256'] ?? null) + || preg_match('/^[0-9a-f]{64}$/D', $footer['stream_sha256']) !== 1 + ) { + throw new ContractException('Footer record shape is invalid.'); + } + } + + /** + * Verifies footer totals and digest against observed stream state. + * + * @param array $footer Footer record. + * @param array $recordCounts Observed non-footer counts. + * @param array{error: int, info: int, warning: int} $diagnostics Observed diagnostics. + * @param int $entries Observed logical entries. + * @param int $artifacts Observed completed artifacts. + * @param int $artifactBytes Observed regular and symlink artifact bytes. + * @param string $streamSha256 Observed pre-footer digest. + * + * @return void + * @since 0.1.0 + */ + private function validateFooterTotals( + array $footer, + array $recordCounts, + array $diagnostics, + int $entries, + int $artifacts, + int $artifactBytes, + string $streamSha256, + ): void { + $footerCounts = []; + $serializedCounts = StructuredData::object($footer['counts'] ?? null, 'Footer counts'); + + foreach ($serializedCounts as $type => $count) { + if (!is_int($count) || $count < 0) { + throw new ContractException('Footer record counts are invalid.'); + } + + $footerCounts[$type] = $count; + } + + foreach (array_keys($footerCounts) as $type) { + if (!array_key_exists($type, self::PHASES) || $type === 'footer') { + throw new ContractException('Footer counts contain an unsupported record type.'); + } + } + + ksort($footerCounts); + ksort($recordCounts); + + $footerDiagnostics = []; + $serializedDiagnostics = StructuredData::object( + $footer['diagnostics'] ?? null, + 'Footer diagnostics', + ); + + foreach (['error', 'info', 'warning'] as $severity) { + $count = $serializedDiagnostics[$severity] ?? null; + + if (!is_int($count) || $count < 0) { + throw new ContractException('Footer diagnostic counts are invalid.'); + } + + $footerDiagnostics[$severity] = $count; + } + + if (count($serializedDiagnostics) !== count($footerDiagnostics)) { + throw new ContractException('Footer diagnostics contain unsupported severities.'); + } + + $footerStreamSha256 = $footer['stream_sha256'] ?? null; + + if (!is_string($footerStreamSha256)) { + throw new ContractException('Footer stream digest is invalid.'); + } + + if ( + $footerCounts !== $recordCounts + || $footerDiagnostics !== $diagnostics + || $footer['entries'] !== $entries + || $footer['artifacts'] !== $artifacts + || $footer['artifact_bytes'] !== $artifactBytes + || !hash_equals($footerStreamSha256, $streamSha256) + ) { + throw new ContractException('Footer totals or stream digest do not match observed records.'); + } + + if (($diagnostics['error'] > 0) !== ($footer['success'] === false)) { + throw new ContractException('Footer success does not agree with error diagnostics.'); + } + } + + /** + * Validates byte envelopes in additive fields that the consumer does not interpret. + * + * @param mixed $value Candidate nested value. + * @param string $context Human-readable member path. + * + * @return void + * @since 0.1.0 + */ + private function validateEmbeddedByteValues(mixed $value, string $context): void + { + if (!is_array($value)) { + return; + } + + if (array_key_exists('base64', $value) || ($value['encoding'] ?? null) === 'base64') { + ByteValue::fromArray($value, $context); + + return; + } + + foreach ($value as $key => $child) { + $this->validateEmbeddedByteValues( + $child, + is_int($key) ? sprintf('%s[%d]', $context, $key) : $context . '.' . $key, + ); + } + } + + /** + * Validates and normalizes a safe root-relative byte path. + * + * @param string $path Exact path bytes. + * @param bool $allowTrailingSeparator Whether a directory may end in slash. + * @param string $context Human-readable member path. + * + * @return string Normalized path bytes suitable as an identity key. + * @since 0.1.0 + */ + private function validateRelativePath(string $path, bool $allowTrailingSeparator, string $context): string + { + if ($path === '' || str_contains($path, "\0") || str_starts_with($path, '/')) { + throw new ContractException(sprintf('%s is not a safe root-relative path.', $context)); + } + + $normalized = $allowTrailingSeparator && str_ends_with($path, '/') + ? substr($path, 0, -1) + : $path; + + foreach (explode('/', $normalized) as $component) { + if ($component === '' || $component === '.' || $component === '..') { + throw new ContractException(sprintf('%s is not a normalized relative path.', $context)); + } + } + + return $normalized; + } +} diff --git a/src/Contract/ContractV1ValidatorInterface.php b/src/Contract/ContractV1ValidatorInterface.php new file mode 100644 index 0000000..3fc8942 --- /dev/null +++ b/src/Contract/ContractV1ValidatorInterface.php @@ -0,0 +1,26 @@ +code = $code; + $this->name = $name; + } + + /** + * Validates and creates an enum from a contract object. + * + * @param array $value Candidate enum. + * @param string $context Human-readable context. + * + * @return self + * @since 0.1.0 + */ + public static function fromArray(array $value, string $context): self + { + $value = StructuredData::object($value, $context); + $code = $value['code'] ?? null; + $name = $value['name'] ?? null; + + if (!is_int($code) || $code < 0 || $code > 255 || !is_string($name)) { + throw new ContractException(sprintf('%s is not a valid SWORD enumeration.', $context)); + } + + return new self($code, $name); + } + + /** + * Returns the native unsigned byte code. + * + * @return int + * @since 0.1.0 + */ + public function code(): int + { + return $this->code; + } + + /** + * Returns the stable producer name. + * + * @return string + * @since 0.1.0 + */ + public function name(): string + { + return $this->name; + } +} diff --git a/src/Contract/OfficialAttributeList.php b/src/Contract/OfficialAttributeList.php new file mode 100644 index 0000000..b862b82 --- /dev/null +++ b/src/Contract/OfficialAttributeList.php @@ -0,0 +1,51 @@ + $values Ordered values. + * + * @since 0.1.0 + */ + public function __construct( + private ByteValue $name, + private array $values, + ) { + } + + /** + * Returns the exact list name. + * + * @return ByteValue + * @since 0.1.0 + */ + public function name(): ByteValue + { + return $this->name; + } + + /** + * Returns ordered list values. + * + * @return list + * @since 0.1.0 + */ + public function values(): array + { + return $this->values; + } +} diff --git a/src/Contract/OfficialAttributeType.php b/src/Contract/OfficialAttributeType.php new file mode 100644 index 0000000..ebfd716 --- /dev/null +++ b/src/Contract/OfficialAttributeType.php @@ -0,0 +1,51 @@ + $lists Ordered lists. + * + * @since 0.1.0 + */ + public function __construct( + private ByteValue $name, + private array $lists, + ) { + } + + /** + * Returns the exact type name. + * + * @return ByteValue + * @since 0.1.0 + */ + public function name(): ByteValue + { + return $this->name; + } + + /** + * Returns ordered attribute lists. + * + * @return list + * @since 0.1.0 + */ + public function lists(): array + { + return $this->lists; + } +} diff --git a/src/Contract/OfficialAttributeValue.php b/src/Contract/OfficialAttributeValue.php new file mode 100644 index 0000000..fa4c5ee --- /dev/null +++ b/src/Contract/OfficialAttributeValue.php @@ -0,0 +1,51 @@ +name; + } + + /** + * Returns the exact attribute value content. + * + * @return ByteValue + * @since 0.1.0 + */ + public function value(): ByteValue + { + return $this->value; + } +} diff --git a/src/Contract/OfficialAttributes.php b/src/Contract/OfficialAttributes.php new file mode 100644 index 0000000..67c8c49 --- /dev/null +++ b/src/Contract/OfficialAttributes.php @@ -0,0 +1,143 @@ + $types Ordered types. + * + * @since 0.1.0 + */ + private function __construct(private array $types) + { + } + + /** + * Validates and creates the complete ordered attribute map. + * + * @param array $attributes Candidate types. + * + * @return self + * @since 0.1.0 + */ + public static function fromArray(array $attributes): self + { + if (!array_is_list($attributes)) { + throw new ContractException('Official attributes must be an ordered list.'); + } + + $types = []; + + foreach ($attributes as $typeIndex => $type) { + $type = StructuredData::object( + $type, + sprintf('Official attribute type %d', $typeIndex), + ); + + if (!is_array($type['name'] ?? null)) { + throw new ContractException(sprintf('Official attribute type %d is invalid.', $typeIndex)); + } + + $lists = []; + + foreach ( + StructuredData::list( + $type['lists'] ?? null, + sprintf('Official attribute type %d lists', $typeIndex), + ) as $listIndex => $list + ) { + $list = StructuredData::object( + $list, + sprintf('Official attribute type %d list %d', $typeIndex, $listIndex), + ); + + if (!is_array($list['name'] ?? null)) { + throw new ContractException(sprintf( + 'Official attribute type %d list %d is invalid.', + $typeIndex, + $listIndex, + )); + } + + $values = []; + + foreach ( + StructuredData::list( + $list['values'] ?? null, + sprintf('Official attribute type %d list %d values', $typeIndex, $listIndex), + ) as $valueIndex => $value + ) { + $value = StructuredData::object( + $value, + sprintf( + 'Official attribute type %d list %d value %d', + $typeIndex, + $listIndex, + $valueIndex, + ), + ); + + if (!is_array($value['name'] ?? null) || !is_array($value['value'] ?? null)) { + throw new ContractException(sprintf( + 'Official attribute type %d list %d value %d is invalid.', + $typeIndex, + $listIndex, + $valueIndex, + )); + } + + $values[] = new OfficialAttributeValue( + ByteValue::fromArray( + $value['name'], + "official_attributes[$typeIndex].lists[$listIndex].values[$valueIndex].name", + ), + ByteValue::fromArray( + $value['value'], + "official_attributes[$typeIndex].lists[$listIndex].values[$valueIndex].value", + ), + ); + } + + $lists[] = new OfficialAttributeList( + ByteValue::fromArray( + $list['name'], + "official_attributes[$typeIndex].lists[$listIndex].name", + ), + $values, + ); + } + + $types[] = new OfficialAttributeType( + ByteValue::fromArray($type['name'], "official_attributes[$typeIndex].name"), + $lists, + ); + } + + return new self($types); + } + + /** + * Returns the complete ordered attribute types. + * + * @return list + * @since 0.1.0 + */ + public function types(): array + { + return $this->types; + } +} diff --git a/src/Contract/RecordObserverInterface.php b/src/Contract/RecordObserverInterface.php new file mode 100644 index 0000000..659e6bd --- /dev/null +++ b/src/Contract/RecordObserverInterface.php @@ -0,0 +1,27 @@ + $record Decoded record. + * @param int $offset Byte offset of the serialized line. + * @param int $length Serialized line length including LF. + * + * @return void + * @since 0.1.0 + */ + public function onRecord(array $record, int $offset, int $length): void; +} diff --git a/src/Contract/StructuredData.php b/src/Contract/StructuredData.php new file mode 100644 index 0000000..b1f22ce --- /dev/null +++ b/src/Contract/StructuredData.php @@ -0,0 +1,91 @@ + + * @since 0.3.0 + */ + public static function object(mixed $value, string $context): array + { + if (!is_array($value) || array_is_list($value)) { + throw new ContractException(sprintf('%s must be a JSON object.', $context)); + } + + foreach (array_keys($value) as $key) { + if (!is_string($key)) { + throw new ContractException(sprintf('%s contains a non-string object key.', $context)); + } + } + + /** @var array $value */ + return $value; + } + + /** + * Requires an ordered JSON list. + * + * @param mixed $value Candidate decoded value. + * @param string $context Human-readable field context. + * + * @return list + * @since 0.3.0 + */ + public static function list(mixed $value, string $context): array + { + if (!is_array($value) || !array_is_list($value)) { + throw new ContractException(sprintf('%s must be a JSON list.', $context)); + } + + return $value; + } + + /** + * Requires a decoded map whose JSON keys may normalize to integers. + * + * PHP converts integer-like JSON object keys to integer array keys when + * decoding into associative arrays. This guard is reserved for schemas, + * such as chapter maps, that deliberately use numeric object keys. + * + * @param mixed $value Candidate decoded value. + * @param string $context Human-readable field context. + * + * @return array + * @since 0.3.0 + */ + public static function map(mixed $value, string $context): array + { + if (!is_array($value)) { + throw new ContractException(sprintf('%s must be a JSON map.', $context)); + } + + return $value; + } + + /** + * Prevents instantiation of this validation utility. + * + * @since 0.3.0 + */ + private function __construct() + { + } +} diff --git a/src/Contract/ValidationResult.php b/src/Contract/ValidationResult.php new file mode 100644 index 0000000..5e50350 --- /dev/null +++ b/src/Contract/ValidationResult.php @@ -0,0 +1,83 @@ + $modules Ordered module metadata. + * @param array $footer Validated footer record. + * + * @since 0.1.0 + */ + public function __construct( + private string $command, + private array $modules, + private array $footer, + ) { + } + + /** + * Returns `list` or `extract`. + * + * @return string + * @since 0.1.0 + */ + public function command(): string + { + return $this->command; + } + + /** + * Returns ordered validated module metadata. + * + * @return list + * @since 0.1.0 + */ + public function modules(): array + { + return $this->modules; + } + + /** + * Returns the validated footer record. + * + * @return array + * @since 0.1.0 + */ + public function footer(): array + { + return $this->footer; + } + + /** + * Returns the verified pre-footer stream digest. + * + * @return string + * @since 0.1.0 + */ + public function streamSha256(): string + { + $sha256 = $this->footer['stream_sha256'] ?? null; + + if (!is_string($sha256)) { + throw new \LogicException('Validated footer state has no stream digest.'); + } + + return $sha256; + } +} diff --git a/src/Contract/VerseScope.php b/src/Contract/VerseScope.php new file mode 100644 index 0000000..6bbed0c --- /dev/null +++ b/src/Contract/VerseScope.php @@ -0,0 +1,272 @@ + $scope Candidate scope. + * + * @return self + * @since 0.1.0 + */ + public static function fromArray(array $scope): self + { + $scope = StructuredData::object($scope, 'Verse scope'); + + if (($scope['type'] ?? null) !== 'verse_key') { + throw new ContractException('A Bible entry requires scope.type="verse_key".'); + } + + foreach (['testament', 'book', 'chapter', 'verse', 'suffix', 'index'] as $field) { + if (!isset($scope[$field]) || !is_int($scope[$field]) || $scope[$field] < 0) { + throw new ContractException(sprintf('Verse scope field "%s" is invalid.', $field)); + } + } + + if ($scope['suffix'] > 255) { + throw new ContractException('Verse scope suffix exceeds an unsigned byte.'); + } + + $intro = $scope['intro_scope'] ?? null; + + if (!is_string($intro) || !in_array($intro, ['module', 'testament', 'book', 'chapter', 'verse'], true)) { + throw new ContractException('Verse scope introduction classification is invalid.'); + } + + $bookAbbreviation = self::optionalByteValue($scope['book_abbreviation'] ?? null, 'book_abbreviation'); + $bookName = self::optionalByteValue($scope['book_name'] ?? null, 'book_name'); + $osis = self::requiredByteValue($scope['osis_reference'] ?? null, 'osis_reference'); + $versification = self::requiredByteValue($scope['versification'] ?? null, 'versification'); + + return new self( + $scope['testament'], + $scope['book'], + $scope['chapter'], + $scope['verse'], + $scope['suffix'], + $scope['index'], + $intro, + $bookAbbreviation, + $bookName, + $osis, + $versification, + ); + } + + /** + * Returns the SWORD testament position. + * + * @return int + * @since 0.1.0 + */ + public function testament(): int + { + return $this->testament; + } + + /** + * Returns the SWORD book position within the versification/testament. + * + * @return int + * @since 0.1.0 + */ + public function book(): int + { + return $this->book; + } + + /** + * Returns the chapter position. + * + * @return int + * @since 0.1.0 + */ + public function chapter(): int + { + return $this->chapter; + } + + /** + * Returns the verse position. + * + * @return int + * @since 0.1.0 + */ + public function verse(): int + { + return $this->verse; + } + + /** + * Returns the SWORD verse suffix byte. + * + * @return int + * @since 0.1.0 + */ + public function suffix(): int + { + return $this->suffix; + } + + /** + * Returns the active SWORD key index. + * + * @return int + * @since 0.1.0 + */ + public function index(): int + { + return $this->index; + } + + /** + * Returns the introduction classification. + * + * @return string + * @since 0.1.0 + */ + public function introductionScope(): string + { + return $this->introductionScope; + } + + /** + * Indicates whether the entry is an ordinary verse. + * + * @return bool + * @since 0.1.0 + */ + public function isVerse(): bool + { + return $this->introductionScope === 'verse' + && $this->book > 0 + && $this->chapter > 0 + && $this->verse > 0; + } + + /** + * Returns the exact book abbreviation when applicable. + * + * @return ByteValue|null + * @since 0.1.0 + */ + public function bookAbbreviation(): ?ByteValue + { + return $this->bookAbbreviation; + } + + /** + * Returns the exact book name when applicable. + * + * @return ByteValue|null + * @since 0.1.0 + */ + public function bookName(): ?ByteValue + { + return $this->bookName; + } + + /** + * Returns the exact OSIS reference. + * + * @return ByteValue + * @since 0.1.0 + */ + public function osisReference(): ByteValue + { + return $this->osisReference; + } + + /** + * Returns the exact versification identifier. + * + * @return ByteValue + * @since 0.1.0 + */ + public function versification(): ByteValue + { + return $this->versification; + } + + /** + * Validates a required byte value. + * + * @param mixed $value Candidate value. + * @param string $field Field name. + * + * @return ByteValue + * @since 0.1.0 + */ + private static function requiredByteValue(mixed $value, string $field): ByteValue + { + if (!is_array($value)) { + throw new ContractException(sprintf('Verse scope field "%s" is not a byte value.', $field)); + } + + return ByteValue::fromArray($value, 'scope.' . $field); + } + + /** + * Validates an optional byte value. + * + * @param mixed $value Candidate value. + * @param string $field Field name. + * + * @return ByteValue|null + * @since 0.1.0 + */ + private static function optionalByteValue(mixed $value, string $field): ?ByteValue + { + if ($value === null) { + return null; + } + + return self::requiredByteValue($value, $field); + } +} diff --git a/src/DependencyInjection/ContainerFactory.php b/src/DependencyInjection/ContainerFactory.php new file mode 100644 index 0000000..38236d1 --- /dev/null +++ b/src/DependencyInjection/ContainerFactory.php @@ -0,0 +1,48 @@ +share( + Configuration::class, + $configuration ?? Configuration::fromEnvironment(), + true, + ); + $container->registerServiceProvider(new ScriptureServiceProvider()); + + return $container; + } + + /** + * Prevents instantiation of this factory. + * + * @since 0.1.0 + */ + private function __construct() + { + } +} diff --git a/src/DependencyInjection/ContainerService.php b/src/DependencyInjection/ContainerService.php new file mode 100644 index 0000000..6dc438d --- /dev/null +++ b/src/DependencyInjection/ContainerService.php @@ -0,0 +1,51 @@ + $class Requested class or interface. + * + * @return T + * @since 0.3.0 + */ + public static function get(Container $container, string $class): object + { + $service = $container->get($class); + + if (!$service instanceof $class) { + throw new \LogicException(sprintf( + 'The Joomla container returned an invalid "%s" service.', + $class, + )); + } + + return $service; + } + + /** + * Prevents instantiation of this resolver. + * + * @since 0.3.0 + */ + private function __construct() + { + } +} diff --git a/src/DependencyInjection/ScriptureServiceProvider.php b/src/DependencyInjection/ScriptureServiceProvider.php new file mode 100644 index 0000000..4aedcb3 --- /dev/null +++ b/src/DependencyInjection/ScriptureServiceProvider.php @@ -0,0 +1,180 @@ +has(Configuration::class)) { + $container->share( + Configuration::class, + static fn (): Configuration => Configuration::fromEnvironment(), + true, + ); + } + + if (!$container->has(ClockInterface::class)) { + $container->share(ClockInterface::class, static fn (): ClockInterface => new SystemClock(), true); + } + + if (!$container->has(DispatcherInterface::class)) { + $container->share( + DispatcherInterface::class, + static fn (): DispatcherInterface => new Dispatcher(), + true, + ); + } + + $container->share( + ModuleExtractorInterface::class, + static fn (Container $container): ModuleExtractorInterface => new SwordEngineAdapter( + ContainerService::get($container, Configuration::class)->modulePath(), + ), + true, + ); + $container->share( + ContractV1ValidatorInterface::class, + static fn (): ContractV1ValidatorInterface => new ContractV1Validator(), + true, + ); + $container->share( + ModuleRootLockInterface::class, + static fn (Container $container): ModuleRootLockInterface => new FileModuleRootLock( + ContainerService::get($container, Configuration::class), + ), + true, + ); + $container->share( + MaintenanceLockInterface::class, + static fn (Container $container): MaintenanceLockInterface => new FileMaintenanceLock( + ContainerService::get($container, Configuration::class), + ), + true, + ); + $container->share( + MaintenanceStateStoreInterface::class, + static fn (Container $container): MaintenanceStateStoreInterface => new JsonMaintenanceStateStore( + ContainerService::get($container, Configuration::class), + ), + true, + ); + $container->share( + ModuleCatalogInterface::class, + static fn (Container $container): ModuleCatalogInterface => new ModuleCatalog( + ContainerService::get($container, ModuleExtractorInterface::class), + ContainerService::get($container, ContractV1ValidatorInterface::class), + ), + true, + ); + $container->share( + SnapshotManagerInterface::class, + static fn (Container $container): SnapshotManagerInterface => new TranslationSnapshotManager( + ContainerService::get($container, Configuration::class), + ContainerService::get($container, ClockInterface::class), + ContainerService::get($container, ModuleCatalogInterface::class), + ContainerService::get($container, ModuleExtractorInterface::class), + ContainerService::get($container, ContractV1ValidatorInterface::class), + ContainerService::get($container, DispatcherInterface::class), + ContainerService::get($container, ModuleRootLockInterface::class), + ), + true, + ); + $container->share( + ModuleProvisionerInterface::class, + static fn (): ModuleProvisionerInterface => new AbiV1ModuleProvisioner(), + true, + ); + $container->share( + ProvisioningCoordinatorInterface::class, + static fn (Container $container): ProvisioningCoordinatorInterface => new ProvisioningCoordinator( + ContainerService::get($container, ModuleProvisionerInterface::class), + ContainerService::get($container, ModuleRootLockInterface::class), + ContainerService::get($container, ModuleCatalogInterface::class), + ContainerService::get($container, SnapshotManagerInterface::class), + ContainerService::get($container, DispatcherInterface::class), + ), + true, + ); + $container->share( + MaintenanceServiceInterface::class, + static fn (Container $container): MaintenanceServiceInterface => new MaintenanceService( + ContainerService::get($container, Configuration::class), + ContainerService::get($container, ClockInterface::class), + ContainerService::get($container, ModuleCatalogInterface::class), + ContainerService::get($container, SnapshotManagerInterface::class), + ContainerService::get($container, ProvisioningCoordinatorInterface::class), + ContainerService::get($container, MaintenanceStateStoreInterface::class), + ContainerService::get($container, MaintenanceLockInterface::class), + ContainerService::get($container, DispatcherInterface::class), + ), + true, + ); + $container->share( + ScheduledRefreshHandler::class, + static fn (Container $container): ScheduledRefreshHandler => new ScheduledRefreshHandler( + ContainerService::get($container, MaintenanceServiceInterface::class), + ), + true, + ); + $container->share( + ScriptureInterface::class, + static fn (Container $container): ScriptureInterface => new Scripture( + ContainerService::get($container, ModuleCatalogInterface::class), + ContainerService::get($container, SnapshotManagerInterface::class), + ContainerService::get($container, ProvisioningCoordinatorInterface::class), + ContainerService::get($container, MaintenanceServiceInterface::class), + ), + true, + ); + $container->alias(Scripture::class, ScriptureInterface::class); + } +} diff --git a/src/Domain/Book.php b/src/Domain/Book.php new file mode 100644 index 0000000..77bbe53 --- /dev/null +++ b/src/Domain/Book.php @@ -0,0 +1,161 @@ +metadata = $snapshot->bookMetadata($bookKey); + } + + /** + * Returns the parent translation. + * + * @return Translation + * @since 0.1.0 + */ + public function translation(): Translation + { + return $this->translation; + } + + /** + * Returns the SWORD testament position. + * + * @return int + * @since 0.1.0 + */ + public function testament(): int + { + return $this->metadata['testament']; + } + + /** + * Returns the SWORD book position in its versification/testament. + * + * @return int + * @since 0.1.0 + */ + public function position(): int + { + return $this->metadata['position']; + } + + /** + * Returns the exact book name. + * + * @return ByteValue + * @since 0.1.0 + */ + public function name(): ByteValue + { + return $this->metadata['name']; + } + + /** + * Returns the exact book abbreviation. + * + * @return ByteValue + * @since 0.1.0 + */ + public function abbreviation(): ByteValue + { + return $this->metadata['abbreviation']; + } + + /** + * Returns the exact versification identifier. + * + * @return ByteValue + * @since 0.1.0 + */ + public function versification(): ByteValue + { + return $this->metadata['versification']; + } + + /** + * Returns ordered lazy chapter objects. + * + * @return list + * @since 0.1.0 + */ + public function chapters(): array + { + return array_map( + fn (int $number): Chapter => new Chapter($this, $this->snapshot, $this->bookKey, $number), + $this->snapshot->chapterNumbers($this->bookKey), + ); + } + + /** + * Returns one chapter. + * + * @param int $number Positive chapter number. + * + * @return Chapter + * @since 0.1.0 + */ + public function chapter(int $number): Chapter + { + if ($number < 1) { + throw new InvalidReferenceException('Chapter numbers must be positive.'); + } + + if (!in_array($number, $this->snapshot->chapterNumbers($this->bookKey), true)) { + throw new ReferenceNotFoundException(sprintf( + 'Chapter %d is not present in book "%s".', + $number, + $this->name()->utf8() ?? $this->abbreviation()->bytes(), + )); + } + + return new Chapter($this, $this->snapshot, $this->bookKey, $number); + } + + /** + * Returns book-level introductions. + * + * @return list + * @since 0.1.0 + */ + public function introductions(): array + { + return $this->snapshot->introductions($this->bookKey); + } +} diff --git a/src/Domain/Chapter.php b/src/Domain/Chapter.php new file mode 100644 index 0000000..30fa6bb --- /dev/null +++ b/src/Domain/Chapter.php @@ -0,0 +1,109 @@ +book; + } + + /** + * Returns the chapter number. + * + * @return int + * @since 0.1.0 + */ + public function number(): int + { + return $this->number; + } + + /** + * Returns one exact verse and optional suffix. + * + * @param int $number Positive verse number. + * @param int $suffix SWORD suffix byte. + * + * @return Verse + * @since 0.1.0 + */ + public function verse(int $number, int $suffix = 0): Verse + { + if ($number < 1 || $suffix < 0 || $suffix > 255) { + throw new InvalidReferenceException('Verse number or suffix is invalid.'); + } + + return $this->snapshot->verse($this->bookKey, $this->number, $number, $suffix); + } + + /** + * Returns all verses or an inclusive range, ordered by verse and suffix. + * + * @param int|null $start Optional first verse. + * @param int|null $end Optional last verse. + * + * @return list + * @since 0.1.0 + */ + public function verses(?int $start = null, ?int $end = null): array + { + if ( + ($start !== null && $start < 1) + || ($end !== null && $end < 1) + || ($start !== null && $end !== null && $end < $start) + ) { + throw new InvalidReferenceException('Verse range must be positive and ascending.'); + } + + return $this->snapshot->verses($this->bookKey, $this->number, $start, $end); + } + + /** + * Returns chapter-level introductions. + * + * @return list + * @since 0.1.0 + */ + public function introductions(): array + { + return $this->snapshot->introductions($this->bookKey, $this->number); + } +} diff --git a/src/Domain/ConfigEntry.php b/src/Domain/ConfigEntry.php new file mode 100644 index 0000000..49ec421 --- /dev/null +++ b/src/Domain/ConfigEntry.php @@ -0,0 +1,99 @@ + $record Configuration entry record. + * + * @return self + * @since 0.1.0 + */ + public static function fromRecord(array $record): self + { + $record = StructuredData::object($record, 'Configuration entry record'); + + if (($record['type'] ?? null) !== 'config_entry') { + throw new ContractException('ConfigEntry requires a config_entry record.'); + } + + $ordinal = $record['ordinal'] ?? null; + $name = $record['name'] ?? null; + $value = $record['value'] ?? null; + + if (!is_int($ordinal) || $ordinal < 0 || !is_array($name) || !is_array($value)) { + throw new ContractException('Configuration entry record is invalid.'); + } + + return new self( + $ordinal, + ByteValue::fromArray($name, 'config_entry.name'), + ByteValue::fromArray($value, 'config_entry.value'), + ); + } + + /** + * Returns the SWORD map order. + * + * @return int + * @since 0.1.0 + */ + public function ordinal(): int + { + return $this->ordinal; + } + + /** + * Returns the exact configuration name. + * + * @return ByteValue + * @since 0.1.0 + */ + public function name(): ByteValue + { + return $this->name; + } + + /** + * Returns the exact configuration value. + * + * @return ByteValue + * @since 0.1.0 + */ + public function value(): ByteValue + { + return $this->value; + } +} diff --git a/src/Domain/Introduction.php b/src/Domain/Introduction.php new file mode 100644 index 0000000..ebce392 --- /dev/null +++ b/src/Domain/Introduction.php @@ -0,0 +1,225 @@ + $segments Ordered lexical segments. + * @param OfficialAttributes $attributes Ordered official attributes. + * @param array $record Original record. + * + * @since 0.1.0 + */ + private function __construct( + private VerseScope $scope, + private ByteValue $key, + private ByteValue $raw, + private ?ByteValue $rendered, + private ?ByteValue $stripped, + private array $segments, + private OfficialAttributes $attributes, + private array $record, + ) { + } + + /** + * Validates and hydrates an introduction from an entry record. + * + * @param array $record Entry record. + * + * @return self + * @since 0.1.0 + */ + public static function fromRecord(array $record): self + { + $record = StructuredData::object($record, 'Introduction record'); + + if ( + ($record['type'] ?? null) !== 'entry' + || !is_array($record['scope'] ?? null) + || !is_array($record['key'] ?? null) + || !is_array($record['raw'] ?? null) + || !is_array($record['annotation_segments'] ?? null) + || !is_array($record['official_attributes'] ?? null) + || !is_bool($record['projections_available'] ?? null) + ) { + throw new ContractException('Introduction record is invalid.'); + } + + $scope = VerseScope::fromArray($record['scope']); + + if ($scope->isVerse()) { + throw new ContractException('An ordinary verse cannot be hydrated as an Introduction.'); + } + + $raw = ByteValue::fromArray($record['raw'], 'entry.raw'); + $segments = []; + $reconstructed = ''; + + foreach ($record['annotation_segments'] as $index => $segment) { + if (!is_array($segment)) { + throw new ContractException(sprintf('Annotation segment %d is invalid.', $index)); + } + + $object = AnnotationSegment::fromArray($segment, $index); + $segments[] = $object; + $reconstructed .= $object->raw()->bytes(); + } + + if ($reconstructed !== $raw->bytes()) { + throw new ContractException('Introduction annotation segments do not reconstruct entry.raw.'); + } + + $available = $record['projections_available']; + + return new self( + $scope, + ByteValue::fromArray($record['key'], 'entry.key'), + $raw, + self::projection($record['rendered_default'] ?? null, 'rendered_default', $available), + self::projection($record['stripped'] ?? null, 'stripped', $available), + $segments, + OfficialAttributes::fromArray($record['official_attributes']), + $record, + ); + } + + /** + * Returns the exact introduction scope. + * + * @return VerseScope + * @since 0.1.0 + */ + public function scope(): VerseScope + { + return $this->scope; + } + + /** + * Returns the exact native key. + * + * @return ByteValue + * @since 0.1.0 + */ + public function key(): ByteValue + { + return $this->key; + } + + /** + * Returns authoritative raw bytes. + * + * @return ByteValue + * @since 0.1.0 + */ + public function raw(): ByteValue + { + return $this->raw; + } + + /** + * Returns default-rendered bytes when available. + * + * @return ByteValue|null + * @since 0.1.0 + */ + public function rendered(): ?ByteValue + { + return $this->rendered; + } + + /** + * Returns stripped bytes when available. + * + * @return ByteValue|null + * @since 0.1.0 + */ + public function stripped(): ?ByteValue + { + return $this->stripped; + } + + /** + * Returns ordered lexical annotation segments. + * + * @return list + * @since 0.1.0 + */ + public function annotationSegments(): array + { + return $this->segments; + } + + /** + * Returns complete ordered official attributes. + * + * @return OfficialAttributes + * @since 0.1.0 + */ + public function officialAttributes(): OfficialAttributes + { + return $this->attributes; + } + + /** + * Returns the original validated record. + * + * @return array + * @since 0.1.0 + */ + public function contractRecord(): array + { + return $this->record; + } + + /** + * Validates an optional projection. + * + * @param mixed $value Candidate value. + * @param string $field Field name. + * @param bool $available Whether projections should exist. + * + * @return ByteValue|null + * @since 0.1.0 + */ + private static function projection(mixed $value, string $field, bool $available): ?ByteValue + { + if (!$available) { + if ($value !== null) { + throw new ContractException(sprintf('entry.%s must be null.', $field)); + } + + return null; + } + + if (!is_array($value)) { + throw new ContractException(sprintf('entry.%s must be a byte value.', $field)); + } + + return ByteValue::fromArray($value, 'entry.' . $field); + } +} diff --git a/src/Domain/Translation.php b/src/Domain/Translation.php new file mode 100644 index 0000000..e4ee530 --- /dev/null +++ b/src/Domain/Translation.php @@ -0,0 +1,208 @@ +moduleName; + } + + /** + * Returns the translation's native metadata. + * + * @return TranslationMetadata + * @since 0.1.0 + */ + public function metadata(): TranslationMetadata + { + return $this->snapshot->metadata(); + } + + /** + * Returns ordered lazy book objects. + * + * @return list + * @since 0.1.0 + */ + public function books(): array + { + return array_map( + fn (string $key): Book => new Book($this, $this->snapshot, $key), + $this->snapshot->bookKeys(), + ); + } + + /** + * Resolves a book by exact or ASCII-case-insensitive name/abbreviation. + * + * @param string $identifier Book name or abbreviation. + * + * @return Book + * @since 0.1.0 + */ + public function book(string $identifier): Book + { + foreach ($this->books() as $book) { + $name = $book->name()->bytes(); + $abbreviation = $book->abbreviation()->bytes(); + + if ( + $identifier === $name + || $identifier === $abbreviation + || strcasecmp($identifier, $name) === 0 + || strcasecmp($identifier, $abbreviation) === 0 + ) { + return $book; + } + } + + throw new ReferenceNotFoundException(sprintf( + 'Book "%s" is not present in translation "%s".', + $identifier, + $this->moduleName, + )); + } + + /** + * Resolves a book by module-versification testament and position. + * + * @param int $testament SWORD testament position. + * @param int $book SWORD book position. + * + * @return Book + * @since 0.1.0 + */ + public function bookByPosition(int $testament, int $book): Book + { + $key = $testament . ':' . $book; + + if (!in_array($key, $this->snapshot->bookKeys(), true)) { + throw new ReferenceNotFoundException(sprintf( + 'Book testament %d position %d is not present in translation "%s".', + $testament, + $book, + $this->moduleName, + )); + } + + return new Book($this, $this->snapshot, $key); + } + + /** + * Returns an inclusive verse range from a named book and chapter. + * + * @param string $book Book name or abbreviation. + * @param int $chapter Chapter number. + * @param int $start First verse. + * @param int $end Last verse. + * + * @return list + * @since 0.1.0 + */ + public function verses(string $book, int $chapter, int $start, int $end): array + { + return $this->book($book)->chapter($chapter)->verses($start, $end); + } + + /** + * Returns all ordered interpreted configuration entries. + * + * @return list + * @since 0.1.0 + */ + public function configEntries(): array + { + return $this->snapshot->configEntries(); + } + + /** + * Returns configuration entries matching one exact name. + * + * @param string $name Exact configuration name. + * + * @return list + * @since 0.1.0 + */ + public function configEntriesNamed(string $name): array + { + return $this->snapshot->configEntriesNamed($name); + } + + /** + * Returns module- and testament-level introductions. + * + * @return list + * @since 0.1.0 + */ + public function introductions(): array + { + return $this->snapshot->introductions(); + } + + /** + * Returns the complete validated native export path. + * + * @return string + * @since 0.1.0 + */ + public function rawExportPath(): string + { + return $this->snapshot->rawExportPath(); + } + + /** + * Returns the snapshot activation time. + * + * @return \DateTimeImmutable + * @since 0.1.0 + */ + public function activatedAt(): \DateTimeImmutable + { + return $this->snapshot->activatedAt(); + } + + /** + * Returns the snapshot freshness deadline. + * + * @return \DateTimeImmutable + * @since 0.1.0 + */ + public function expiresAt(): \DateTimeImmutable + { + return $this->snapshot->expiresAt(); + } +} diff --git a/src/Domain/TranslationMetadata.php b/src/Domain/TranslationMetadata.php new file mode 100644 index 0000000..d815bf2 --- /dev/null +++ b/src/Domain/TranslationMetadata.php @@ -0,0 +1,263 @@ + + * @since 0.1.0 + */ + private const CLASSIFICATIONS = [ + 'bible', + 'commentary', + 'dictionary_or_lexicon', + 'general_book', + 'devotional', + 'resource', + 'unknown', + ]; + + /** + * Creates complete module metadata. + * + * @param string $classification Convenience classification. + * @param ByteValue $name Exact module identifier. + * @param ByteValue $description Exact description. + * @param ByteValue $driver Exact ModDrv. + * @param ByteValue $language Exact language identifier. + * @param ByteValue $swordType Exact authoritative SWORD type. + * @param EnumValue $direction Native direction. + * @param EnumValue $encoding Native encoding. + * @param EnumValue $markup Native markup. + * @param array $record Original record. + * + * @since 0.1.0 + */ + private function __construct( + private string $classification, + private ByteValue $name, + private ByteValue $description, + private ByteValue $driver, + private ByteValue $language, + private ByteValue $swordType, + private EnumValue $direction, + private EnumValue $encoding, + private EnumValue $markup, + private array $record, + ) { + } + + /** + * Validates and creates metadata from a module record. + * + * @param array $record Module record. + * + * @return self + * @since 0.1.0 + */ + public static function fromRecord(array $record): self + { + $record = StructuredData::object($record, 'Module record'); + + if (($record['type'] ?? null) !== 'module') { + throw new ContractException('Translation metadata requires a module record.'); + } + + $classification = $record['classification'] ?? null; + + if (!is_string($classification) || !in_array($classification, self::CLASSIFICATIONS, true)) { + throw new ContractException('Module classification is invalid.'); + } + + return new self( + $classification, + self::byteValue($record, 'name'), + self::byteValue($record, 'description'), + self::byteValue($record, 'driver'), + self::byteValue($record, 'language'), + self::byteValue($record, 'sword_type'), + self::enumValue($record, 'direction'), + self::enumValue($record, 'encoding'), + self::enumValue($record, 'markup'), + $record, + ); + } + + /** + * Returns the producer convenience classification. + * + * @return string + * @since 0.1.0 + */ + public function classification(): string + { + return $this->classification; + } + + /** + * Indicates whether this module is a Bible translation. + * + * @return bool + * @since 0.1.0 + */ + public function isBible(): bool + { + return $this->classification === 'bible'; + } + + /** + * Returns the exact module identifier. + * + * @return ByteValue + * @since 0.1.0 + */ + public function name(): ByteValue + { + return $this->name; + } + + /** + * Returns the exact module description. + * + * @return ByteValue + * @since 0.1.0 + */ + public function description(): ByteValue + { + return $this->description; + } + + /** + * Returns the exact native module driver. + * + * @return ByteValue + * @since 0.1.0 + */ + public function driver(): ByteValue + { + return $this->driver; + } + + /** + * Returns the exact module language identifier. + * + * @return ByteValue + * @since 0.1.0 + */ + public function language(): ByteValue + { + return $this->language; + } + + /** + * Returns the authoritative exact SWORD module type. + * + * @return ByteValue + * @since 0.1.0 + */ + public function swordType(): ByteValue + { + return $this->swordType; + } + + /** + * Returns the native direction. + * + * @return EnumValue + * @since 0.1.0 + */ + public function direction(): EnumValue + { + return $this->direction; + } + + /** + * Returns the native encoding. + * + * @return EnumValue + * @since 0.1.0 + */ + public function encoding(): EnumValue + { + return $this->encoding; + } + + /** + * Returns the native markup. + * + * @return EnumValue + * @since 0.1.0 + */ + public function markup(): EnumValue + { + return $this->markup; + } + + /** + * Returns the original validated module record. + * + * @return array + * @since 0.1.0 + */ + public function contractRecord(): array + { + return $this->record; + } + + /** + * Extracts a required byte envelope. + * + * @param array $record Module record. + * @param string $field Field name. + * + * @return ByteValue + * @since 0.1.0 + */ + private static function byteValue(array $record, string $field): ByteValue + { + $value = $record[$field] ?? null; + + if (!is_array($value)) { + throw new ContractException(sprintf('Module field "%s" is not a byte value.', $field)); + } + + return ByteValue::fromArray($value, 'module.' . $field); + } + + /** + * Extracts a required native enumeration. + * + * @param array $record Module record. + * @param string $field Field name. + * + * @return EnumValue + * @since 0.1.0 + */ + private static function enumValue(array $record, string $field): EnumValue + { + $value = $record[$field] ?? null; + + if (!is_array($value)) { + throw new ContractException(sprintf('Module field "%s" is not an enum value.', $field)); + } + + return EnumValue::fromArray($value, 'module.' . $field); + } +} diff --git a/src/Domain/Verse.php b/src/Domain/Verse.php new file mode 100644 index 0000000..1d08b59 --- /dev/null +++ b/src/Domain/Verse.php @@ -0,0 +1,252 @@ + $segments Lexical raw segments. + * @param OfficialAttributes $attributes Official SWORD attributes. + * @param array $record Original entry record. + * + * @since 0.1.0 + */ + private function __construct( + private int $ordinal, + private ByteValue $key, + private VerseScope $scope, + private ByteValue $raw, + private ?ByteValue $rendered, + private ?ByteValue $stripped, + private array $segments, + private OfficialAttributes $attributes, + private array $record, + ) { + } + + /** + * Validates and hydrates an ordinary verse from an entry record. + * + * @param array $record Entry record. + * + * @return self + * @since 0.1.0 + */ + public static function fromRecord(array $record): self + { + $record = StructuredData::object($record, 'Verse record'); + + if (($record['type'] ?? null) !== 'entry') { + throw new ContractException('Verse hydration requires an entry record.'); + } + + $ordinal = $record['ordinal'] ?? null; + $key = $record['key'] ?? null; + $raw = $record['raw'] ?? null; + $scopeValue = $record['scope'] ?? null; + $segmentsValue = $record['annotation_segments'] ?? null; + $attributesValue = $record['official_attributes'] ?? null; + $available = $record['projections_available'] ?? null; + + if (!is_int($ordinal) || $ordinal < 0 || !is_array($key) || !is_array($raw)) { + throw new ContractException('Entry ordinal, key, or raw byte value is invalid.'); + } + + if (!is_array($scopeValue) || !is_array($segmentsValue) || !is_array($attributesValue)) { + throw new ContractException('Entry scope, annotations, or official attributes are invalid.'); + } + + if (!is_bool($available)) { + throw new ContractException('Entry projections_available must be boolean.'); + } + + $scope = VerseScope::fromArray($scopeValue); + + if (!$scope->isVerse()) { + throw new ContractException('An introduction cannot be hydrated as an ordinary Verse.'); + } + + $rawValue = ByteValue::fromArray($raw, 'entry.raw'); + $segments = []; + $reconstructed = ''; + + foreach ($segmentsValue as $index => $segment) { + if (!is_array($segment)) { + throw new ContractException(sprintf('Annotation segment %d is not an object.', $index)); + } + + $object = AnnotationSegment::fromArray($segment, $index); + $segments[] = $object; + $reconstructed .= $object->raw()->bytes(); + } + + if ($reconstructed !== $rawValue->bytes()) { + throw new ContractException('Annotation segments do not reconstruct entry.raw.'); + } + + $rendered = self::projection($record['rendered_default'] ?? null, 'rendered_default', $available); + $stripped = self::projection($record['stripped'] ?? null, 'stripped', $available); + + return new self( + $ordinal, + ByteValue::fromArray($key, 'entry.key'), + $scope, + $rawValue, + $rendered, + $stripped, + $segments, + OfficialAttributes::fromArray($attributesValue), + $record, + ); + } + + /** + * Returns the native traversal ordinal. + * + * @return int + * @since 0.1.0 + */ + public function ordinal(): int + { + return $this->ordinal; + } + + /** + * Returns the exact native key. + * + * @return ByteValue + * @since 0.1.0 + */ + public function key(): ByteValue + { + return $this->key; + } + + /** + * Returns the exact verse scope. + * + * @return VerseScope + * @since 0.1.0 + */ + public function scope(): VerseScope + { + return $this->scope; + } + + /** + * Returns authoritative raw entry bytes. + * + * @return ByteValue + * @since 0.1.0 + */ + public function raw(): ByteValue + { + return $this->raw; + } + + /** + * Returns the default SWORD rendering when available. + * + * @return ByteValue|null + * @since 0.1.0 + */ + public function rendered(): ?ByteValue + { + return $this->rendered; + } + + /** + * Returns the stripped text projection when available. + * + * @return ByteValue|null + * @since 0.1.0 + */ + public function stripped(): ?ByteValue + { + return $this->stripped; + } + + /** + * Returns ordered, lossless lexical annotation segments. + * + * @return list + * @since 0.1.0 + */ + public function annotationSegments(): array + { + return $this->segments; + } + + /** + * Returns the complete ordered SWORD official attributes. + * + * @return OfficialAttributes + * @since 0.1.0 + */ + public function officialAttributes(): OfficialAttributes + { + return $this->attributes; + } + + /** + * Returns the original validated contract record. + * + * @return array + * @since 0.1.0 + */ + public function contractRecord(): array + { + return $this->record; + } + + /** + * Validates an optional rendered or stripped projection. + * + * @param mixed $value Candidate value. + * @param string $field Field name. + * @param bool $available Whether projections should exist. + * + * @return ByteValue|null + * @since 0.1.0 + */ + private static function projection(mixed $value, string $field, bool $available): ?ByteValue + { + if (!$available) { + if ($value !== null) { + throw new ContractException(sprintf('entry.%s must be null when projections are unavailable.', $field)); + } + + return null; + } + + if (!is_array($value)) { + throw new ContractException(sprintf('entry.%s must be a byte value.', $field)); + } + + return ByteValue::fromArray($value, 'entry.' . $field); + } +} diff --git a/src/Event/EventName.php b/src/Event/EventName.php new file mode 100644 index 0000000..b6141ba --- /dev/null +++ b/src/Event/EventName.php @@ -0,0 +1,108 @@ +path); + + if (!Folder::create($directory, 0750)) { + throw new \RuntimeException(sprintf('Unable to create lock directory "%s".', $directory)); + } + + $handle = fopen($this->path, 'c+b'); + + if (!is_resource($handle)) { + throw new \RuntimeException(sprintf('Unable to open lifecycle lock "%s".', $this->path)); + } + + $deadline = hrtime(true) + ($this->timeout * 1_000_000_000); + $acquired = false; + + try { + do { + $acquired = flock($handle, $mode | LOCK_NB); + + if ($acquired) { + break; + } + + usleep(50_000); + } while (hrtime(true) < $deadline); + + if (!$acquired) { + throw new \RuntimeException(sprintf( + 'Timed out after %d seconds waiting for lifecycle lock "%s".', + $this->timeout, + $this->path, + )); + } + + return $operation(); + } finally { + if ($acquired) { + flock($handle, LOCK_UN); + } + + fclose($handle); + } + } +} diff --git a/src/Infrastructure/Lock/FileMaintenanceLock.php b/src/Infrastructure/Lock/FileMaintenanceLock.php new file mode 100644 index 0000000..f042317 --- /dev/null +++ b/src/Infrastructure/Lock/FileMaintenanceLock.php @@ -0,0 +1,55 @@ +lock = new BoundedFileLock( + $configuration->cachePath() . '/locks/maintenance.lock', + $configuration->lockTimeout(), + ); + } + + /** + * Executes one complete maintenance run under an exclusive lock. + * + * @template T + * + * @param callable(): T $operation Maintenance callback. + * + * @return T + * @since 0.3.0 + */ + public function run(callable $operation): mixed + { + return $this->lock->synchronized(LOCK_EX, $operation); + } +} diff --git a/src/Infrastructure/Lock/FileModuleRootLock.php b/src/Infrastructure/Lock/FileModuleRootLock.php new file mode 100644 index 0000000..4cc02aa --- /dev/null +++ b/src/Infrastructure/Lock/FileModuleRootLock.php @@ -0,0 +1,70 @@ +lock = new BoundedFileLock( + $configuration->cachePath() . '/locks/module-root.lock', + $configuration->lockTimeout(), + ); + } + + /** + * Executes an operation under a shared lock. + * + * @template T + * + * @param callable(): T $operation Read operation. + * + * @return T + * @since 0.2.0 + */ + public function read(callable $operation): mixed + { + return $this->lock->synchronized(LOCK_SH, $operation); + } + + /** + * Executes an operation under an exclusive lock. + * + * @template T + * + * @param callable(): T $operation Write operation. + * + * @return T + * @since 0.2.0 + */ + public function write(callable $operation): mixed + { + return $this->lock->synchronized(LOCK_EX, $operation); + } +} diff --git a/src/Infrastructure/Lock/MaintenanceLockInterface.php b/src/Infrastructure/Lock/MaintenanceLockInterface.php new file mode 100644 index 0000000..4342172 --- /dev/null +++ b/src/Infrastructure/Lock/MaintenanceLockInterface.php @@ -0,0 +1,27 @@ +engine = new \GetBible\Sword\Engine($modulePath); + } + + /** + * Returns the native engine's resolved SWORD root. + * + * @return string + * @since 0.1.0 + */ + public function modulePath(): string + { + return $this->engine->modulePath(); + } + + /** + * Streams installed modules and translates native failures. + * + * @param resource $destination Writable destination. + * + * @return int + * @since 0.1.0 + */ + public function streamModules(mixed $destination): int + { + try { + return $this->engine->streamModules($destination); + } catch (\GetBible\Sword\Exception $exception) { + throw new NativeEngineException( + 'Unable to stream installed SWORD modules: ' . $exception->getMessage(), + $exception->getCode(), + $exception, + ); + } + } + + /** + * Streams an installed module and translates native failures. + * + * @param string $module Module identifier. + * @param resource $destination Writable destination. + * @param int $artifactChunkSize Artifact record chunk size. + * + * @return int + * @since 0.1.0 + */ + public function streamModule( + string $module, + mixed $destination, + int $artifactChunkSize = 1048576, + ): int { + try { + return $this->engine->streamModule($module, $destination, $artifactChunkSize); + } catch (\GetBible\Sword\Exception $exception) { + throw new NativeEngineException( + sprintf('Unable to stream SWORD module "%s": %s', $module, $exception->getMessage()), + $exception->getCode(), + $exception, + ); + } + } +} diff --git a/src/Integration/Joomla/ScheduledRefreshHandler.php b/src/Integration/Joomla/ScheduledRefreshHandler.php new file mode 100644 index 0000000..d32ee8c --- /dev/null +++ b/src/Integration/Joomla/ScheduledRefreshHandler.php @@ -0,0 +1,51 @@ +maintenance->refreshIfDue(); + } + + /** + * Invokes the scheduler bridge as a callable service. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function __invoke(): MaintenanceResult + { + return $this->run(); + } +} diff --git a/src/Maintenance/JsonMaintenanceStateStore.php b/src/Maintenance/JsonMaintenanceStateStore.php new file mode 100644 index 0000000..afc8d90 --- /dev/null +++ b/src/Maintenance/JsonMaintenanceStateStore.php @@ -0,0 +1,126 @@ +path = $configuration->maintenanceStatePath(); + } + + /** + * Loads state or returns empty state when no run has completed. + * + * @return MaintenanceState + * @since 0.3.0 + */ + public function load(): MaintenanceState + { + $json = @file_get_contents($this->path); + + if ($json === false) { + return MaintenanceState::empty(); + } + + try { + $state = json_decode($json, true, 32, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new \RuntimeException('Unable to decode durable maintenance state.', 0, $exception); + } + + return MaintenanceState::fromArray( + StructuredData::object($state, 'Durable maintenance state'), + ); + } + + /** + * Atomically replaces the durable maintenance state. + * + * @param MaintenanceState $state New state. + * + * @return void + * @since 0.3.0 + */ + public function save(MaintenanceState $state): void + { + $directory = dirname($this->path); + + if (!Folder::create($directory, 0750)) { + throw new \RuntimeException(sprintf('Unable to create maintenance state directory "%s".', $directory)); + } + + try { + $json = json_encode( + $state->toArray(), + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + ) . "\n"; + } catch (\JsonException $exception) { + throw new \RuntimeException('Unable to encode durable maintenance state.', 0, $exception); + } + + $temporary = $this->path . '.' . bin2hex(random_bytes(8)) . '.tmp'; + $stream = fopen($temporary, 'x+b'); + + if (!is_resource($stream)) { + throw new \RuntimeException('Unable to create temporary maintenance state.'); + } + + $failure = null; + + try { + $written = fwrite($stream, $json); + + if ( + $written !== strlen($json) + || fflush($stream) === false + || (function_exists('fsync') && fsync($stream) === false) + ) { + throw new \RuntimeException('Unable to synchronize temporary maintenance state.'); + } + } catch (\Throwable $exception) { + $failure = $exception; + } finally { + fclose($stream); + } + + if ($failure !== null) { + @unlink($temporary); + + throw $failure; + } + + if (!rename($temporary, $this->path)) { + @unlink($temporary); + throw new \RuntimeException('Unable to atomically activate maintenance state.'); + } + } +} diff --git a/src/Maintenance/MaintenanceModuleResult.php b/src/Maintenance/MaintenanceModuleResult.php new file mode 100644 index 0000000..d474768 --- /dev/null +++ b/src/Maintenance/MaintenanceModuleResult.php @@ -0,0 +1,131 @@ +module; + } + + /** + * Returns the final status. + * + * @return string + * @since 0.3.0 + */ + public function status(): string + { + return $this->status; + } + + /** + * Returns the diagnostic message. + * + * @return string + * @since 0.3.0 + */ + public function message(): string + { + return $this->message; + } + + /** + * Reports whether this module failed. + * + * @return bool + * @since 0.3.0 + */ + public function failed(): bool + { + return $this->status === self::STATUS_FAILED; + } + + /** + * Returns a serialization-safe module outcome. + * + * @return array{module: string, status: string, message: string} + * @since 0.3.0 + */ + public function toArray(): array + { + return [ + 'module' => $this->module, + 'status' => $this->status, + 'message' => $this->message, + ]; + } +} diff --git a/src/Maintenance/MaintenanceResult.php b/src/Maintenance/MaintenanceResult.php new file mode 100644 index 0000000..e945573 --- /dev/null +++ b/src/Maintenance/MaintenanceResult.php @@ -0,0 +1,218 @@ + + * @since 0.3.0 + */ + private array $modules; + + /** + * Ordered validated operation-level errors. + * + * @var list + * @since 0.3.0 + */ + private array $errors; + + /** + * Creates a complete maintenance outcome. + * + * @param string $operation Stable operation name. + * @param \DateTimeImmutable $startedAt Start time. + * @param \DateTimeImmutable $completedAt Completion time. + * @param bool $due Whether interval policy required work. + * @param array $modules Per-module outcomes. + * @param ProvisioningResult|null $provisioning Optional remote provisioning outcome. + * @param array $errors Operation-level errors. + * @param string|null $skipReason Reason interval work was skipped. + * + * @since 0.3.0 + */ + public function __construct( + private string $operation, + private \DateTimeImmutable $startedAt, + private \DateTimeImmutable $completedAt, + private bool $due, + array $modules, + private ?ProvisioningResult $provisioning, + array $errors, + private ?string $skipReason = null, + ) { + if (trim($operation) === '' || $completedAt < $startedAt) { + throw new \InvalidArgumentException('Maintenance operation and chronological timestamps are required.'); + } + + $validatedModules = []; + + foreach ($modules as $module) { + if (!$module instanceof MaintenanceModuleResult) { + throw new \InvalidArgumentException('Maintenance results must contain module outcomes.'); + } + + $validatedModules[] = $module; + } + + $validatedErrors = []; + + foreach ($errors as $error) { + if (!is_string($error) || trim($error) === '') { + throw new \InvalidArgumentException('Maintenance errors must be non-empty strings.'); + } + + $validatedErrors[] = $error; + } + + $this->modules = $validatedModules; + $this->errors = $validatedErrors; + } + + /** + * Returns the stable operation name. + * + * @return string + * @since 0.3.0 + */ + public function operation(): string + { + return $this->operation; + } + + /** + * Returns the operation start time. + * + * @return \DateTimeImmutable + * @since 0.3.0 + */ + public function startedAt(): \DateTimeImmutable + { + return $this->startedAt; + } + + /** + * Returns the operation completion time. + * + * @return \DateTimeImmutable + * @since 0.3.0 + */ + public function completedAt(): \DateTimeImmutable + { + return $this->completedAt; + } + + /** + * Reports whether interval policy required work. + * + * @return bool + * @since 0.3.0 + */ + public function due(): bool + { + return $this->due; + } + + /** + * Returns ordered per-module outcomes. + * + * @return list + * @since 0.3.0 + */ + public function modules(): array + { + return $this->modules; + } + + /** + * Returns the optional remote provisioning outcome. + * + * @return ProvisioningResult|null + * @since 0.3.0 + */ + public function provisioning(): ?ProvisioningResult + { + return $this->provisioning; + } + + /** + * Returns operation-level errors. + * + * @return list + * @since 0.3.0 + */ + public function errors(): array + { + return $this->errors; + } + + /** + * Returns the interval skip reason. + * + * @return string|null + * @since 0.3.0 + */ + public function skipReason(): ?string + { + return $this->skipReason; + } + + /** + * Reports whether the complete operation succeeded. + * + * @return bool + * @since 0.3.0 + */ + public function succeeded(): bool + { + if ($this->errors !== [] || ($this->provisioning !== null && !$this->provisioning->succeeded())) { + return false; + } + + foreach ($this->modules as $module) { + if ($module->failed()) { + return false; + } + } + + return true; + } + + /** + * Returns a serialization-safe maintenance outcome. + * + * @return array + * @since 0.3.0 + */ + public function toArray(): array + { + return [ + 'operation' => $this->operation, + 'succeeded' => $this->succeeded(), + 'due' => $this->due, + 'started_at' => $this->startedAt->format(DATE_ATOM), + 'completed_at' => $this->completedAt->format(DATE_ATOM), + 'skip_reason' => $this->skipReason, + 'errors' => $this->errors, + 'provisioning' => $this->provisioning?->toArray(), + 'modules' => array_map( + static fn (MaintenanceModuleResult $module): array => $module->toArray(), + $this->modules, + ), + ]; + } +} diff --git a/src/Maintenance/MaintenanceService.php b/src/Maintenance/MaintenanceService.php new file mode 100644 index 0000000..32f90a8 --- /dev/null +++ b/src/Maintenance/MaintenanceService.php @@ -0,0 +1,545 @@ + $modules Explicit module targets or configuration defaults. + * @param bool $all Whether every policy-approved translation should be installed. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function initialize(array $modules = [], bool $all = false): MaintenanceResult + { + $modules = $this->normalizeModules($modules); + + return $this->execute( + 'initialize', + fn (\DateTimeImmutable $startedAt): MaintenanceResult => $this->runInitialize( + $modules, + $all || $this->configuration->installAll(), + $startedAt, + ), + ); + } + + /** + * Refreshes remote modules when enabled and rebuilds their snapshots. + * + * @param list $modules Explicit module targets or configuration defaults. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function refresh(array $modules = []): MaintenanceResult + { + $modules = $this->normalizeModules($modules); + + return $this->execute( + 'refresh', + fn (\DateTimeImmutable $startedAt): MaintenanceResult => $this->runRefresh( + $modules, + $startedAt, + 'refresh', + ), + ); + } + + /** + * Refreshes only when the durable interval policy is due. + * + * @param list $modules Explicit module targets or configuration defaults. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function refreshIfDue(array $modules = []): MaintenanceResult + { + $modules = $this->normalizeModules($modules); + + return $this->execute( + 'refresh-if-due', + function (\DateTimeImmutable $startedAt) use ($modules): MaintenanceResult { + $state = $this->stateStore->load(); + + if (!$state->isDue($startedAt, $this->configuration->refreshInterval())) { + return new MaintenanceResult( + 'refresh-if-due', + $startedAt, + $this->clock->now(), + false, + [], + null, + [], + 'The configured refresh interval has not elapsed.', + ); + } + + return $this->runRefresh($modules, $startedAt, 'refresh-if-due'); + }, + ); + } + + /** + * Returns current maintenance, capability, and installed-module status. + * + * @return MaintenanceStatus + * @since 0.3.0 + */ + public function status(): MaintenanceStatus + { + $now = $this->clock->now(); + $state = $this->stateStore->load(); + $interval = $this->configuration->refreshInterval(); + + return new MaintenanceStatus( + $now, + $state->isDue($now, $interval), + $state->nextDueAt($interval), + $state, + $this->provisioning->capabilities(), + $this->configuration->provisioningEnabled(), + $this->configuration->modules(), + array_keys($this->installedModules()), + ); + } + + /** + * Runs initialization inside the whole-run lock. + * + * @param list $requested Explicit module targets. + * @param bool $all Whether all approved modules should be installed. + * @param \DateTimeImmutable $startedAt Operation start. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + private function runInitialize( + array $requested, + bool $all, + \DateTimeImmutable $startedAt, + ): MaintenanceResult { + $targets = $requested !== [] ? $requested : $this->configuration->modules(); + $errors = []; + $moduleResults = []; + $reported = []; + $provisioning = null; + $installed = $this->installedModules(); + + if ($all) { + if (!$this->configuration->provisioningEnabled()) { + $errors[] = 'All-module installation is disabled by runtime provisioning policy.'; + } elseif (!$this->provisioning->capabilities()->canInstallAll()) { + $errors[] = 'The active native backend cannot install all translations.'; + } else { + $provisioning = $this->captureProvisioning( + fn (): ProvisioningResult => $this->provisioning->installAll(), + $errors, + ); + } + } else { + $missing = array_values(array_filter( + $targets, + static fn (string $module): bool => !isset($installed[$module]), + )); + + if ($missing !== []) { + if (!$this->configuration->provisioningEnabled()) { + $errors[] = sprintf( + 'Missing modules cannot be installed because provisioning is disabled: %s.', + implode(', ', $missing), + ); + } elseif (!$this->provisioning->capabilities()->canInstallSelected()) { + $errors[] = sprintf( + 'The active native backend cannot install missing modules: %s.', + implode(', ', $missing), + ); + } else { + $provisioning = $this->captureProvisioning( + fn (): ProvisioningResult => $this->provisioning->install($missing), + $errors, + ); + } + } + } + + $installed = $this->installedModules(); + + if ($targets === []) { + $targets = array_keys($installed); + } + + if ($targets === []) { + $errors[] = 'No installed Bible translations are available to initialize.'; + } + + foreach ($targets as $module) { + if (!isset($installed[$module])) { + $moduleResults[] = new MaintenanceModuleResult( + $module, + MaintenanceModuleResult::STATUS_FAILED, + 'The translation is not installed.', + ); + $reported[$module] = true; + continue; + } + + try { + $this->snapshots->get($module); + $moduleResults[] = new MaintenanceModuleResult( + $module, + MaintenanceModuleResult::STATUS_READY, + 'The validated translation snapshot is ready.', + ); + $reported[$module] = true; + } catch (\Throwable $exception) { + $moduleResults[] = new MaintenanceModuleResult( + $module, + MaintenanceModuleResult::STATUS_FAILED, + $exception->getMessage(), + ); + $reported[$module] = true; + } + } + + if ($provisioning !== null) { + foreach ($provisioning->failed() as $module) { + if (!isset($reported[$module])) { + $moduleResults[] = new MaintenanceModuleResult( + $module, + MaintenanceModuleResult::STATUS_FAILED, + 'Native provisioning failed for this translation.', + ); + } + } + } + + return $this->complete( + 'initialize', + $startedAt, + true, + $moduleResults, + $provisioning, + $errors, + ); + } + + /** + * Runs remote refresh policy and rebuilds selected snapshots. + * + * @param list $requested Explicit module targets. + * @param \DateTimeImmutable $startedAt Operation start. + * @param string $operation Stable operation name. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + private function runRefresh( + array $requested, + \DateTimeImmutable $startedAt, + string $operation, + ): MaintenanceResult { + $installed = $this->installedModules(); + $targets = $requested !== [] ? $requested : $this->configuration->modules(); + + if ($targets === []) { + $targets = array_keys($installed); + } + + $errors = []; + $moduleResults = []; + $provisioning = null; + + if ($targets === []) { + $errors[] = 'No installed Bible translations are available to refresh.'; + } + + if ($this->configuration->provisioningEnabled()) { + if (!$this->provisioning->capabilities()->canRefresh()) { + $errors[] = 'Remote refresh is enabled by policy but unavailable in the active native backend.'; + } else { + $provisioning = $this->captureProvisioning( + fn (): ProvisioningResult => $this->provisioning->refresh($targets), + $errors, + ); + } + } + + $installed = $this->installedModules(); + + foreach ($targets as $module) { + if (!isset($installed[$module])) { + $moduleResults[] = new MaintenanceModuleResult( + $module, + MaintenanceModuleResult::STATUS_FAILED, + 'The translation is not installed.', + ); + continue; + } + + try { + $this->snapshots->refresh($module); + $moduleResults[] = new MaintenanceModuleResult( + $module, + MaintenanceModuleResult::STATUS_REFRESHED, + 'The validated translation snapshot was rebuilt.', + ); + } catch (\Throwable $exception) { + $moduleResults[] = new MaintenanceModuleResult( + $module, + MaintenanceModuleResult::STATUS_FAILED, + $exception->getMessage(), + ); + } + } + + return $this->complete( + $operation, + $startedAt, + true, + $moduleResults, + $provisioning, + $errors, + ); + } + + /** + * Calls native provisioning and converts thrown failures into run errors. + * + * @param callable(): ProvisioningResult $callback Provisioning operation. + * @param list $errors Operation errors, updated by reference. + * + * @return ProvisioningResult|null + * @since 0.3.0 + */ + private function captureProvisioning(callable $callback, array &$errors): ?ProvisioningResult + { + try { + $result = $callback(); + + if (!$result->succeeded()) { + $errors[] = sprintf( + 'Native provisioning failed for: %s.', + implode(', ', $result->failed()), + ); + } + + return $result; + } catch (\Throwable $exception) { + $errors[] = 'Native provisioning failed: ' . $exception->getMessage(); + + return null; + } + } + + /** + * Persists outcome state and creates the immutable result. + * + * @param string $operation Stable operation name. + * @param \DateTimeImmutable $startedAt Operation start. + * @param bool $due Whether interval policy required work. + * @param list $modules Per-module outcomes. + * @param ProvisioningResult|null $provisioning Optional provisioning outcome. + * @param list $errors Operation errors. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + private function complete( + string $operation, + \DateTimeImmutable $startedAt, + bool $due, + array $modules, + ?ProvisioningResult $provisioning, + array $errors, + ): MaintenanceResult { + $completedAt = $this->clock->now(); + $result = new MaintenanceResult( + $operation, + $startedAt, + $completedAt, + $due, + $modules, + $provisioning, + $errors, + ); + $state = $this->stateStore->load(); + + if ($result->succeeded()) { + $state = $state->succeededAt($completedAt); + } else { + $failureMessages = $errors; + + foreach ($modules as $module) { + if ($module->failed()) { + $failureMessages[] = sprintf('%s: %s', $module->module(), $module->message()); + } + } + + if ($failureMessages === []) { + $failureMessages[] = 'Maintenance did not complete successfully.'; + } + + $state = $state->failedAt( + $completedAt, + implode(' | ', array_values(array_unique($failureMessages))), + ); + } + + $this->stateStore->save($state); + + return $result; + } + + /** + * Executes a maintenance callback under the whole-run lock and emits events. + * + * @param string $operation Stable operation name. + * @param callable(\DateTimeImmutable): MaintenanceResult $callback Operation callback. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + private function execute(string $operation, callable $callback): MaintenanceResult + { + $result = $this->lock->run(function () use ($operation, $callback): MaintenanceResult { + $startedAt = $this->clock->now(); + $this->dispatcher->dispatch( + EventName::MAINTENANCE_STARTED, + new Event(EventName::MAINTENANCE_STARTED, [ + 'operation' => $operation, + 'started_at' => $startedAt, + ]), + ); + + try { + $result = $callback($startedAt); + $this->dispatcher->dispatch( + EventName::MAINTENANCE_COMPLETED, + new Event(EventName::MAINTENANCE_COMPLETED, [ + 'operation' => $operation, + 'result' => $result, + ]), + ); + + return $result; + } catch (\Throwable $exception) { + $this->dispatcher->dispatch( + EventName::MAINTENANCE_FAILED, + new Event(EventName::MAINTENANCE_FAILED, [ + 'operation' => $operation, + 'exception' => $exception, + ]), + ); + + throw $exception; + } + }); + + return $result; + } + + /** + * Returns installed Bible modules keyed by exact identifier. + * + * @return array + * @since 0.3.0 + */ + private function installedModules(): array + { + $installed = []; + + foreach ($this->catalog->translations() as $translation) { + $module = $translation->name()->bytes(); + + if ($module === '' || str_contains($module, "\0")) { + throw new \UnexpectedValueException('The native catalog returned an invalid module identifier.'); + } + + $installed[$module] = true; + } + + return $installed; + } + + /** + * Validates, trims, and de-duplicates explicit module identifiers. + * + * @param array $modules Candidate identifiers. + * + * @return list + * @since 0.3.0 + */ + private function normalizeModules(array $modules): array + { + $normalized = []; + + foreach ($modules as $module) { + if (!is_string($module)) { + throw new \InvalidArgumentException('Maintenance module identifiers must be strings.'); + } + + $module = trim($module); + + if ($module === '' || str_contains($module, "\0")) { + throw new \InvalidArgumentException( + 'Maintenance module identifiers must be non-empty and contain no NUL bytes.', + ); + } + + $normalized[$module] = $module; + } + + return array_values($normalized); + } +} diff --git a/src/Maintenance/MaintenanceServiceInterface.php b/src/Maintenance/MaintenanceServiceInterface.php new file mode 100644 index 0000000..1aa095d --- /dev/null +++ b/src/Maintenance/MaintenanceServiceInterface.php @@ -0,0 +1,54 @@ + $modules Explicit module targets or configuration defaults. + * @param bool $all Whether every policy-approved translation should be installed. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function initialize(array $modules = [], bool $all = false): MaintenanceResult; + + /** + * Refreshes remote modules when enabled and rebuilds their snapshots. + * + * @param list $modules Explicit module targets or configuration defaults. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function refresh(array $modules = []): MaintenanceResult; + + /** + * Refreshes only when the durable interval policy is due. + * + * @param list $modules Explicit module targets or configuration defaults. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function refreshIfDue(array $modules = []): MaintenanceResult; + + /** + * Returns current maintenance, capability, and installed-module status. + * + * @return MaintenanceStatus + * @since 0.3.0 + */ + public function status(): MaintenanceStatus; +} diff --git a/src/Maintenance/MaintenanceState.php b/src/Maintenance/MaintenanceState.php new file mode 100644 index 0000000..34cbb29 --- /dev/null +++ b/src/Maintenance/MaintenanceState.php @@ -0,0 +1,266 @@ + $state Serialized state. + * + * @return self + * @since 0.3.0 + */ + public static function fromArray(array $state): self + { + if ( + ($state['format'] ?? null) !== self::FORMAT + || !is_int($state['consecutive_failures'] ?? null) + ) { + throw new \UnexpectedValueException('Maintenance state has an unsupported structure.'); + } + + $lastError = $state['last_error'] ?? null; + + if ($lastError !== null && !is_string($lastError)) { + throw new \UnexpectedValueException('Maintenance state last_error must be a string or null.'); + } + + return new self( + self::date($state['last_attempt_at'] ?? null, 'last_attempt_at'), + self::date($state['last_success_at'] ?? null, 'last_success_at'), + self::date($state['last_failure_at'] ?? null, 'last_failure_at'), + $lastError, + $state['consecutive_failures'], + ); + } + + /** + * Returns state after a completely successful maintenance run. + * + * @param \DateTimeImmutable $completedAt Completion time. + * + * @return self + * @since 0.3.0 + */ + public function succeededAt(\DateTimeImmutable $completedAt): self + { + return new self($completedAt, $completedAt, $this->lastFailureAt, null, 0); + } + + /** + * Returns state after a failed or partially failed maintenance run. + * + * @param \DateTimeImmutable $completedAt Completion time. + * @param string $error Concise failure summary. + * + * @return self + * @since 0.3.0 + */ + public function failedAt(\DateTimeImmutable $completedAt, string $error): self + { + $error = trim($error); + + if ($error === '') { + throw new \InvalidArgumentException('A failed maintenance run requires an error summary.'); + } + + return new self( + $completedAt, + $this->lastSuccessAt, + $completedAt, + $error, + $this->consecutiveFailures + 1, + ); + } + + /** + * Reports whether refresh is due at a given time. + * + * @param \DateTimeImmutable $now Current time. + * @param \DateInterval $interval Required interval after the last success. + * + * @return bool + * @since 0.3.0 + */ + public function isDue(\DateTimeImmutable $now, \DateInterval $interval): bool + { + $next = $this->nextDueAt($interval); + + return $next === null || $next <= $now; + } + + /** + * Returns the next due time or null when refresh has never succeeded. + * + * @param \DateInterval $interval Required interval after the last success. + * + * @return \DateTimeImmutable|null + * @since 0.3.0 + */ + public function nextDueAt(\DateInterval $interval): ?\DateTimeImmutable + { + return $this->lastSuccessAt?->add($interval); + } + + /** + * Returns the last maintenance attempt. + * + * @return \DateTimeImmutable|null + * @since 0.3.0 + */ + public function lastAttemptAt(): ?\DateTimeImmutable + { + return $this->lastAttemptAt; + } + + /** + * Returns the last completely successful maintenance time. + * + * @return \DateTimeImmutable|null + * @since 0.3.0 + */ + public function lastSuccessAt(): ?\DateTimeImmutable + { + return $this->lastSuccessAt; + } + + /** + * Returns the last failed maintenance time. + * + * @return \DateTimeImmutable|null + * @since 0.3.0 + */ + public function lastFailureAt(): ?\DateTimeImmutable + { + return $this->lastFailureAt; + } + + /** + * Returns the last failure summary. + * + * @return string|null + * @since 0.3.0 + */ + public function lastError(): ?string + { + return $this->lastError; + } + + /** + * Returns the number of consecutive failures since the last success. + * + * @return int + * @since 0.3.0 + */ + public function consecutiveFailures(): int + { + return $this->consecutiveFailures; + } + + /** + * Returns a serialization-safe state map. + * + * @return array{ + * format: string, + * last_attempt_at: string|null, + * last_success_at: string|null, + * last_failure_at: string|null, + * last_error: string|null, + * consecutive_failures: int + * } + * @since 0.3.0 + */ + public function toArray(): array + { + return [ + 'format' => self::FORMAT, + 'last_attempt_at' => $this->lastAttemptAt?->format(DATE_ATOM), + 'last_success_at' => $this->lastSuccessAt?->format(DATE_ATOM), + 'last_failure_at' => $this->lastFailureAt?->format(DATE_ATOM), + 'last_error' => $this->lastError, + 'consecutive_failures' => $this->consecutiveFailures, + ]; + } + + /** + * Parses an optional serialized timestamp. + * + * @param mixed $value Candidate timestamp. + * @param string $field Field name. + * + * @return \DateTimeImmutable|null + * @since 0.3.0 + */ + private static function date(mixed $value, string $field): ?\DateTimeImmutable + { + if ($value === null) { + return null; + } + + if (!is_string($value) || trim($value) === '') { + throw new \UnexpectedValueException(sprintf('Maintenance state %s is invalid.', $field)); + } + + try { + return new \DateTimeImmutable($value); + } catch (\Exception $exception) { + throw new \UnexpectedValueException( + sprintf('Maintenance state %s is not a valid timestamp.', $field), + 0, + $exception, + ); + } + } +} diff --git a/src/Maintenance/MaintenanceStateStoreInterface.php b/src/Maintenance/MaintenanceStateStoreInterface.php new file mode 100644 index 0000000..639239d --- /dev/null +++ b/src/Maintenance/MaintenanceStateStoreInterface.php @@ -0,0 +1,33 @@ + $configuredModules Configured module targets. + * @param list $installedModules Installed Bible module identifiers. + * + * @since 0.3.0 + */ + public function __construct( + private \DateTimeImmutable $checkedAt, + private bool $due, + private ?\DateTimeImmutable $nextDueAt, + private MaintenanceState $state, + private ProvisioningCapabilities $capabilities, + private bool $provisioningEnabled, + private array $configuredModules, + private array $installedModules, + ) { + } + + /** + * Reports whether refresh is currently due. + * + * @return bool + * @since 0.3.0 + */ + public function due(): bool + { + return $this->due; + } + + /** + * Returns durable maintenance state. + * + * @return MaintenanceState + * @since 0.3.0 + */ + public function state(): MaintenanceState + { + return $this->state; + } + + /** + * Returns a serialization-safe operational status. + * + * @return array + * @since 0.3.0 + */ + public function toArray(): array + { + return [ + 'checked_at' => $this->checkedAt->format(DATE_ATOM), + 'due' => $this->due, + 'next_due_at' => $this->nextDueAt?->format(DATE_ATOM), + 'provisioning_enabled' => $this->provisioningEnabled, + 'capabilities' => $this->capabilities->toArray(), + 'configured_modules' => $this->configuredModules, + 'installed_modules' => $this->installedModules, + 'state' => $this->state->toArray(), + ]; + } +} diff --git a/src/Provisioning/AbiV1ModuleProvisioner.php b/src/Provisioning/AbiV1ModuleProvisioner.php new file mode 100644 index 0000000..a9777d4 --- /dev/null +++ b/src/Provisioning/AbiV1ModuleProvisioner.php @@ -0,0 +1,92 @@ + $modules Exact module identifiers. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function installTranslations(array $modules): ProvisioningResult + { + throw $this->unavailable(); + } + + /** + * Rejects all-module installation until a safe native API exists. + * + * @return ProvisioningResult + * @since 0.1.0 + */ + public function installAllTranslations(): ProvisioningResult + { + throw $this->unavailable(); + } + + /** + * Rejects remote refresh until a safe native API exists. + * + * @param list $modules Exact module identifiers or an empty list. + * + * @return ProvisioningResult + * @since 0.1.0 + */ + public function refreshTranslations(array $modules = []): ProvisioningResult + { + throw $this->unavailable(); + } + + /** + * Rejects removal until a safe native API exists. + * + * @param string $module Exact module identifier. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function removeTranslation(string $module): ProvisioningResult + { + throw $this->unavailable(); + } + + /** + * Creates the stable capability error. + * + * @return ProvisioningUnavailableException + * @since 0.1.0 + */ + private function unavailable(): ProvisioningUnavailableException + { + return new ProvisioningUnavailableException( + 'getBibleSword ABI v1 cannot install or refresh modules safely. ' + . 'Use preinstalled SWORD modules until the native provisioning API is released.', + ); + } +} diff --git a/src/Provisioning/ModuleProvisionerInterface.php b/src/Provisioning/ModuleProvisionerInterface.php new file mode 100644 index 0000000..b65e764 --- /dev/null +++ b/src/Provisioning/ModuleProvisionerInterface.php @@ -0,0 +1,61 @@ + $modules Exact module identifiers. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function installTranslations(array $modules): ProvisioningResult; + + /** + * Installs every policy-approved Bible translation into a staged root. + * + * @return ProvisioningResult + * @since 0.1.0 + */ + public function installAllTranslations(): ProvisioningResult; + + /** + * Refreshes every installed Bible translation through the remote repository. + * + * @param list $modules Exact module identifiers or an empty list. + * + * @return ProvisioningResult + * @since 0.1.0 + */ + public function refreshTranslations(array $modules = []): ProvisioningResult; + + /** + * Removes one installed Bible translation. + * + * @param string $module Exact module identifier. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function removeTranslation(string $module): ProvisioningResult; +} diff --git a/src/Provisioning/ModuleProvisioningResult.php b/src/Provisioning/ModuleProvisioningResult.php new file mode 100644 index 0000000..be8d9ab --- /dev/null +++ b/src/Provisioning/ModuleProvisioningResult.php @@ -0,0 +1,177 @@ + $details Machine-readable details. + * + * @since 0.2.0 + */ + public function __construct( + private string $module, + private string $action, + private string $status, + private string $message = '', + private array $details = [], + ) { + if (trim($module) === '') { + throw new \InvalidArgumentException('A module provisioning result requires a module identifier.'); + } + + if (!in_array($action, [self::ACTION_INSTALL, self::ACTION_REFRESH, self::ACTION_REMOVE], true)) { + throw new \InvalidArgumentException(sprintf('Unsupported module action "%s".', $action)); + } + + if (!in_array($status, [self::STATUS_CHANGED, self::STATUS_SKIPPED, self::STATUS_FAILED], true)) { + throw new \InvalidArgumentException(sprintf('Unsupported module status "%s".', $status)); + } + } + + /** + * Returns the exact module identifier. + * + * @return string + * @since 0.2.0 + */ + public function module(): string + { + return $this->module; + } + + /** + * Returns the requested action. + * + * @return string + * @since 0.2.0 + */ + public function action(): string + { + return $this->action; + } + + /** + * Returns the final status. + * + * @return string + * @since 0.2.0 + */ + public function status(): string + { + return $this->status; + } + + /** + * Returns the backend diagnostic. + * + * @return string + * @since 0.2.0 + */ + public function message(): string + { + return $this->message; + } + + /** + * Returns machine-readable backend details. + * + * @return array + * @since 0.2.0 + */ + public function details(): array + { + return $this->details; + } + + /** + * Reports whether this module failed. + * + * @return bool + * @since 0.2.0 + */ + public function failed(): bool + { + return $this->status === self::STATUS_FAILED; + } + + /** + * Returns a serialization-safe outcome map. + * + * @return array{ + * module: string, + * action: string, + * status: string, + * message: string, + * details: array + * } + * @since 0.2.0 + */ + public function toArray(): array + { + return [ + 'module' => $this->module, + 'action' => $this->action, + 'status' => $this->status, + 'message' => $this->message, + 'details' => $this->details, + ]; + } +} diff --git a/src/Provisioning/ProvisioningCapabilities.php b/src/Provisioning/ProvisioningCapabilities.php new file mode 100644 index 0000000..1f526c5 --- /dev/null +++ b/src/Provisioning/ProvisioningCapabilities.php @@ -0,0 +1,160 @@ +backend; + } + + /** + * Returns the stable backend contract identifier. + * + * @return string + * @since 0.2.0 + */ + public function contract(): string + { + return $this->contract; + } + + /** + * Reports selected-module installation support. + * + * @return bool + * @since 0.2.0 + */ + public function canInstallSelected(): bool + { + return $this->installSelected; + } + + /** + * Reports all-module installation support. + * + * @return bool + * @since 0.2.0 + */ + public function canInstallAll(): bool + { + return $this->installAll; + } + + /** + * Reports remote refresh support. + * + * @return bool + * @since 0.2.0 + */ + public function canRefresh(): bool + { + return $this->refresh; + } + + /** + * Reports module removal support. + * + * @return bool + * @since 0.2.0 + */ + public function canRemove(): bool + { + return $this->remove; + } + + /** + * Reports whether any mutating provisioning operation is available. + * + * @return bool + * @since 0.2.0 + */ + public function isAvailable(): bool + { + return $this->installSelected || $this->installAll || $this->refresh || $this->remove; + } + + /** + * Returns a serialization-safe capability map. + * + * @return array{ + * backend: string, + * contract: string, + * install_selected: bool, + * install_all: bool, + * refresh: bool, + * remove: bool + * } + * @since 0.2.0 + */ + public function toArray(): array + { + return [ + 'backend' => $this->backend, + 'contract' => $this->contract, + 'install_selected' => $this->installSelected, + 'install_all' => $this->installAll, + 'refresh' => $this->refresh, + 'remove' => $this->remove, + ]; + } +} diff --git a/src/Provisioning/ProvisioningCoordinator.php b/src/Provisioning/ProvisioningCoordinator.php new file mode 100644 index 0000000..7d1eb18 --- /dev/null +++ b/src/Provisioning/ProvisioningCoordinator.php @@ -0,0 +1,209 @@ +provisioner->capabilities(); + } + + /** + * Installs selected Bible translations. + * + * @param list $modules Exact module identifiers. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function install(array $modules): ProvisioningResult + { + $modules = $this->normalizeModules($modules, false); + + return $this->execute( + 'install-selected', + $modules, + fn (): ProvisioningResult => $this->provisioner->installTranslations($modules), + ); + } + + /** + * Installs all policy-approved Bible translations. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function installAll(): ProvisioningResult + { + return $this->execute( + 'install-all', + [], + fn (): ProvisioningResult => $this->provisioner->installAllTranslations(), + ); + } + + /** + * Refreshes selected or all installed Bible translations. + * + * @param list $modules Exact identifiers, or an empty list for every installed translation. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function refresh(array $modules = []): ProvisioningResult + { + $modules = $this->normalizeModules($modules, true); + + return $this->execute( + 'refresh', + $modules, + fn (): ProvisioningResult => $this->provisioner->refreshTranslations($modules), + ); + } + + /** + * Removes one installed Bible translation. + * + * @param string $module Exact module identifier. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function remove(string $module): ProvisioningResult + { + $modules = $this->normalizeModules([$module], false); + + return $this->execute( + 'remove', + $modules, + fn (): ProvisioningResult => $this->provisioner->removeTranslation($modules[0]), + ); + } + + /** + * Runs one backend mutation under the exclusive application lock. + * + * @param string $operation Stable operation name. + * @param list $modules Requested module identifiers. + * @param callable(): ProvisioningResult $callback Backend operation. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + private function execute(string $operation, array $modules, callable $callback): ProvisioningResult + { + $this->dispatcher->dispatch( + EventName::PROVISIONING_STARTED, + new Event(EventName::PROVISIONING_STARTED, [ + 'operation' => $operation, + 'modules' => $modules, + 'capabilities' => $this->capabilities(), + ]), + ); + + try { + $result = $this->lock->write($callback); + + $this->catalog->clear(); + $this->snapshots->clear(); + $this->dispatcher->dispatch( + EventName::PROVISIONING_COMPLETED, + new Event(EventName::PROVISIONING_COMPLETED, [ + 'operation' => $operation, + 'modules' => $modules, + 'result' => $result, + ]), + ); + + return $result; + } catch (\Throwable $exception) { + $this->dispatcher->dispatch( + EventName::PROVISIONING_FAILED, + new Event(EventName::PROVISIONING_FAILED, [ + 'operation' => $operation, + 'modules' => $modules, + 'exception' => $exception, + ]), + ); + + throw $exception; + } + } + + /** + * Validates, trims, and de-duplicates module identifiers. + * + * @param array $modules Candidate module identifiers. + * @param bool $allowEmpty Whether an empty list means all installed translations. + * + * @return list + * @since 0.2.0 + */ + private function normalizeModules(array $modules, bool $allowEmpty): array + { + $normalized = []; + + foreach ($modules as $module) { + if (!is_string($module)) { + throw new \InvalidArgumentException('Module identifiers must be strings.'); + } + + $module = trim($module); + + if ($module === '' || str_contains($module, "\0")) { + throw new \InvalidArgumentException('Module identifiers must be non-empty strings without NUL bytes.'); + } + + $normalized[$module] = $module; + } + + if (!$allowEmpty && $normalized === []) { + throw new \InvalidArgumentException('At least one module identifier is required.'); + } + + return array_values($normalized); + } +} diff --git a/src/Provisioning/ProvisioningCoordinatorInterface.php b/src/Provisioning/ProvisioningCoordinatorInterface.php new file mode 100644 index 0000000..24c5043 --- /dev/null +++ b/src/Provisioning/ProvisioningCoordinatorInterface.php @@ -0,0 +1,61 @@ + $modules Exact module identifiers. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function install(array $modules): ProvisioningResult; + + /** + * Installs all policy-approved Bible translations. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function installAll(): ProvisioningResult; + + /** + * Refreshes selected or all installed Bible translations. + * + * @param list $modules Exact identifiers, or an empty list for all installed translations. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function refresh(array $modules = []): ProvisioningResult; + + /** + * Removes one installed Bible translation. + * + * @param string $module Exact module identifier. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function remove(string $module): ProvisioningResult; +} diff --git a/src/Provisioning/ProvisioningResult.php b/src/Provisioning/ProvisioningResult.php new file mode 100644 index 0000000..29dd468 --- /dev/null +++ b/src/Provisioning/ProvisioningResult.php @@ -0,0 +1,226 @@ + + * @since 0.2.0 + */ + private array $modules; + + /** + * Creates a complete provisioning result. + * + * @param string $operation Backend operation name. + * @param array $modules Per-module outcomes. + * + * @since 0.2.0 + */ + public function __construct(string $operation, array $modules) + { + if (trim($operation) === '') { + throw new \InvalidArgumentException('A provisioning operation name is required.'); + } + + $validated = []; + + foreach ($modules as $module) { + if (!$module instanceof ModuleProvisioningResult) { + throw new \InvalidArgumentException('Provisioning results must contain module outcomes.'); + } + + $validated[] = $module; + } + + $this->operation = $operation; + $this->modules = $validated; + } + + /** + * Returns the backend operation name. + * + * @return string + * @since 0.2.0 + */ + public function operation(): string + { + return $this->operation; + } + + /** + * Returns every per-module outcome in backend order. + * + * @return list + * @since 0.2.0 + */ + public function modules(): array + { + return $this->modules; + } + + /** + * Returns installed modules. + * + * @return list + * @since 0.1.0 + */ + public function installed(): array + { + return $this->matching(ModuleProvisioningResult::ACTION_INSTALL, ModuleProvisioningResult::STATUS_CHANGED); + } + + /** + * Returns updated modules. + * + * @return list + * @since 0.1.0 + */ + public function updated(): array + { + return $this->matching(ModuleProvisioningResult::ACTION_REFRESH, ModuleProvisioningResult::STATUS_CHANGED); + } + + /** + * Returns skipped modules. + * + * @return list + * @since 0.1.0 + */ + public function skipped(): array + { + $modules = []; + + foreach ($this->modules as $module) { + if ($module->status() === ModuleProvisioningResult::STATUS_SKIPPED) { + $modules[] = $module->module(); + } + } + + return $modules; + } + + /** + * Returns removed module identifiers. + * + * @return list + * @since 0.2.0 + */ + public function removed(): array + { + return $this->matching(ModuleProvisioningResult::ACTION_REMOVE, ModuleProvisioningResult::STATUS_CHANGED); + } + + /** + * Returns failed module identifiers. + * + * @return list + * @since 0.2.0 + */ + public function failed(): array + { + $modules = []; + + foreach ($this->modules as $module) { + if ($module->failed()) { + $modules[] = $module->module(); + } + } + + return $modules; + } + + /** + * Reports whether every module operation completed without failure. + * + * @return bool + * @since 0.2.0 + */ + public function succeeded(): bool + { + return $this->failed() === []; + } + + /** + * Reports whether at least one module changed. + * + * @return bool + * @since 0.2.0 + */ + public function changed(): bool + { + foreach ($this->modules as $module) { + if ($module->status() === ModuleProvisioningResult::STATUS_CHANGED) { + return true; + } + } + + return false; + } + + /** + * Returns a serialization-safe result map. + * + * @return array{ + * operation: string, + * succeeded: bool, + * changed: bool, + * modules: list> + * } + * @since 0.2.0 + */ + public function toArray(): array + { + return [ + 'operation' => $this->operation, + 'succeeded' => $this->succeeded(), + 'changed' => $this->changed(), + 'modules' => array_map( + static fn (ModuleProvisioningResult $module): array => $module->toArray(), + $this->modules, + ), + ]; + } + + /** + * Returns module identifiers matching an action and status. + * + * @param string $action Action filter. + * @param string $status Status filter. + * + * @return list + * @since 0.2.0 + */ + private function matching(string $action, string $status): array + { + $modules = []; + + foreach ($this->modules as $module) { + if ($module->action() === $action && $module->status() === $status) { + $modules[] = $module->module(); + } + } + + return $modules; + } +} diff --git a/src/Service/Scripture.php b/src/Service/Scripture.php new file mode 100644 index 0000000..1ce8923 --- /dev/null +++ b/src/Service/Scripture.php @@ -0,0 +1,297 @@ + + * @since 0.1.0 + */ + private array $translations = []; + + /** + * Creates the Scripture service. + * + * @param ModuleCatalogInterface $catalog Installed module catalog. + * @param SnapshotManagerInterface $snapshots Snapshot lifecycle. + * @param ProvisioningCoordinatorInterface $provisioning Module lifecycle. + * @param MaintenanceServiceInterface $maintenance Automated maintenance lifecycle. + * + * @since 0.1.0 + */ + public function __construct( + private ModuleCatalogInterface $catalog, + private SnapshotManagerInterface $snapshots, + private ProvisioningCoordinatorInterface $provisioning, + private MaintenanceServiceInterface $maintenance, + ) { + } + + /** + * Installs missing configured modules when supported and warms snapshots. + * + * @param list $modules Explicit module targets or configuration defaults. + * @param bool $all Whether every policy-approved translation should be installed. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function initialize(array $modules = [], bool $all = false): MaintenanceResult + { + $result = $this->maintenance->initialize($modules, $all); + $this->translations = []; + + return $result; + } + + /** + * Refreshes remote modules when enabled and rebuilds snapshots. + * + * @param list $modules Explicit module targets or configuration defaults. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function refresh(array $modules = []): MaintenanceResult + { + $result = $this->maintenance->refresh($modules); + $this->translations = []; + + return $result; + } + + /** + * Refreshes only after the configured durable interval has elapsed. + * + * @param list $modules Explicit module targets or configuration defaults. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function refreshIfDue(array $modules = []): MaintenanceResult + { + $result = $this->maintenance->refreshIfDue($modules); + + if ($result->due()) { + $this->translations = []; + } + + return $result; + } + + /** + * Returns current maintenance and native capability status. + * + * @return MaintenanceStatus + * @since 0.3.0 + */ + public function maintenanceStatus(): MaintenanceStatus + { + return $this->maintenance->status(); + } + + /** + * Returns installed Bible translation metadata. + * + * @return list<\GetBible\Scripture\Domain\TranslationMetadata> + * @since 0.1.0 + */ + public function translations(): array + { + return $this->catalog->translations(); + } + + /** + * Opens one installed translation. + * + * @param string $module Exact native module identifier. + * + * @return Translation + * @since 0.1.0 + */ + public function translation(string $module): Translation + { + return $this->translations[$module] ??= new Translation($module, $this->snapshots->get($module)); + } + + /** + * Returns one verse. + * + * @param string $module Exact native module identifier. + * @param string $book Book name or abbreviation. + * @param int $chapter Chapter number. + * @param int $verse Verse number. + * @param int $suffix SWORD suffix byte. + * + * @return Verse + * @since 0.1.0 + */ + public function verse( + string $module, + string $book, + int $chapter, + int $verse, + int $suffix = 0, + ): Verse { + return $this->translation($module)->book($book)->chapter($chapter)->verse($verse, $suffix); + } + + /** + * Returns an inclusive verse range. + * + * @param string $module Exact native module identifier. + * @param string $book Book name or abbreviation. + * @param int $chapter Chapter number. + * @param int $start First verse. + * @param int $end Last verse. + * + * @return list + * @since 0.1.0 + */ + public function verses( + string $module, + string $book, + int $chapter, + int $start, + int $end, + ): array { + return $this->translation($module)->verses($book, $chapter, $start, $end); + } + + /** + * Forces an installed-module snapshot refresh. + * + * @param string $module Exact native module identifier. + * + * @return Translation + * @since 0.1.0 + */ + public function refreshTranslation(string $module): Translation + { + $translation = new Translation($module, $this->snapshots->refresh($module)); + $this->translations[$module] = $translation; + + return $translation; + } + + /** + * Reports native remote provisioning availability. + * + * @return bool + * @since 0.1.0 + */ + public function canProvisionModules(): bool + { + return $this->provisioning->capabilities()->isAvailable(); + } + + /** + * Returns exact native provisioning capabilities. + * + * @return ProvisioningCapabilities + * @since 0.2.0 + */ + public function provisioningCapabilities(): ProvisioningCapabilities + { + return $this->provisioning->capabilities(); + } + + /** + * Installs selected policy-approved translations when supported. + * + * @param list $modules Exact module identifiers. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function installTranslations(array $modules): ProvisioningResult + { + $result = $this->provisioning->install($modules); + $this->translations = []; + + return $result; + } + + /** + * Installs all policy-approved translations when supported. + * + * @return ProvisioningResult + * @since 0.1.0 + */ + public function installAllTranslations(): ProvisioningResult + { + $result = $this->provisioning->installAll(); + $this->translations = []; + + return $result; + } + + /** + * Refreshes remote module files when supported. + * + * @return ProvisioningResult + * @since 0.1.0 + */ + public function refreshModules(): ProvisioningResult + { + $result = $this->provisioning->refresh(); + $this->translations = []; + + return $result; + } + + /** + * Refreshes selected remote module files when supported. + * + * @param list $modules Exact module identifiers. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function refreshSelectedModules(array $modules): ProvisioningResult + { + $result = $this->provisioning->refresh($modules); + $this->translations = []; + + return $result; + } + + /** + * Removes one installed Bible translation when supported. + * + * @param string $module Exact module identifier. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function removeTranslation(string $module): ProvisioningResult + { + $result = $this->provisioning->remove($module); + unset($this->translations[$module]); + + return $result; + } +} diff --git a/src/Service/ScriptureInterface.php b/src/Service/ScriptureInterface.php new file mode 100644 index 0000000..a691a12 --- /dev/null +++ b/src/Service/ScriptureInterface.php @@ -0,0 +1,192 @@ + $modules Explicit module targets or configuration defaults. + * @param bool $all Whether every policy-approved translation should be installed. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function initialize(array $modules = [], bool $all = false): MaintenanceResult; + + /** + * Refreshes remote modules when enabled and rebuilds snapshots. + * + * @param list $modules Explicit module targets or configuration defaults. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function refresh(array $modules = []): MaintenanceResult; + + /** + * Refreshes only after the configured durable interval has elapsed. + * + * @param list $modules Explicit module targets or configuration defaults. + * + * @return MaintenanceResult + * @since 0.3.0 + */ + public function refreshIfDue(array $modules = []): MaintenanceResult; + + /** + * Returns current maintenance and native capability status. + * + * @return MaintenanceStatus + * @since 0.3.0 + */ + public function maintenanceStatus(): MaintenanceStatus; + + /** + * Returns installed Bible translation metadata. + * + * @return list + * @since 0.1.0 + */ + public function translations(): array; + + /** + * Opens one installed translation, warming it when necessary. + * + * @param string $module Exact native module identifier. + * + * @return Translation + * @since 0.1.0 + */ + public function translation(string $module): Translation; + + /** + * Returns one verse through a convenience query. + * + * @param string $module Exact native module identifier. + * @param string $book Book name or abbreviation. + * @param int $chapter Chapter number. + * @param int $verse Verse number. + * @param int $suffix SWORD suffix byte. + * + * @return Verse + * @since 0.1.0 + */ + public function verse( + string $module, + string $book, + int $chapter, + int $verse, + int $suffix = 0, + ): Verse; + + /** + * Returns an inclusive verse range through a convenience query. + * + * @param string $module Exact native module identifier. + * @param string $book Book name or abbreviation. + * @param int $chapter Chapter number. + * @param int $start First verse. + * @param int $end Last verse. + * + * @return list + * @since 0.1.0 + */ + public function verses( + string $module, + string $book, + int $chapter, + int $start, + int $end, + ): array; + + /** + * Forces a validated snapshot refresh from the installed module. + * + * @param string $module Exact native module identifier. + * + * @return Translation + * @since 0.1.0 + */ + public function refreshTranslation(string $module): Translation; + + /** + * Reports whether remote module provisioning is available. + * + * @return bool + * @since 0.1.0 + */ + public function canProvisionModules(): bool; + + /** + * Returns exact native provisioning capabilities. + * + * @return ProvisioningCapabilities + * @since 0.2.0 + */ + public function provisioningCapabilities(): ProvisioningCapabilities; + + /** + * Installs selected policy-approved Bible modules when supported. + * + * @param list $modules Exact module identifiers. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function installTranslations(array $modules): ProvisioningResult; + + /** + * Installs every policy-approved Bible module when supported. + * + * @return ProvisioningResult + * @since 0.1.0 + */ + public function installAllTranslations(): ProvisioningResult; + + /** + * Refreshes installed remote module files when supported. + * + * @return ProvisioningResult + * @since 0.1.0 + */ + public function refreshModules(): ProvisioningResult; + + /** + * Refreshes selected remote module files when supported. + * + * @param list $modules Exact module identifiers. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function refreshSelectedModules(array $modules): ProvisioningResult; + + /** + * Removes one installed Bible module when supported. + * + * @param string $module Exact module identifier. + * + * @return ProvisioningResult + * @since 0.2.0 + */ + public function removeTranslation(string $module): ProvisioningResult; +} diff --git a/src/Snapshot/SnapshotIndex.php b/src/Snapshot/SnapshotIndex.php new file mode 100644 index 0000000..7e9e9f1 --- /dev/null +++ b/src/Snapshot/SnapshotIndex.php @@ -0,0 +1,531 @@ + $index Decoded index. + * @param \DateTimeImmutable $activatedAt Activation time. + * @param \DateTimeImmutable $expiresAt Freshness deadline. + * + * @since 0.1.0 + */ + private function __construct( + private string $generationPath, + private array $index, + private \DateTimeImmutable $activatedAt, + private \DateTimeImmutable $expiresAt, + ) { + } + + /** + * Opens and minimally verifies one immutable generation. + * + * @param string $generationPath Generation directory. + * @param \DateTimeImmutable $activatedAt Activation time. + * @param \DateTimeImmutable $expiresAt Freshness deadline. + * + * @return self + * @since 0.1.0 + */ + public static function open( + string $generationPath, + \DateTimeImmutable $activatedAt, + \DateTimeImmutable $expiresAt, + ): self { + $indexPath = $generationPath . '/index.json'; + $modulePath = $generationPath . '/module.ndjson'; + $json = file_get_contents($indexPath); + + if ($json === false || !is_file($modulePath)) { + throw new ContractException(sprintf('Snapshot generation "%s" is incomplete.', $generationPath)); + } + + try { + $index = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ContractException('Snapshot index JSON is invalid.', 0, $exception); + } + + $index = StructuredData::object($index, 'Snapshot index'); + + if ( + ($index['format'] ?? null) !== 'getbible.scripture.snapshot/v1' + || !is_string($index['stream_sha256'] ?? null) + || preg_match('/^[0-9a-f]{64}$/D', $index['stream_sha256']) !== 1 + ) { + throw new ContractException('Snapshot index structure is invalid.'); + } + + StructuredData::object($index['module'] ?? null, 'Snapshot module metadata'); + StructuredData::list($index['config_entries'] ?? null, 'Snapshot configuration entries'); + StructuredData::list($index['introductions'] ?? null, 'Snapshot introductions'); + StructuredData::object($index['books'] ?? null, 'Snapshot books'); + + return new self($generationPath, $index, $activatedAt, $expiresAt); + } + + /** + * Closes the module stream when the snapshot reader is released. + * + * @since 0.1.0 + */ + public function __destruct() + { + if (is_resource($this->stream)) { + fclose($this->stream); + } + } + + /** + * Returns the validated translation metadata. + * + * @return TranslationMetadata + * @since 0.1.0 + */ + public function metadata(): TranslationMetadata + { + return TranslationMetadata::fromRecord( + StructuredData::object($this->index['module'] ?? null, 'Snapshot module metadata'), + ); + } + + /** + * Returns all ordered interpreted configuration entries. + * + * @return list + * @since 0.1.0 + */ + public function configEntries(): array + { + $entries = []; + + foreach ( + StructuredData::list( + $this->index['config_entries'] ?? null, + 'Snapshot configuration entries', + ) as $index => $record + ) { + $entries[] = ConfigEntry::fromRecord( + StructuredData::object($record, sprintf('Snapshot configuration entry %d', $index)), + ); + } + + return $entries; + } + + /** + * Returns configuration entries with an exact byte name. + * + * @param string $name Exact configuration name. + * + * @return list + * @since 0.1.0 + */ + public function configEntriesNamed(string $name): array + { + return array_values(array_filter( + $this->configEntries(), + static fn (ConfigEntry $entry): bool => $entry->name()->bytes() === $name, + )); + } + + /** + * Returns ordered compound book keys. + * + * @return list + * @since 0.1.0 + */ + public function bookKeys(): array + { + return array_keys(StructuredData::object($this->index['books'] ?? null, 'Snapshot books')); + } + + /** + * Returns verified book metadata used by lazy Book objects. + * + * @param string $bookKey Compound testament/book key. + * + * @return array{testament: int, position: int, name: ByteValue, abbreviation: ByteValue, versification: ByteValue} + * @since 0.1.0 + */ + public function bookMetadata(string $bookKey): array + { + $book = $this->bookData($bookKey); + + if ( + !is_int($book['testament'] ?? null) + || !is_int($book['position'] ?? null) + || !is_array($book['name'] ?? null) + || !is_array($book['abbreviation'] ?? null) + || !is_array($book['versification'] ?? null) + ) { + throw new ContractException(sprintf('Snapshot book "%s" metadata is invalid.', $bookKey)); + } + + return [ + 'testament' => $book['testament'], + 'position' => $book['position'], + 'name' => ByteValue::fromArray($book['name'], "books.$bookKey.name"), + 'abbreviation' => ByteValue::fromArray($book['abbreviation'], "books.$bookKey.abbreviation"), + 'versification' => ByteValue::fromArray($book['versification'], "books.$bookKey.versification"), + ]; + } + + /** + * Returns ordered chapter numbers for a book. + * + * @param string $bookKey Compound testament/book key. + * + * @return list + * @since 0.1.0 + */ + public function chapterNumbers(string $bookKey): array + { + $book = $this->bookData($bookKey); + $chapters = StructuredData::map( + $book['chapters'] ?? null, + sprintf('Snapshot book "%s" chapters', $bookKey), + ); + + return array_map('intval', array_keys($chapters)); + } + + /** + * Returns ordered unique verse numbers for a chapter. + * + * @param string $bookKey Compound testament/book key. + * @param int $chapter Chapter number. + * + * @return list + * @since 0.1.0 + */ + public function verseNumbers(string $bookKey, int $chapter): array + { + $chapterData = $this->chapterData($bookKey, $chapter); + $verses = StructuredData::object($chapterData['verses'] ?? null, 'Snapshot chapter verses'); + + $numbers = []; + + foreach (array_keys($verses) as $key) { + $parts = explode(':', $key, 2); + $numbers[] = (int) $parts[0]; + } + + $numbers = array_values(array_unique($numbers)); + sort($numbers, SORT_NUMERIC); + + return $numbers; + } + + /** + * Hydrates one verse by exact coordinate. + * + * @param string $bookKey Compound testament/book key. + * @param int $chapter Chapter number. + * @param int $verse Verse number. + * @param int $suffix SWORD suffix byte. + * + * @return Verse + * @since 0.1.0 + */ + public function verse(string $bookKey, int $chapter, int $verse, int $suffix = 0): Verse + { + $chapterData = $this->chapterData($bookKey, $chapter); + $verseKey = $verse . ':' . $suffix; + $locations = StructuredData::object($chapterData['verses'] ?? null, 'Snapshot chapter verses'); + $location = $locations[$verseKey] ?? null; + + if (!is_array($location)) { + throw new ReferenceNotFoundException(sprintf( + 'Verse %s %d:%d suffix %d is not present.', + $bookKey, + $chapter, + $verse, + $suffix, + )); + } + + return Verse::fromRecord($this->readRecord($location)); + } + + /** + * Hydrates an inclusive ordered verse range, retaining suffix variants. + * + * @param string $bookKey Compound testament/book key. + * @param int $chapter Chapter number. + * @param int|null $start First verse, or null for the first available verse. + * @param int|null $end Last verse, or null for the last available verse. + * + * @return list + * @since 0.1.0 + */ + public function verses( + string $bookKey, + int $chapter, + ?int $start = null, + ?int $end = null, + ): array { + $chapterData = $this->chapterData($bookKey, $chapter); + $locations = StructuredData::object($chapterData['verses'] ?? null, 'Snapshot chapter verses'); + + $coordinates = []; + + foreach ($locations as $key => $location) { + if (!is_array($location)) { + throw new ContractException('Snapshot verse index is invalid.'); + } + + $parts = explode(':', $key, 2); + + if (count($parts) !== 2 || !ctype_digit($parts[0]) || !ctype_digit($parts[1])) { + throw new ContractException('Snapshot verse coordinate is invalid.'); + } + + $verse = (int) $parts[0]; + $suffix = (int) $parts[1]; + + if (($start !== null && $verse < $start) || ($end !== null && $verse > $end)) { + continue; + } + + $coordinates[] = ['verse' => $verse, 'suffix' => $suffix, 'location' => $location]; + } + + usort( + $coordinates, + static fn (array $left, array $right): int => [$left['verse'], $left['suffix']] + <=> [$right['verse'], $right['suffix']], + ); + + $verses = []; + + foreach ($coordinates as $coordinate) { + $verses[] = Verse::fromRecord($this->readRecord($coordinate['location'])); + } + + return $verses; + } + + /** + * Returns introductions attached to a book, chapter, or module. + * + * @param string|null $bookKey Optional compound book key. + * @param int|null $chapter Optional chapter number. + * + * @return list + * @since 0.1.0 + */ + public function introductions(?string $bookKey = null, ?int $chapter = null): array + { + if ($bookKey === null) { + $locations = StructuredData::list( + $this->index['introductions'] ?? null, + 'Snapshot module introductions', + ); + } elseif ($chapter === null) { + $locations = StructuredData::list( + $this->bookData($bookKey)['introductions'] ?? null, + 'Snapshot book introductions', + ); + } else { + $locations = StructuredData::list( + $this->chapterData($bookKey, $chapter)['introductions'] ?? null, + 'Snapshot chapter introductions', + ); + } + + $introductions = []; + + foreach ($locations as $location) { + if (!is_array($location)) { + throw new ContractException('Snapshot introduction location is invalid.'); + } + + $introductions[] = Introduction::fromRecord($this->readRecord($location)); + } + + return $introductions; + } + + /** + * Returns the raw validated native export path. + * + * @return string + * @since 0.1.0 + */ + public function rawExportPath(): string + { + return $this->generationPath . '/module.ndjson'; + } + + /** + * Returns the activation time. + * + * @return \DateTimeImmutable + * @since 0.1.0 + */ + public function activatedAt(): \DateTimeImmutable + { + return $this->activatedAt; + } + + /** + * Returns the freshness deadline. + * + * @return \DateTimeImmutable + * @since 0.1.0 + */ + public function expiresAt(): \DateTimeImmutable + { + return $this->expiresAt; + } + + /** + * Indicates whether the generation is stale at a supplied time. + * + * @param \DateTimeImmutable $now Current time. + * + * @return bool + * @since 0.1.0 + */ + public function isExpired(\DateTimeImmutable $now): bool + { + return $now >= $this->expiresAt; + } + + /** + * Returns one indexed book object. + * + * @param string $bookKey Compound testament/book key. + * + * @return array + * @since 0.1.0 + */ + private function bookData(string $bookKey): array + { + $books = StructuredData::object($this->index['books'] ?? null, 'Snapshot books'); + $book = $books[$bookKey] ?? null; + + if (!is_array($book)) { + throw new ReferenceNotFoundException(sprintf('Book "%s" is not present.', $bookKey)); + } + + return StructuredData::object($book, sprintf('Snapshot book "%s"', $bookKey)); + } + + /** + * Returns one indexed chapter object. + * + * @param string $bookKey Compound testament/book key. + * @param int $chapter Chapter number. + * + * @return array + * @since 0.1.0 + */ + private function chapterData(string $bookKey, int $chapter): array + { + $book = $this->bookData($bookKey); + $chapters = StructuredData::map( + $book['chapters'] ?? null, + sprintf('Snapshot book "%s" chapters', $bookKey), + ); + $chapterData = $chapters[(string) $chapter] ?? null; + + if (!is_array($chapterData)) { + throw new ReferenceNotFoundException(sprintf( + 'Chapter %d is not present in book "%s".', + $chapter, + $bookKey, + )); + } + + return StructuredData::object( + $chapterData, + sprintf('Snapshot book "%s" chapter %d', $bookKey, $chapter), + ); + } + + /** + * Reads one exact serialized entry record. + * + * @param array $location Indexed offset and length. + * + * @return array + * @since 0.1.0 + */ + private function readRecord(array $location): array + { + $location = StructuredData::object($location, 'Snapshot record location'); + $offset = $location['offset'] ?? null; + $length = $location['length'] ?? null; + + if (!is_int($offset) || $offset < 0 || !is_int($length) || $length < 2) { + throw new ContractException('Snapshot record location is invalid.'); + } + + if (!is_resource($this->stream)) { + $stream = fopen($this->rawExportPath(), 'rb'); + + if (!is_resource($stream)) { + throw new ContractException('Unable to open the snapshot module stream.'); + } + + $this->stream = $stream; + } + + if (fseek($this->stream, $offset) !== 0) { + throw new ContractException('Unable to seek to a snapshot record.'); + } + + $line = fread($this->stream, $length); + + if ($line === false || strlen($line) !== $length || !str_ends_with($line, "\n")) { + throw new ContractException('Unable to read the complete snapshot record.'); + } + + try { + $record = json_decode($line, true, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ContractException('Snapshot record JSON is invalid.', 0, $exception); + } + + $record = StructuredData::object($record, 'Snapshot entry record'); + + if (($record['type'] ?? null) !== 'entry') { + throw new ContractException('Snapshot location does not reference an entry record.'); + } + + return $record; + } +} diff --git a/src/Snapshot/SnapshotManagerInterface.php b/src/Snapshot/SnapshotManagerInterface.php new file mode 100644 index 0000000..42400bf --- /dev/null +++ b/src/Snapshot/SnapshotManagerInterface.php @@ -0,0 +1,43 @@ +, + * verses: array + * } + * @phpstan-type BookIndex array{ + * testament: int, + * position: int, + * name: array{base64: string, encoding: string, sha256: string, size: int, utf8?: string}, + * abbreviation: array{base64: string, encoding: string, sha256: string, size: int, utf8?: string}, + * versification: array{base64: string, encoding: string, sha256: string, size: int, utf8?: string}, + * introductions: list, + * chapters: array + * } + * + * @since 0.1.0 + */ +final class SnapshotRecordObserver implements RecordObserverInterface +{ + /** + * Validated module record. + * + * @var array|null + * @since 0.1.0 + */ + private ?array $module = null; + + /** + * Ordered configuration entry records. + * + * @var list> + * @since 0.1.0 + */ + private array $configEntries = []; + + /** + * Indexed books and chapters. + * + * @var array + * @since 0.1.0 + */ + private array $books = []; + + /** + * Module and testament introduction record locations. + * + * @var list + * @since 0.1.0 + */ + private array $introductions = []; + + /** + * Observes a validated record and retains only query index data. + * + * @param array $record Decoded record. + * @param int $offset Serialized line offset. + * @param int $length Serialized line length including LF. + * + * @return void + * @since 0.1.0 + */ + public function onRecord(array $record, int $offset, int $length): void + { + $type = $record['type']; + + if ($type === 'module') { + $metadata = TranslationMetadata::fromRecord($record); + + if (!$metadata->isBible()) { + throw new ContractException('Scripture snapshots accept only classification="bible".'); + } + + $this->module = $record; + + return; + } + + if ($type === 'config_entry') { + ConfigEntry::fromRecord($record); + $this->configEntries[] = $record; + + return; + } + + if ($type !== 'entry') { + return; + } + + if (!is_array($record['scope'] ?? null)) { + throw new ContractException('A Bible snapshot entry has no verse-key scope.'); + } + + $scope = VerseScope::fromArray($record['scope']); + $location = ['offset' => $offset, 'length' => $length]; + + if ($scope->book() === 0) { + $this->introductions[] = $location; + + return; + } + + $bookKey = $scope->testament() . ':' . $scope->book(); + + if (!isset($this->books[$bookKey])) { + $name = $scope->bookName(); + $abbreviation = $scope->bookAbbreviation(); + + if ($name === null || $abbreviation === null) { + throw new ContractException('A scoped book entry is missing its name or abbreviation.'); + } + + $this->books[$bookKey] = [ + 'testament' => $scope->testament(), + 'position' => $scope->book(), + 'name' => $name->toArray(), + 'abbreviation' => $abbreviation->toArray(), + 'versification' => $scope->versification()->toArray(), + 'introductions' => [], + 'chapters' => [], + ]; + } + + if ($scope->chapter() === 0) { + $this->books[$bookKey]['introductions'][] = $location; + + return; + } + + $chapterKey = (string) $scope->chapter(); + + if (!isset($this->books[$bookKey]['chapters'][$chapterKey])) { + $this->books[$bookKey]['chapters'][$chapterKey] = [ + 'number' => $scope->chapter(), + 'introductions' => [], + 'verses' => [], + ]; + } + + if (!$scope->isVerse()) { + $this->books[$bookKey]['chapters'][$chapterKey]['introductions'][] = $location; + + return; + } + + $verseKey = $scope->verse() . ':' . $scope->suffix(); + + if (isset($this->books[$bookKey]['chapters'][$chapterKey]['verses'][$verseKey])) { + throw new ContractException(sprintf( + 'Duplicate verse coordinate %s/%s/%s.', + $bookKey, + $chapterKey, + $verseKey, + )); + } + + $this->books[$bookKey]['chapters'][$chapterKey]['verses'][$verseKey] = $location; + } + + /** + * Creates the final serializable snapshot index. + * + * @param string $streamSha256 Verified native stream digest. + * @param \DateTimeImmutable $generatedAt Snapshot generation time. + * + * @return array + * @since 0.1.0 + */ + public function index(string $streamSha256, \DateTimeImmutable $generatedAt): array + { + if ($this->module === null) { + throw new ContractException('A Scripture snapshot requires one Bible module record.'); + } + + return [ + 'format' => 'getbible.scripture.snapshot/v1', + 'stream_sha256' => $streamSha256, + 'generated_at' => $generatedAt->format(DATE_ATOM), + 'module' => $this->module, + 'config_entries' => $this->configEntries, + 'introductions' => $this->introductions, + 'books' => $this->books, + ]; + } +} diff --git a/src/Snapshot/TranslationSnapshotManager.php b/src/Snapshot/TranslationSnapshotManager.php new file mode 100644 index 0000000..9ab6a93 --- /dev/null +++ b/src/Snapshot/TranslationSnapshotManager.php @@ -0,0 +1,436 @@ + + * @since 0.1.0 + */ + private array $snapshots = []; + + /** + * Creates the snapshot manager. + * + * @param Configuration $configuration Runtime configuration. + * @param ClockInterface $clock Refresh clock. + * @param ModuleCatalogInterface $catalog Installed module catalog. + * @param ModuleExtractorInterface $extractor Native stream adapter. + * @param ContractV1ValidatorInterface $validator Stream validator. + * @param DispatcherInterface $dispatcher Joomla event dispatcher. + * @param ModuleRootLockInterface $moduleRootLock SWORD root reader/writer lock. + * + * @since 0.1.0 + */ + public function __construct( + private Configuration $configuration, + private ClockInterface $clock, + private ModuleCatalogInterface $catalog, + private ModuleExtractorInterface $extractor, + private ContractV1ValidatorInterface $validator, + private DispatcherInterface $dispatcher, + private ModuleRootLockInterface $moduleRootLock, + ) { + } + + /** + * Opens a current fresh snapshot or warms a replacement. + * + * @param string $module Exact installed module identifier. + * + * @return SnapshotIndex + * @since 0.1.0 + */ + public function get(string $module): SnapshotIndex + { + $module = $this->validateModule($module); + $snapshot = $this->snapshots[$module] ?? $this->openCurrent($module); + + if ( + $snapshot !== null + && (!$this->configuration->autoRefresh() || !$snapshot->isExpired($this->clock->now())) + ) { + return $this->snapshots[$module] = $snapshot; + } + + return $this->warm($module, false); + } + + /** + * Forces a complete installed-module re-export and activation. + * + * @param string $module Exact installed module identifier. + * + * @return SnapshotIndex + * @since 0.1.0 + */ + public function refresh(string $module): SnapshotIndex + { + $module = $this->validateModule($module); + $this->dispatcher->dispatch( + EventName::REFRESH_STARTED, + new Event(EventName::REFRESH_STARTED, ['module' => $module]), + ); + + try { + $snapshot = $this->warm($module, true); + $this->dispatcher->dispatch( + EventName::REFRESH_COMPLETED, + new Event(EventName::REFRESH_COMPLETED, ['module' => $module, 'snapshot' => $snapshot]), + ); + + return $snapshot; + } catch (\Throwable $exception) { + $this->dispatcher->dispatch( + EventName::REFRESH_FAILED, + new Event(EventName::REFRESH_FAILED, ['module' => $module, 'exception' => $exception]), + ); + + throw $exception; + } + } + + /** + * Clears process-local open snapshots. + * + * @return void + * @since 0.1.0 + */ + public function clear(): void + { + $this->snapshots = []; + } + + /** + * Warms one module under its interprocess lock. + * + * @param string $module Exact installed module identifier. + * @param bool $force Whether an existing fresh snapshot must be replaced. + * + * @return SnapshotIndex + * @since 0.1.0 + */ + private function warm(string $module, bool $force): SnapshotIndex + { + $this->catalog->translation($module); + $moduleRoot = $this->moduleRoot($module); + + if (!Folder::create($moduleRoot . '/generations', 0750)) { + throw new \RuntimeException(sprintf('Unable to create snapshot root "%s".', $moduleRoot)); + } + + $lock = fopen($moduleRoot . '/warm.lock', 'c+b'); + + if (!is_resource($lock) || !flock($lock, LOCK_EX)) { + if (is_resource($lock)) { + fclose($lock); + } + + throw new \RuntimeException(sprintf('Unable to acquire the "%s" snapshot lock.', $module)); + } + + try { + if (!$force) { + $current = $this->openCurrent($module); + + if ( + $current !== null + && (!$this->configuration->autoRefresh() || !$current->isExpired($this->clock->now())) + ) { + return $this->snapshots[$module] = $current; + } + } + + $this->dispatcher->dispatch( + EventName::WARM_STARTED, + new Event(EventName::WARM_STARTED, ['module' => $module]), + ); + + try { + $snapshot = $this->buildGeneration($module, $moduleRoot); + $this->snapshots[$module] = $snapshot; + $this->dispatcher->dispatch( + EventName::WARM_COMPLETED, + new Event(EventName::WARM_COMPLETED, ['module' => $module, 'snapshot' => $snapshot]), + ); + + return $snapshot; + } catch (\Throwable $exception) { + $this->dispatcher->dispatch( + EventName::WARM_FAILED, + new Event(EventName::WARM_FAILED, ['module' => $module, 'exception' => $exception]), + ); + + throw $exception; + } + } finally { + flock($lock, LOCK_UN); + fclose($lock); + } + } + + /** + * Streams, validates, indexes, and activates one generation. + * + * @param string $module Exact installed module identifier. + * @param string $moduleRoot Module cache root. + * + * @return SnapshotIndex + * @since 0.1.0 + */ + private function buildGeneration(string $module, string $moduleRoot): SnapshotIndex + { + $now = $this->clock->now(); + $expires = $now->add($this->configuration->refreshInterval()); + $staging = $moduleRoot . '/generations/.staging-' . getmypid() . '-' . bin2hex(random_bytes(8)); + + if (!Folder::create($staging, 0750)) { + throw new \RuntimeException(sprintf('Unable to create snapshot staging path "%s".', $staging)); + } + + $stream = null; + + try { + $moduleFile = $staging . '/module.ndjson'; + $stream = fopen($moduleFile, 'w+b'); + + if (!is_resource($stream)) { + throw new \RuntimeException('Unable to create the staged native module stream.'); + } + + $written = $this->moduleRootLock->read( + fn (): int => $this->extractor->streamModule($module, $stream), + ); + + if ($written < 0) { + throw new ContractException('Native module extraction returned an invalid byte count.'); + } + + if (fflush($stream) === false) { + throw new \RuntimeException('Unable to flush the staged native module stream.'); + } + + if (function_exists('fsync') && fsync($stream) === false) { + throw new \RuntimeException('Unable to synchronize the staged native module stream.'); + } + + $stats = fstat($stream); + + if (!is_array($stats) || $stats['size'] !== $written) { + throw new ContractException('Native module byte count does not match its staged stream.'); + } + + if (fseek($stream, 0) !== 0) { + throw new \RuntimeException('Unable to rewind the staged native module stream.'); + } + + $observer = new SnapshotRecordObserver(); + $result = $this->validator->validate($stream, $observer); + + if ( + $result->command() !== 'extract' + || count($result->modules()) !== 1 + || $result->modules()[0]->name()->bytes() !== $module + || !$result->modules()[0]->isBible() + ) { + throw new ContractException('Native extraction does not match the requested Bible module.'); + } + + $index = $observer->index($result->streamSha256(), $now); + $indexJson = json_encode( + $index, + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR, + ) . "\n"; + $this->writeSynchronized($staging . '/index.json', $indexJson); + fclose($stream); + $stream = null; + + $generation = $result->streamSha256(); + $destination = $moduleRoot . '/generations/' . $generation; + + if (is_dir($destination)) { + $snapshot = SnapshotIndex::open($destination, $now, $expires); + Folder::delete($staging); + } elseif (!rename($staging, $destination)) { + throw new \RuntimeException('Unable to atomically commit the staged snapshot generation.'); + } else { + $snapshot = SnapshotIndex::open($destination, $now, $expires); + } + + $pointer = [ + 'format' => 'getbible.scripture.current/v1', + 'generation' => $generation, + 'activated_at' => $now->format(DATE_ATOM), + 'expires_at' => $expires->format(DATE_ATOM), + ]; + $pointerJson = json_encode( + $pointer, + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + ) . "\n"; + $pointerTemp = $moduleRoot . '/current.' . bin2hex(random_bytes(8)) . '.tmp'; + $this->writeSynchronized($pointerTemp, $pointerJson); + + if (!rename($pointerTemp, $moduleRoot . '/current.json')) { + @unlink($pointerTemp); + throw new \RuntimeException('Unable to atomically activate the snapshot generation.'); + } + + return $snapshot; + } catch (\JsonException $exception) { + throw new \RuntimeException('Unable to serialize the snapshot index.', 0, $exception); + } finally { + if (is_resource($stream)) { + fclose($stream); + } + + if (is_dir($staging)) { + Folder::delete($staging); + } + } + } + + /** + * Opens the active generation when its pointer is complete and valid. + * + * @param string $module Exact installed module identifier. + * + * @return SnapshotIndex|null + * @since 0.1.0 + */ + private function openCurrent(string $module): ?SnapshotIndex + { + $moduleRoot = $this->moduleRoot($module); + $json = @file_get_contents($moduleRoot . '/current.json'); + + if ($json === false) { + return null; + } + + try { + $pointer = json_decode($json, true, 32, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + return null; + } + + if ( + !is_array($pointer) + || ($pointer['format'] ?? null) !== 'getbible.scripture.current/v1' + || !is_string($pointer['generation'] ?? null) + || preg_match('/^[0-9a-f]{64}$/D', $pointer['generation']) !== 1 + || !is_string($pointer['activated_at'] ?? null) + || !is_string($pointer['expires_at'] ?? null) + ) { + return null; + } + + try { + $activated = new \DateTimeImmutable($pointer['activated_at']); + $expires = new \DateTimeImmutable($pointer['expires_at']); + + return SnapshotIndex::open( + $moduleRoot . '/generations/' . $pointer['generation'], + $activated, + $expires, + ); + } catch (\Throwable) { + return null; + } + } + + /** + * Returns a traversal-safe per-module cache root. + * + * @param string $module Validated module identifier. + * + * @return string + * @since 0.1.0 + */ + private function moduleRoot(string $module): string + { + return $this->configuration->cachePath() . '/translations/' . $module; + } + + /** + * Validates a traversal-safe native module identifier. + * + * @param string $module Candidate identifier. + * + * @return string + * @since 0.1.0 + */ + private function validateModule(string $module): string + { + if ( + $module === '' + || $module === '.' + || $module === '..' + || preg_match('/^[A-Za-z0-9_.+-]+$/D', $module) !== 1 + ) { + throw new \InvalidArgumentException(sprintf('Invalid SWORD module identifier "%s".', $module)); + } + + return $module; + } + + /** + * Writes and synchronizes an application-owned file. + * + * @param string $path Destination path. + * @param string $contents Complete file contents. + * + * @return void + * @since 0.1.0 + */ + private function writeSynchronized(string $path, string $contents): void + { + $stream = fopen($path, 'xb'); + + if (!is_resource($stream)) { + throw new \RuntimeException(sprintf('Unable to create "%s".', $path)); + } + + try { + $remaining = $contents; + + while ($remaining !== '') { + $written = fwrite($stream, $remaining); + + if ($written === false || $written === 0) { + throw new \RuntimeException(sprintf('Unable to write "%s".', $path)); + } + + $remaining = substr($remaining, $written); + } + + if (fflush($stream) === false || (function_exists('fsync') && fsync($stream) === false)) { + throw new \RuntimeException(sprintf('Unable to synchronize "%s".', $path)); + } + } finally { + fclose($stream); + } + } +} diff --git a/stubs/getbible-sword.php b/stubs/getbible-sword.php new file mode 100644 index 0000000..a269cb3 --- /dev/null +++ b/stubs/getbible-sword.php @@ -0,0 +1,107 @@ +"}},{"interpretation":"not_applicable","kind":"text","raw":{"base64":"Sm9obg==","encoding":"base64","sha256":"a8cfcd74832004951b4408cdb0a5dbcd8c7e52d43f7fe244bf720582e05241da","size":4,"utf8":"John"}},{"interpretation":"uninterpreted","kind":"markup","raw":{"base64":"PC90aXRsZT4=","encoding":"base64","sha256":"6b9ee9595ebb616ce8c200221d7027056400a0cd58774db49d1af451ca22f2e2","size":8,"utf8":""}}],"key":{"base64":"Sm9obiAx","encoding":"base64","sha256":"bab25ddb636c3e5d2ab63b935c73f90ae2616f32ffa78504cfbb7741842e04cf","size":6,"utf8":"John 1"},"official_attributes":[],"ordinal":0,"projections_available":true,"raw":{"base64":"PHRpdGxlPkpvaG48L3RpdGxlPg==","encoding":"base64","sha256":"e9a23b617cc1e2eee7bd26bce57d1f5412973f130b44095a7253c44240a55455","size":19,"utf8":"John"},"rendered_default":{"base64":"PHRpdGxlPkpvaG48L3RpdGxlPg==","encoding":"base64","sha256":"e9a23b617cc1e2eee7bd26bce57d1f5412973f130b44095a7253c44240a55455","size":19,"utf8":"John"},"scope":{"book":4,"book_abbreviation":{"base64":"Sm9obg==","encoding":"base64","sha256":"a8cfcd74832004951b4408cdb0a5dbcd8c7e52d43f7fe244bf720582e05241da","size":4,"utf8":"John"},"book_name":{"base64":"Sm9obg==","encoding":"base64","sha256":"a8cfcd74832004951b4408cdb0a5dbcd8c7e52d43f7fe244bf720582e05241da","size":4,"utf8":"John"},"chapter":1,"index":0,"intro_scope":"chapter","osis_reference":{"base64":"Sm9obi4xLjA=","encoding":"base64","sha256":"de9f00a25f2618cba90a0694e4da68114abc8b964f56620475de902eb013f897","size":8,"utf8":"John.1.0"},"suffix":0,"testament":2,"type":"verse_key","verse":0,"versification":{"base64":"S0pW","encoding":"base64","sha256":"f98326ec7971053443d80268b911680a0eec8d4ead3b1d67445b7d534f1b5b2f","size":3,"utf8":"KJV"}},"sequence":3,"stripped":{"base64":"Sm9obg==","encoding":"base64","sha256":"a8cfcd74832004951b4408cdb0a5dbcd8c7e52d43f7fe244bf720582e05241da","size":4,"utf8":"John"},"type":"entry"} +{"annotation_segments":[{"interpretation":"uninterpreted","kind":"markup","raw":{"base64":"PHcgbGVtbWE9InN0cm9uZzpHMzA1NiI+","encoding":"base64","sha256":"06b1af3f7a407824650d5ebf1018826f7a7831a28d9e34dee7bb87c97949874d","size":24,"utf8":""}},{"interpretation":"not_applicable","kind":"text","raw":{"base64":"V29yZA==","encoding":"base64","sha256":"3a2860ece5a4ee0b48b41ee96dd8054cf9bc6f113249ec601478b2582d72ead4","size":4,"utf8":"Word"}},{"interpretation":"uninterpreted","kind":"markup","raw":{"base64":"PC93Pg==","encoding":"base64","sha256":"6cf15a9e3e0bfdad0c3e4c04c97d52bda066dc971aadd6b94adb0a4ce1cc6408","size":4,"utf8":""}}],"key":{"base64":"Sm9obiAxOjE=","encoding":"base64","sha256":"9ae7c2b973ffb922c598b029d22f0afe491bf3a12ee4513d9e9e2c9df04b65ec","size":8,"utf8":"John 1:1"},"official_attributes":[{"lists":[{"name":{"base64":"V29yZA==","encoding":"base64","sha256":"3a2860ece5a4ee0b48b41ee96dd8054cf9bc6f113249ec601478b2582d72ead4","size":4,"utf8":"Word"},"values":[{"name":{"base64":"TGVtbWE=","encoding":"base64","sha256":"f2a949af5ee49090d70aa9724334e1f968569f59ec8a5c3126c7d0f38ccec03c","size":5,"utf8":"Lemma"},"value":{"base64":"c3Ryb25nOkczMDU2","encoding":"base64","sha256":"e87cd6f7b32e14a9354f9a6ffe4956a8946c5b820714e1a2dd80d88deb6b3dca","size":12,"utf8":"strong:G3056"}}]}],"name":{"base64":"Rm9vdG5vdGU=","encoding":"base64","sha256":"aa8885bcba3b417e5cfcc4adbc958c42f5202b666abf364c8ef1af5cb2cb5314","size":8,"utf8":"Footnote"}}],"ordinal":1,"projections_available":true,"raw":{"base64":"PHcgbGVtbWE9InN0cm9uZzpHMzA1NiI+V29yZDwvdz4=","encoding":"base64","sha256":"35712cd2110cf23c3c02298290defc3b6b14dd0675af790a475d8245dcd68d1c","size":32,"utf8":"Word"},"rendered_default":{"base64":"PHcgbGVtbWE9InN0cm9uZzpHMzA1NiI+V29yZDwvdz4=","encoding":"base64","sha256":"35712cd2110cf23c3c02298290defc3b6b14dd0675af790a475d8245dcd68d1c","size":32,"utf8":"Word"},"scope":{"book":4,"book_abbreviation":{"base64":"Sm9obg==","encoding":"base64","sha256":"a8cfcd74832004951b4408cdb0a5dbcd8c7e52d43f7fe244bf720582e05241da","size":4,"utf8":"John"},"book_name":{"base64":"Sm9obg==","encoding":"base64","sha256":"a8cfcd74832004951b4408cdb0a5dbcd8c7e52d43f7fe244bf720582e05241da","size":4,"utf8":"John"},"chapter":1,"index":1,"intro_scope":"verse","osis_reference":{"base64":"Sm9obi4xLjE=","encoding":"base64","sha256":"408afba5ec077bf53fcf36c5a2520a3888ea07bbfedfbc971c2166baa70dd51a","size":8,"utf8":"John.1.1"},"suffix":0,"testament":2,"type":"verse_key","verse":1,"versification":{"base64":"S0pW","encoding":"base64","sha256":"f98326ec7971053443d80268b911680a0eec8d4ead3b1d67445b7d534f1b5b2f","size":3,"utf8":"KJV"}},"sequence":4,"stripped":{"base64":"V29yZA==","encoding":"base64","sha256":"3a2860ece5a4ee0b48b41ee96dd8054cf9bc6f113249ec601478b2582d72ead4","size":4,"utf8":"Word"},"type":"entry"} +{"artifact_bytes":0,"artifacts":0,"counts":{"config_entry":1,"entry":2,"header":1,"module":1},"diagnostics":{"error":0,"info":0,"warning":0},"entries":2,"sequence":5,"stream_sha256":"12dfe5252316bc73232da8b9b0ebf5ca18c7839daa6b11189206d0a5e1ee6686","success":true,"type":"footer"} diff --git a/tests/Unit/Configuration/ConfigurationTest.php b/tests/Unit/Configuration/ConfigurationTest.php new file mode 100644 index 0000000..d963776 --- /dev/null +++ b/tests/Unit/Configuration/ConfigurationTest.php @@ -0,0 +1,78 @@ + '/tmp/getbible-scripture-configuration-test', + 'modules' => ' KJV, WEB, KJV ', + 'provisioning_enabled' => 'yes', + 'install_all' => 'on', + 'lock_timeout' => '45', + ]); + + self::assertSame(['KJV', 'WEB'], $configuration->modules()); + self::assertTrue($configuration->provisioningEnabled()); + self::assertTrue($configuration->installAll()); + self::assertSame(45, $configuration->lockTimeout()); + self::assertSame( + '/tmp/getbible-scripture-configuration-test/maintenance/state.json', + $configuration->maintenanceStatePath(), + ); + } + + /** + * Verifies all-module installation requires explicit mutation policy. + * + * @return void + * @since 0.3.0 + */ + public function testRejectsInstallAllWithoutProvisioningPolicy(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('requires explicit provisioning_enabled'); + + Configuration::fromEnvironment([ + 'cache_path' => '/tmp/getbible-scripture-configuration-test', + 'install_all' => true, + ]); + } + + /** + * Verifies a syntactically valid interval must still advance time. + * + * @return void + * @since 0.3.0 + */ + public function testRejectsNonAdvancingInterval(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('must advance time'); + + Configuration::fromEnvironment([ + 'cache_path' => '/tmp/getbible-scripture-configuration-test', + 'refresh_interval' => 'P0D', + ]); + } +} diff --git a/tests/Unit/Contract/ByteValueTest.php b/tests/Unit/Contract/ByteValueTest.php new file mode 100644 index 0000000..37bcca0 --- /dev/null +++ b/tests/Unit/Contract/ByteValueTest.php @@ -0,0 +1,59 @@ + 'S0pW', + 'encoding' => 'base64', + 'sha256' => 'f98326ec7971053443d80268b911680a0eec8d4ead3b1d67445b7d534f1b5b2f', + 'size' => 3, + 'utf8' => 'KJV', + ]); + + self::assertSame('KJV', $value->bytes()); + self::assertSame('KJV', $value->requireUtf8()); + self::assertSame(3, $value->size()); + } + + /** + * Verifies that digest tampering is rejected. + * + * @return void + * @since 0.1.0 + */ + public function testDigestMismatchIsRejected(): void + { + $this->expectException(ContractException::class); + + ByteValue::fromArray([ + 'base64' => 'S0pW', + 'encoding' => 'base64', + 'sha256' => str_repeat('0', 64), + 'size' => 3, + 'utf8' => 'KJV', + ]); + } +} diff --git a/tests/Unit/Contract/ContractV1ValidatorTest.php b/tests/Unit/Contract/ContractV1ValidatorTest.php new file mode 100644 index 0000000..e968842 --- /dev/null +++ b/tests/Unit/Contract/ContractV1ValidatorTest.php @@ -0,0 +1,361 @@ +validate($stream); + } finally { + fclose($stream); + } + + self::assertSame('extract', $result->command()); + self::assertSame('TestBible', $result->modules()[0]->name()->requireUtf8()); + self::assertSame( + '12dfe5252316bc73232da8b9b0ebf5ca18c7839daa6b11189206d0a5e1ee6686', + $result->streamSha256(), + ); + } + + /** + * Verifies that changing one authoritative field invalidates the footer. + * + * @return void + * @since 0.1.0 + */ + public function testStreamDigestTamperingIsRejected(): void + { + $contents = file_get_contents(__DIR__ . '/../../Fixtures/test-bible.ndjson'); + self::assertIsString($contents); + $tampered = str_replace('"Public Domain"', '"Public domain"', $contents); + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, $tampered); + rewind($stream); + + $this->expectException(ContractException::class); + + try { + (new ContractV1Validator())->validate($stream); + } finally { + fclose($stream); + } + } + + /** + * Verifies complete regular-artifact validation. + * + * @return void + * @since 0.1.0 + */ + public function testRegularArtifactIsAccepted(): void + { + $records = $this->fixtureRecords(); + array_push($records, ...$this->regularArtifactRecords('mods.d/test.dat', 'content')); + $stream = $this->stream($records); + + try { + $result = (new ContractV1Validator())->validate($stream); + } finally { + fclose($stream); + } + + self::assertSame(1, $result->footer()['artifacts']); + self::assertSame(7, $result->footer()['artifact_bytes']); + } + + /** + * Verifies that stable artifact metadata must agree with streamed bytes. + * + * @return void + * @since 0.1.0 + */ + public function testStableArtifactExpectedSizeMismatchIsRejected(): void + { + $records = $this->fixtureRecords(); + $artifact = $this->regularArtifactRecords('mods.d/test.dat', 'content'); + $artifact[0]['size_expected'] = 8; + array_push($records, ...$artifact); + $stream = $this->stream($records); + + $this->expectException(ContractException::class); + + try { + (new ContractV1Validator())->validate($stream); + } finally { + fclose($stream); + } + } + + /** + * Verifies that artifact groups cannot be split by diagnostics. + * + * @return void + * @since 0.1.0 + */ + public function testDiagnosticInsideArtifactGroupIsRejected(): void + { + $records = $this->fixtureRecords(); + $artifact = $this->regularArtifactRecords('mods.d/test.dat', 'content'); + array_splice($artifact, 1, 0, [[ + 'code' => 'test.info', + 'message' => $this->byteValue('Test information'), + 'severity' => 'info', + 'type' => 'diagnostic', + ]]); + array_push($records, ...$artifact); + $stream = $this->stream($records); + + $this->expectException(ContractException::class); + + try { + (new ContractV1Validator())->validate($stream); + } finally { + fclose($stream); + } + } + + /** + * Verifies that a short artifact chunk must be final. + * + * @return void + * @since 0.1.0 + */ + public function testChunkAfterShortChunkIsRejected(): void + { + $records = $this->fixtureRecords(); + $artifact = $this->regularArtifactRecords('mods.d/test.dat', 'ab'); + $artifact[1]['data'] = $this->byteValue('a'); + array_splice($artifact, 2, 0, [[ + 'artifact_id' => 0, + 'data' => $this->byteValue('b'), + 'index' => 1, + 'type' => 'artifact_chunk', + ]]); + array_push($records, ...$artifact); + $stream = $this->stream($records); + + $this->expectException(ContractException::class); + + try { + (new ContractV1Validator())->validate($stream); + } finally { + fclose($stream); + } + } + + /** + * Verifies that artifact paths cannot traverse their extraction root. + * + * @return void + * @since 0.1.0 + */ + public function testUnsafeArtifactPathIsRejected(): void + { + $records = $this->fixtureRecords(); + array_push($records, ...$this->regularArtifactRecords('../test.dat', 'content')); + $stream = $this->stream($records); + + $this->expectException(ContractException::class); + + try { + (new ContractV1Validator())->validate($stream); + } finally { + fclose($stream); + } + } + + /** + * Verifies that list operations cannot contain extract-only records. + * + * @return void + * @since 0.1.0 + */ + public function testListStreamRejectsExtractRecords(): void + { + $records = $this->fixtureRecords(); + $records[0]['command'] = 'list'; + unset($records[0]['artifact_chunk_size']); + $stream = $this->stream($records); + + $this->expectException(ContractException::class); + + try { + (new ContractV1Validator())->validate($stream); + } finally { + fclose($stream); + } + } + + /** + * Loads non-footer records from the deterministic fixture. + * + * @return list> + * @since 0.1.0 + */ + private function fixtureRecords(): array + { + $lines = file(__DIR__ . '/../../Fixtures/test-bible.ndjson', FILE_IGNORE_NEW_LINES); + self::assertIsArray($lines); + $records = []; + + foreach ($lines as $line) { + $record = json_decode($line, true, 512, JSON_THROW_ON_ERROR); + $record = StructuredData::object($record, 'Test fixture record'); + + if (($record['type'] ?? null) !== 'footer') { + $records[] = $record; + } + } + + return $records; + } + + /** + * Creates a complete regular-artifact record group. + * + * @param string $path Root-relative artifact path. + * @param string $bytes Artifact bytes. + * + * @return list> + * @since 0.1.0 + */ + private function regularArtifactRecords(string $path, string $bytes): array + { + return [ + [ + 'artifact_id' => 0, + 'file_type' => 'regular', + 'mode' => 420, + 'path' => $this->byteValue($path), + 'role' => 'module_data', + 'size_expected' => strlen($bytes), + 'type' => 'artifact_begin', + ], + [ + 'artifact_id' => 0, + 'data' => $this->byteValue($bytes), + 'index' => 0, + 'type' => 'artifact_chunk', + ], + [ + 'artifact_id' => 0, + 'sha256' => hash('sha256', $bytes), + 'size' => strlen($bytes), + 'stable' => true, + 'type' => 'artifact_end', + ], + ]; + } + + /** + * Creates an exact byte envelope for generated contract records. + * + * @param string $bytes Exact bytes. + * + * @return array{base64: string, encoding: string, sha256: string, size: int, utf8: string} + * @since 0.1.0 + */ + private function byteValue(string $bytes): array + { + return [ + 'base64' => base64_encode($bytes), + 'encoding' => 'base64', + 'sha256' => hash('sha256', $bytes), + 'size' => strlen($bytes), + 'utf8' => $bytes, + ]; + } + + /** + * Serializes records with an internally consistent footer. + * + * @param list> $records Non-footer records. + * + * @return resource + * @since 0.1.0 + */ + private function stream(array $records): mixed + { + $lines = []; + $counts = []; + $diagnostics = ['error' => 0, 'info' => 0, 'warning' => 0]; + $entries = 0; + $artifacts = 0; + $artifactBytes = 0; + + foreach ($records as $sequence => $record) { + $record['sequence'] = $sequence; + $type = $record['type']; + self::assertIsString($type); + $counts[$type] = ($counts[$type] ?? 0) + 1; + + if ($type === 'entry') { + ++$entries; + } elseif ($type === 'artifact_end') { + $size = $record['size'] ?? null; + self::assertIsInt($size); + ++$artifacts; + $artifactBytes += $size; + } elseif ($type === 'diagnostic') { + $severity = $record['severity'] ?? null; + self::assertIsString($severity); + self::assertArrayHasKey($severity, $diagnostics); + ++$diagnostics[$severity]; + } + + $lines[] = json_encode( + $record, + JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR, + ) . "\n"; + } + + $footer = [ + 'artifact_bytes' => $artifactBytes, + 'artifacts' => $artifacts, + 'counts' => $counts, + 'diagnostics' => $diagnostics, + 'entries' => $entries, + 'sequence' => count($records), + 'stream_sha256' => hash('sha256', implode('', $lines)), + 'success' => $diagnostics['error'] === 0, + 'type' => 'footer', + ]; + $lines[] = json_encode( + $footer, + JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR, + ) . "\n"; + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, implode('', $lines)); + rewind($stream); + + return $stream; + } +} diff --git a/tests/Unit/Maintenance/JsonMaintenanceStateStoreTest.php b/tests/Unit/Maintenance/JsonMaintenanceStateStoreTest.php new file mode 100644 index 0000000..bccaf68 --- /dev/null +++ b/tests/Unit/Maintenance/JsonMaintenanceStateStoreTest.php @@ -0,0 +1,117 @@ +cachePath = sys_get_temp_dir() + . '/getbible-scripture-state-test-' + . bin2hex(random_bytes(8)); + } + + /** + * Removes the isolated persisted state. + * + * @return void + * @since 0.3.0 + */ + protected function tearDown(): void + { + $statePath = $this->cachePath . '/maintenance/state.json'; + + if (is_file($statePath)) { + unlink($statePath); + } + + if (is_dir(dirname($statePath))) { + rmdir(dirname($statePath)); + } + + if (is_dir($this->cachePath)) { + rmdir($this->cachePath); + } + } + + /** + * Verifies a successful state survives an atomic round trip. + * + * @return void + * @since 0.3.0 + */ + public function testRoundTripsState(): void + { + $store = $this->store(); + $completedAt = new \DateTimeImmutable('2026-07-26T12:00:00+00:00'); + + self::assertNull($store->load()->lastAttemptAt()); + + $store->save(MaintenanceState::empty()->succeededAt($completedAt)); + $restored = $store->load(); + + self::assertSame( + $completedAt->format(DATE_ATOM), + $restored->lastSuccessAt()?->format(DATE_ATOM), + ); + self::assertSame(0, $restored->consecutiveFailures()); + } + + /** + * Verifies corrupt durable state is rejected instead of silently reset. + * + * @return void + * @since 0.3.0 + */ + public function testRejectsCorruptState(): void + { + $store = $this->store(); + $store->save(MaintenanceState::empty()); + $statePath = $this->cachePath . '/maintenance/state.json'; + self::assertNotFalse(file_put_contents($statePath, '{"format":"invalid"}')); + + $this->expectException(\UnexpectedValueException::class); + $store->load(); + } + + /** + * Creates the state store for the isolated path. + * + * @return JsonMaintenanceStateStore + * @since 0.3.0 + */ + private function store(): JsonMaintenanceStateStore + { + return new JsonMaintenanceStateStore(Configuration::fromEnvironment([ + 'cache_path' => $this->cachePath, + ])); + } +} diff --git a/tests/Unit/Maintenance/MaintenanceServiceTest.php b/tests/Unit/Maintenance/MaintenanceServiceTest.php new file mode 100644 index 0000000..9e180ed --- /dev/null +++ b/tests/Unit/Maintenance/MaintenanceServiceTest.php @@ -0,0 +1,394 @@ +catalog($metadata); + $snapshots = $this->snapshots(); + $store = $this->stateStore(); + $service = new MaintenanceService( + Configuration::fromEnvironment([ + 'cache_path' => sys_get_temp_dir() . '/getbible-scripture-maintenance-test', + 'modules' => ['TestBible'], + 'provisioning_enabled' => false, + ]), + $this->clock(), + $catalog, + $snapshots, + $this->provisioning(), + $store, + $this->lock(), + new Dispatcher(), + ); + + $result = $service->initialize(); + + self::assertTrue($result->succeeded()); + self::assertSame('ready', $result->modules()[0]->status()); + self::assertNotNull($store->load()->lastSuccessAt()); + } + + /** + * Verifies interval-gated refresh skips without touching native services. + * + * @return void + * @since 0.3.0 + */ + public function testRefreshIfDueSkipsAfterRecentSuccess(): void + { + $store = $this->stateStore(); + $store->save( + $store->load()->succeededAt(new \DateTimeImmutable('2026-07-26T12:00:00+00:00')), + ); + $service = new MaintenanceService( + Configuration::fromEnvironment([ + 'cache_path' => sys_get_temp_dir() . '/getbible-scripture-maintenance-test', + 'refresh_interval' => 'P1M', + ]), + $this->clock(), + $this->catalog(), + $this->snapshots(), + $this->provisioning(), + $store, + $this->lock(), + new Dispatcher(), + ); + + $result = $service->refreshIfDue(); + + self::assertTrue($result->succeeded()); + self::assertFalse($result->due()); + self::assertSame('The configured refresh interval has not elapsed.', $result->skipReason()); + } + + /** + * Creates a fixed clock. + * + * @return ClockInterface + * @since 0.3.0 + */ + private function clock(): ClockInterface + { + return new class () implements ClockInterface { + /** + * Returns deterministic UTC time. + * + * @return \DateTimeImmutable + */ + public function now(): \DateTimeImmutable + { + return new \DateTimeImmutable('2026-07-26T12:01:00+00:00'); + } + }; + } + + /** + * Creates an in-memory state store. + * + * @return MaintenanceStateStoreInterface + * @since 0.3.0 + */ + private function stateStore(): MaintenanceStateStoreInterface + { + return new class () implements MaintenanceStateStoreInterface { + /** + * Current in-memory state. + * + * @var MaintenanceState + */ + public MaintenanceState $state; + + /** + * Creates empty state. + */ + public function __construct() + { + $this->state = MaintenanceState::empty(); + } + + /** + * Returns current state. + * + * @return MaintenanceState + */ + public function load(): MaintenanceState + { + return $this->state; + } + + /** + * Replaces current state. + * + * @param MaintenanceState $state New state. + * + * @return void + */ + public function save(MaintenanceState $state): void + { + $this->state = $state; + } + }; + } + + /** + * Creates a direct test maintenance lock. + * + * @return MaintenanceLockInterface + * @since 0.3.0 + */ + private function lock(): MaintenanceLockInterface + { + return new class () implements MaintenanceLockInterface { + /** + * Executes the callback directly. + * + * @template T + * + * @param callable(): T $operation Callback. + * + * @return T + */ + public function run(callable $operation): mixed + { + return $operation(); + } + }; + } + + /** + * Creates a fixed installed-module catalog. + * + * @param TranslationMetadata|null $metadata Optional installed translation. + * + * @return ModuleCatalogInterface + * @since 0.3.0 + */ + private function catalog(?TranslationMetadata $metadata = null): ModuleCatalogInterface + { + return new class ($metadata) implements ModuleCatalogInterface { + /** + * Creates a fixed catalog. + * + * @param TranslationMetadata|null $metadata Optional translation. + */ + public function __construct(private ?TranslationMetadata $metadata) + { + } + + /** + * Returns the optional translation. + * + * @return list + */ + public function translations(): array + { + return $this->metadata === null ? [] : [$this->metadata]; + } + + /** + * Returns the fixed translation. + * + * @param string $module Module identifier. + * + * @return TranslationMetadata + */ + public function translation(string $module): TranslationMetadata + { + if ($this->metadata === null || $this->metadata->name()->bytes() !== $module) { + throw new \RuntimeException('Translation is not installed.'); + } + + return $this->metadata; + } + + /** + * Clears no in-memory state. + * + * @return void + */ + public function clear(): void + { + } + }; + } + + /** + * Creates a counting snapshot manager. + * + * @return SnapshotManagerInterface + * @since 0.3.0 + */ + private function snapshots(): SnapshotManagerInterface + { + $reflection = new \ReflectionClass(SnapshotIndex::class); + $snapshot = $reflection->newInstanceWithoutConstructor(); + + return new class ($snapshot) implements SnapshotManagerInterface { + /** + * Number of get calls. + * + * @var int + */ + public int $gets = 0; + + /** + * Number of refresh calls. + * + * @var int + */ + public int $refreshes = 0; + + /** + * Creates the snapshot manager. + * + * @param SnapshotIndex $snapshot Uninitialized type-safe test object. + */ + public function __construct(private SnapshotIndex $snapshot) + { + } + + /** + * Counts and returns a snapshot. + * + * @param string $module Module identifier. + * + * @return SnapshotIndex + */ + public function get(string $module): SnapshotIndex + { + ++$this->gets; + + return $this->snapshot; + } + + /** + * Counts and returns a refreshed snapshot. + * + * @param string $module Module identifier. + * + * @return SnapshotIndex + */ + public function refresh(string $module): SnapshotIndex + { + ++$this->refreshes; + + return $this->snapshot; + } + + /** + * Clears no process state. + * + * @return void + */ + public function clear(): void + { + } + }; + } + + /** + * Creates an unavailable provisioning coordinator. + * + * @return ProvisioningCoordinatorInterface + * @since 0.3.0 + */ + private function provisioning(): ProvisioningCoordinatorInterface + { + return new class () implements ProvisioningCoordinatorInterface { + /** + * Returns ABI v1 capabilities. + * + * @return ProvisioningCapabilities + */ + public function capabilities(): ProvisioningCapabilities + { + return ProvisioningCapabilities::abiV1(); + } + + /** + * Rejects selected installation. + * + * @param list $modules Module identifiers. + * + * @return ProvisioningResult + */ + public function install(array $modules): ProvisioningResult + { + throw new \LogicException('Provisioning is unavailable.'); + } + + /** + * Rejects all-module installation. + * + * @return ProvisioningResult + */ + public function installAll(): ProvisioningResult + { + throw new \LogicException('Provisioning is unavailable.'); + } + + /** + * Rejects remote refresh. + * + * @param list $modules Module identifiers. + * + * @return ProvisioningResult + */ + public function refresh(array $modules = []): ProvisioningResult + { + throw new \LogicException('Provisioning is unavailable.'); + } + + /** + * Rejects removal. + * + * @param string $module Module identifier. + * + * @return ProvisioningResult + */ + public function remove(string $module): ProvisioningResult + { + throw new \LogicException('Provisioning is unavailable.'); + } + }; + } +} diff --git a/tests/Unit/Maintenance/MaintenanceStateTest.php b/tests/Unit/Maintenance/MaintenanceStateTest.php new file mode 100644 index 0000000..c845438 --- /dev/null +++ b/tests/Unit/Maintenance/MaintenanceStateTest.php @@ -0,0 +1,65 @@ +succeededAt($success); + $interval = new \DateInterval('P1M'); + + self::assertFalse($state->isDue( + new \DateTimeImmutable('2026-08-25T23:59:59+00:00'), + $interval, + )); + self::assertTrue($state->isDue( + new \DateTimeImmutable('2026-08-26T12:00:00+00:00'), + $interval, + )); + self::assertSame( + '2026-08-26T12:00:00+00:00', + $state->nextDueAt($interval)?->format(DATE_ATOM), + ); + } + + /** + * Verifies failures preserve last success and survive serialization. + * + * @return void + * @since 0.3.0 + */ + public function testFailureStateRoundTripsWithoutAdvancingSuccess(): void + { + $success = new \DateTimeImmutable('2026-07-01T00:00:00+00:00'); + $failure = new \DateTimeImmutable('2026-07-26T12:00:00+00:00'); + $state = MaintenanceState::empty() + ->succeededAt($success) + ->failedAt($failure, 'Network unavailable'); + $restored = MaintenanceState::fromArray($state->toArray()); + + self::assertSame($success->format(DATE_ATOM), $restored->lastSuccessAt()?->format(DATE_ATOM)); + self::assertSame($failure->format(DATE_ATOM), $restored->lastFailureAt()?->format(DATE_ATOM)); + self::assertSame('Network unavailable', $restored->lastError()); + self::assertSame(1, $restored->consecutiveFailures()); + } +} diff --git a/tests/Unit/Provisioning/ProvisioningCoordinatorTest.php b/tests/Unit/Provisioning/ProvisioningCoordinatorTest.php new file mode 100644 index 0000000..a19d0a0 --- /dev/null +++ b/tests/Unit/Provisioning/ProvisioningCoordinatorTest.php @@ -0,0 +1,252 @@ + + */ + public array $refreshed = []; + + /** + * Returns a complete test capability set. + * + * @return ProvisioningCapabilities + */ + public function capabilities(): ProvisioningCapabilities + { + return new ProvisioningCapabilities('test', 'test/v1', true, true, true, true); + } + + /** + * Rejects an unused selected installation. + * + * @param list $modules Module identifiers. + * + * @return ProvisioningResult + */ + public function installTranslations(array $modules): ProvisioningResult + { + throw new \LogicException('Not used in this test.'); + } + + /** + * Rejects an unused all-module installation. + * + * @return ProvisioningResult + */ + public function installAllTranslations(): ProvisioningResult + { + throw new \LogicException('Not used in this test.'); + } + + /** + * Returns changed outcomes for every requested module. + * + * @param list $modules Module identifiers. + * + * @return ProvisioningResult + */ + public function refreshTranslations(array $modules = []): ProvisioningResult + { + $this->refreshed = $modules; + + return new ProvisioningResult( + 'refresh', + array_map( + static fn (string $module): ModuleProvisioningResult => new ModuleProvisioningResult( + $module, + ModuleProvisioningResult::ACTION_REFRESH, + ModuleProvisioningResult::STATUS_CHANGED, + ), + $modules, + ), + ); + } + + /** + * Rejects an unused module removal. + * + * @param string $module Module identifier. + * + * @return ProvisioningResult + */ + public function removeTranslation(string $module): ProvisioningResult + { + throw new \LogicException('Not used in this test.'); + } + }; + + $lock = new class () implements ModuleRootLockInterface { + /** + * Number of acquired write locks. + * + * @var int + */ + public int $writes = 0; + + /** + * Executes a read callback. + * + * @template T + * + * @param callable(): T $operation Callback. + * + * @return T + */ + public function read(callable $operation): mixed + { + return $operation(); + } + + /** + * Executes a write callback. + * + * @template T + * + * @param callable(): T $operation Callback. + * + * @return T + */ + public function write(callable $operation): mixed + { + ++$this->writes; + + return $operation(); + } + }; + + $catalog = new class () implements ModuleCatalogInterface { + /** + * Number of process-cache invalidations. + * + * @var int + */ + public int $clears = 0; + + /** + * Returns no translations. + * + * @return list + */ + public function translations(): array + { + return []; + } + + /** + * Rejects an unused lookup. + * + * @param string $module Module identifier. + * + * @return TranslationMetadata + */ + public function translation(string $module): TranslationMetadata + { + throw new \LogicException('Not used in this test.'); + } + + /** + * Counts process-cache invalidations. + * + * @return void + */ + public function clear(): void + { + ++$this->clears; + } + }; + + $snapshots = new class () implements SnapshotManagerInterface { + /** + * Number of process-cache invalidations. + * + * @var int + */ + public int $clears = 0; + + /** + * Rejects an unused snapshot lookup. + * + * @param string $module Module identifier. + * + * @return SnapshotIndex + */ + public function get(string $module): SnapshotIndex + { + throw new \LogicException('Not used in this test.'); + } + + /** + * Rejects an unused snapshot refresh. + * + * @param string $module Module identifier. + * + * @return SnapshotIndex + */ + public function refresh(string $module): SnapshotIndex + { + throw new \LogicException('Not used in this test.'); + } + + /** + * Counts process-cache invalidations. + * + * @return void + */ + public function clear(): void + { + ++$this->clears; + } + }; + + $coordinator = new ProvisioningCoordinator( + $provisioner, + $lock, + $catalog, + $snapshots, + new Dispatcher(), + ); + $result = $coordinator->refresh([' KJV ', 'KJV', 'WEB']); + + self::assertSame(['KJV', 'WEB'], $provisioner->refreshed); + self::assertSame(['KJV', 'WEB'], $result->updated()); + self::assertSame(1, $lock->writes); + self::assertSame(1, $catalog->clears); + self::assertSame(1, $snapshots->clears); + } +} diff --git a/tests/Unit/Snapshot/TranslationSnapshotManagerTest.php b/tests/Unit/Snapshot/TranslationSnapshotManagerTest.php new file mode 100644 index 0000000..2ef4ce5 --- /dev/null +++ b/tests/Unit/Snapshot/TranslationSnapshotManagerTest.php @@ -0,0 +1,261 @@ +cachePath = sys_get_temp_dir() . '/getbible-scripture-test-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($this->cachePath, 0700, true)); + } + + /** + * Removes the isolated cache root. + * + * @return void + * @since 0.1.0 + */ + protected function tearDown(): void + { + $this->deleteDirectory($this->cachePath); + } + + /** + * Verifies one extraction warms a lazy translation and is reused. + * + * @return void + * @since 0.1.0 + */ + public function testTranslationIsWarmedOnceAndQueriedLazily(): void + { + $fixture = __DIR__ . '/../../Fixtures/test-bible.ndjson'; + $lines = file($fixture); + self::assertIsArray($lines); + $moduleRecord = json_decode($lines[1], true, 512, JSON_THROW_ON_ERROR); + self::assertIsArray($moduleRecord); + $metadata = TranslationMetadata::fromRecord($moduleRecord); + + $catalog = new class ($metadata) implements ModuleCatalogInterface { + /** + * Creates a fixed test catalog. + * + * @param TranslationMetadata $metadata Fixed module. + */ + public function __construct(private TranslationMetadata $metadata) + { + } + + /** + * Returns the fixed module. + * + * @return list + */ + public function translations(): array + { + return [$this->metadata]; + } + + /** + * Resolves the fixed module. + * + * @param string $module Module identifier. + * + * @return TranslationMetadata + */ + public function translation(string $module): TranslationMetadata + { + if ($module !== $this->metadata->name()->bytes()) { + throw new \RuntimeException('Unexpected test module.'); + } + + return $this->metadata; + } + + /** + * Clears no state. + * + * @return void + */ + public function clear(): void + { + } + }; + + $extractor = new class ($fixture) implements ModuleExtractorInterface { + /** + * Number of extraction calls. + * + * @var int + */ + public int $calls = 0; + + /** + * Creates a fixture-backed extractor. + * + * @param string $fixture Fixture path. + */ + public function __construct(private string $fixture) + { + } + + /** + * Returns a test module root. + * + * @return string + */ + public function modulePath(): string + { + return '/test/modules'; + } + + /** + * Rejects an unused list operation. + * + * @param resource $destination Destination. + * + * @return int + */ + public function streamModules(mixed $destination): int + { + throw new \LogicException('Not used in this test.'); + } + + /** + * Copies the deterministic fixture. + * + * @param string $module Module identifier. + * @param resource $destination Destination. + * @param int $artifactChunkSize Artifact chunk size. + * + * @return int + */ + public function streamModule( + string $module, + mixed $destination, + int $artifactChunkSize = 1048576, + ): int { + ++$this->calls; + $contents = file_get_contents($this->fixture); + + if ($contents === false || fwrite($destination, $contents) !== strlen($contents)) { + throw new \RuntimeException('Unable to copy test fixture.'); + } + + return strlen($contents); + } + }; + + $clock = new class () implements ClockInterface { + /** + * Returns a deterministic UTC time. + * + * @return \DateTimeImmutable + */ + public function now(): \DateTimeImmutable + { + return new \DateTimeImmutable('2026-07-26T12:00:00+00:00'); + } + }; + + $configuration = Configuration::fromEnvironment([ + 'module_path' => '/test/modules', + 'cache_path' => $this->cachePath, + 'refresh_interval' => 'P1M', + 'auto_refresh' => true, + ]); + $manager = new TranslationSnapshotManager( + $configuration, + $clock, + $catalog, + $extractor, + new ContractV1Validator(), + new Dispatcher(), + new FileModuleRootLock($configuration), + ); + + $translation = new Translation('TestBible', $manager->get('TestBible')); + $verse = $translation->book('John')->chapter(1)->verse(1); + + self::assertSame('Word', $verse->stripped()?->requireUtf8()); + self::assertSame('strong:G3056', $verse->officialAttributes()->types()[0] + ->lists()[0] + ->values()[0] + ->value() + ->requireUtf8()); + self::assertCount(1, $translation->book('John')->chapter(1)->introductions()); + self::assertSame( + 'Public Domain', + $translation->configEntriesNamed('DistributionLicense')[0]->value()->requireUtf8(), + ); + + $manager->get('TestBible'); + self::assertSame(1, $extractor->calls); + } + + /** + * Recursively removes a controlled test directory. + * + * @param string $path Controlled temporary path. + * + * @return void + * @since 0.1.0 + */ + private function deleteDirectory(string $path): void + { + if (!is_dir($path)) { + return; + } + + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST, + ); + + foreach ($iterator as $item) { + /** @var \SplFileInfo $item */ + if ($item->isDir()) { + rmdir($item->getPathname()); + } else { + unlink($item->getPathname()); + } + } + + rmdir($path); + } +}