commit 26acf5538ee231aa4368bea58ec804d62ddf499d Author: uchoamp Date: Thu Aug 7 23:35:39 2025 +0000 Initial commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..e8c3fae --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*.zig] +indent_style = space +indent_size = 4 +charset = utf-8 +trim_trailing_whitespace = true +max_line_length = 120 +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..880cd5d --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +zig-out +.zig-cache diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5b79932 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM alpine:latest + +RUN apk update +RUN apk add --no-cache zig +RUN mkdir app +WORKDIR /app +COPY ./src ./src +COPY ./build.zig . + +RUN zig build --release=fast +RUN rm -rf ./src +RUN rm -rf ./.zig-cache +RUN rm ./build.zig +RUN cp ./zig-out/bin/zigpay . +RUN rm -rf ./zig-out + + +ENTRYPOINT ["/app/zigpay"] + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4286f74 --- /dev/null +++ b/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. + +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. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +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 Affero 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 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 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. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it 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 the "copyright" line and a pointer to where the full notice is found. + + zig-pay + Copyright (C) 2025 uchoamp + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +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 AGPL, see . diff --git a/README.md b/README.md new file mode 100644 index 0000000..74950ef --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# ZigPay + +the code speaks for itself zig + nginx diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..c3acc16 --- /dev/null +++ b/build.zig @@ -0,0 +1,139 @@ +const std = @import("std"); + +// Although this function looks imperative, note that its job is to +// declaratively construct a build graph that will be executed by an external +// runner. +pub fn build(b: *std.Build) void { + // Standard target options allows the person running `zig build` to choose + // what target to build for. Here we do not override the defaults, which + // means any target is allowed, and the default is native. Other options + // for restricting supported target set are available. + const target = b.standardTargetOptions(.{}); + + // Standard optimization options allow the person running `zig build` to select + // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not + // set a preferred release mode, allowing the user to decide how to optimize. + const optimize = b.standardOptimizeOption(.{}); + + // We will also create a module for our other entry point, 'main.zig'. + const exe_mod = b.createModule(.{ + // `root_source_file` is the Zig "entry point" of the module. If a module + // only contains e.g. external object files, you can make this `null`. + // In this case the main source file is merely a path, however, in more + // complicated build scripts, this could be a generated file. + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + }); + + const security_mod = b.createModule(.{ .root_source_file = b.path("src/security/main.zig"), .target = target, .optimize = optimize }); + const context_mod = b.createModule(.{ .root_source_file = b.path("src/context/main.zig"), .target = target, .optimize = optimize }); + const data_mod = b.createModule(.{ .root_source_file = b.path("src/data/main.zig"), .target = target, .optimize = optimize }); + const endpoints_mod = b.createModule(.{ .root_source_file = b.path("src/endpoints/main.zig"), .target = target, .optimize = optimize }); + const parses_mod = b.createModule(.{ .root_source_file = b.path("src/parses/main.zig"), .target = target, .optimize = optimize }); + const things_mod = b.createModule(.{ .root_source_file = b.path("src/things/main.zig"), .target = target, .optimize = optimize }); + const services_mod = b.createModule(.{ .root_source_file = b.path("src/services/main.zig"), .target = target, .optimize = optimize }); + const exchange_mod = b.createModule(.{ .root_source_file = b.path("src/exchange/main.zig"), .target = target, .optimize = optimize }); + const helpers_mod = b.createModule(.{ .root_source_file = b.path("src/helpers/main.zig"), .target = target, .optimize = optimize }); + + parses_mod.addImport("things", things_mod); + + data_mod.addImport("things", things_mod); + + context_mod.addImport("data", data_mod); + context_mod.addImport("exchange", exchange_mod); + + endpoints_mod.addImport("things", things_mod); + endpoints_mod.addImport("parses", parses_mod); + endpoints_mod.addImport("context", context_mod); + endpoints_mod.addImport("data", data_mod); + endpoints_mod.addImport("security", security_mod); + + services_mod.addImport("helpers", helpers_mod); + + exchange_mod.addImport("things", things_mod); + exchange_mod.addImport("data", data_mod); + exchange_mod.addImport("helpers", helpers_mod); + + exe_mod.addImport("things", things_mod); + exe_mod.addImport("context", context_mod); + exe_mod.addImport("security", security_mod); + exe_mod.addImport("endpoints", endpoints_mod); + exe_mod.addImport("parses", parses_mod); + exe_mod.addImport("data", data_mod); + exe_mod.addImport("services", services_mod); + exe_mod.addImport("exchange", exchange_mod); + + // This creates another `std.Build.Step.Compile`, but this one builds an executable + // rather than a static library. + const exe = b.addExecutable(.{ + .name = "zigpay", + .root_module = exe_mod, + }); + + // This declares intent for the executable to be installed into the + // standard location when the user invokes the "install" step (the default + // step when running `zig build`). + b.installArtifact(exe); + + // This *creates* a Run step in the build graph, to be executed when another + // step is evaluated that depends on it. The next line below will establish + // such a dependency. + const run_cmd = b.addRunArtifact(exe); + + // By making the run step depend on the install step, it will be run from the + // installation directory rather than directly from within the cache directory. + // This is not necessary, however, if the application depends on other installed + // files, this ensures they will be present and in the expected location. + run_cmd.step.dependOn(b.getInstallStep()); + + // This allows the user to pass arguments to the application in the build + // command itself, like this: `zig build run -- arg1 arg2 etc` + if (b.args) |args| { + run_cmd.addArgs(args); + } + + // This creates a build step. It will be visible in the `zig build --help` menu, + // and can be selected like this: `zig build run` + // This will evaluate the `run` step rather than the default, which is "install". + const run_step = b.step("run", "Run the app"); + run_step.dependOn(&run_cmd.step); + + // TESTS + const security_unit_tests = b.addTest(.{ .root_module = security_mod, .name = "security" }); + const run_security_unit_tests = b.addRunArtifact(security_unit_tests); + + const data_unit_tests = b.addTest(.{ .root_module = data_mod, .name = "data" }); + const run_data_unit_tests = b.addRunArtifact(data_unit_tests); + + const things_unit_tests = b.addTest(.{ .root_module = things_mod, .name = "things" }); + const run_things_unit_tests = b.addRunArtifact(things_unit_tests); + + const endpoints_unit_tests = b.addTest(.{ .root_module = endpoints_mod, .name = "endpoints" }); + const run_endpoints_unit_tests = b.addRunArtifact(endpoints_unit_tests); + + const services_unit_tests = b.addTest(.{ .root_module = services_mod, .name = "services" }); + const run_services_unit_tests = b.addRunArtifact(services_unit_tests); + + const exchange_unit_tests = b.addTest(.{ .root_module = exchange_mod, .name = "exchange" }); + const run_exchange_unit_tests = b.addRunArtifact(exchange_unit_tests); + + const parses_unit_tests = b.addTest(.{ .root_module = parses_mod, .name = "parses" }); + const run_parses_unit_tests = b.addRunArtifact(parses_unit_tests); + + const exe_unit_tests = b.addTest(.{ .root_module = exe_mod, .name = "root" }); + const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); + + // Similar to creating the run step earlier, this exposes a `test` step to + // the `zig build --help` menu, providing a way for the user to request + // running the unit tests. + const test_step = b.step("test", "Run unit tests"); + test_step.dependOn(&run_security_unit_tests.step); + test_step.dependOn(&run_things_unit_tests.step); + test_step.dependOn(&run_data_unit_tests.step); + test_step.dependOn(&run_parses_unit_tests.step); + test_step.dependOn(&run_services_unit_tests.step); + test_step.dependOn(&run_exchange_unit_tests.step); + test_step.dependOn(&run_endpoints_unit_tests.step); + test_step.dependOn(&run_exe_unit_tests.step); +} diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..d1e32ff --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,86 @@ +.{ + // This is the default name used by packages depending on this one. For + // example, when a user runs `zig fetch --save `, this field is used + // as the key in the `dependencies` table. Although the user can choose a + // different name, most users will stick with this provided value. + // + // It is redundant to include "zig" in this name because it is already + // within the Zig package namespace. + .name = .zigpay, + + // This is a [Semantic Version](https://semver.org/). + // In a future version of Zig it will be used for package deduplication. + .version = "0.0.0", + + // Together with name, this represents a globally unique package + // identifier. This field is generated by the Zig toolchain when the + // package is first created, and then *never changes*. This allows + // unambiguous detection of one package being an updated version of + // another. + // + // When forking a Zig project, this id should be regenerated (delete the + // field and run `zig build`) if the upstream project is still maintained. + // Otherwise, the fork is *hostile*, attempting to take control over the + // original project's identity. Thus it is recommended to leave the comment + // on the following line intact, so that it shows up in code reviews that + // modify the field. + .fingerprint = 0x2866aeaca47c3b91, // Changing this has security and trust implications. + + // Tracks the earliest Zig version that the package considers to be a + // supported use case. + .minimum_zig_version = "0.14.0", + + // This field is optional. + // Each dependency must either provide a `url` and `hash`, or a `path`. + // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. + // Once all dependencies are fetched, `zig build` no longer requires + // internet connectivity. + .dependencies = .{ + // See `zig fetch --save ` for a command-line interface for adding dependencies. + //.example = .{ + // // When updating this field to a new URL, be sure to delete the corresponding + // // `hash`, otherwise you are communicating that you expect to find the old hash at + // // the new URL. If the contents of a URL change this will result in a hash mismatch + // // which will prevent zig from using it. + // .url = "https://example.com/foo.tar.gz", + // + // // This is computed from the file contents of the directory of files that is + // // obtained after fetching `url` and applying the inclusion rules given by + // // `paths`. + // // + // // This field is the source of truth; packages do not come from a `url`; they + // // come from a `hash`. `url` is just one of many possible mirrors for how to + // // obtain a package matching this `hash`. + // // + // // Uses the [multihash](https://multiparses.io/multihash/) format. + // .hash = "...", + // + // // When this is provided, the package is found in a directory relative to the + // // build root. In this case the package's hash is irrelevant and therefore not + // // computed. This field and `url` are mutually exclusive. + // .path = "foo", + // + // // When this is set to `true`, a package is declared to be lazily + // // fetched. This makes the dependency only get fetched if it is + // // actually used. + // .lazy = false, + //}, + }, + + // Specifies the set of files and directories that are included in this package. + // Only files and directories listed here are included in the `hash` that + // is computed for this package. Only files listed here will remain on disk + // when using the zig package manager. As a rule of thumb, one should list + // files required for compilation plus any license(s). + // Paths are relative to the build root. Use the empty string (`""`) to refer to + // the build root itself. + // A directory listed here means that all files within, recursively, are included. + .paths = .{ + "build.zig", + "build.zig.zon", + "src", + // For example... + //"LICENSE", + //"README.md", + }, +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..b318287 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,57 @@ +services: + nginx: + container_name: balance-zig-pay + image: nginx:1.25-alpine + volumes: + - ./nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + - zig1 + - zig2 + ports: + - "9999:9999" + networks: + - payment-processor + deploy: + resources: + limits: + cpus: "0.30" + memory: "338MB" + zig1: &zig + container_name: zig-pay-1 + build: . + environment: + - SERVER_ENV=PROD + - DEFAULT_HOST=payment-processor-default + - DEFAULT_PORT=8080 + - DEFAULT_POOL=30 + - FALLBACK_HOST=payment-processor-fallback + - FALLBACK_PORT=8080 + - FALLBACK_POOL=0 + - PORT=8080 + - PAYMENT_SUMMARY_EXCHANGE_HOST=zig2 + - PAYMENT_SUMMARY_EXCHANGE_PORT=6969 + networks: + - payment-processor + deploy: + resources: + limits: + cpus: "0.60" + memory: "6MB" + zig2: + <<: *zig + container_name: zig-pay-2 + environment: + - SERVER_ENV=PROD + - DEFAULT_HOST=payment-processor-default + - DEFAULT_PORT=8080 + - FALLBACK_HOST=payment-processor-fallback + - FALLBACK_PORT=8080 + - PORT=8080 + - PAYMENT_SUMMARY_EXCHANGE_HOST=zig1 + - PAYMENT_SUMMARY_EXCHANGE_PORT=6969 + +networks: + backend: + driver: bridge + payment-processor: + external: true diff --git a/nginx.conf b/nginx.conf new file mode 100644 index 0000000..0748411 --- /dev/null +++ b/nginx.conf @@ -0,0 +1,28 @@ +worker_processes auto; +worker_rlimit_nofile 500000; + +events { + use epoll; + worker_connections 1024; +} +http { + access_log off; + error_log /dev/null emerg; + + upstream backend_servers { + server zig1:8080; + server zig2:8080; + keepalive 200; + } + server { + listen 9999; + location / { + proxy_buffering off; + proxy_set_header Connection ""; + proxy_http_version 1.1; + proxy_set_header Keep-Alive ""; + proxy_set_header Proxy-Connection "keep-alive"; + proxy_pass http://backend_servers; + } + } +} diff --git a/src/context/config.zig b/src/context/config.zig new file mode 100644 index 0000000..2d0a971 --- /dev/null +++ b/src/context/config.zig @@ -0,0 +1,64 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const eql = std.mem.eql; + +const Env = enum { DEV, PROD }; + +pub const Config = struct { + env: Env, + name: []const u8 = "Payment Processor Default", + port: u16, + initial_token: []const u8, + default_host: []const u8, + default_port: u16, + default_pool: u16, + fallback_host: []const u8, + fallback_port: u16, + fallback_pool: u16, + payment_summary_exchange_host: ?[]const u8, + payment_summary_exchange_port: u16, + + pub fn init(allocator: Allocator) !Config { + var envMap = try std.process.getEnvMap(allocator); + + const port_env = envMap.get("PORT"); + const port = try std.fmt.parseInt(u16, port_env orelse "9999", 10); + + const initial_token = envMap.get("INITIAL_TOKEN") orelse "123"; + + const default_host = envMap.get("DEFAULT_HOST") orelse "localhost"; + const default_port_env = envMap.get("DEFAULT_PORT"); + const default_port = try std.fmt.parseInt(u16, default_port_env orelse "8001", 10); + const default_pool_env = envMap.get("DEFAULT_POOL"); + const default_pool = try std.fmt.parseInt(u16, default_pool_env orelse "20", 10); + + const fallback_host = envMap.get("FALLBACK_HOST") orelse "localhost"; + const fallback_port_env = envMap.get("FALLBACK_PORT"); + const fallback_pool_env = envMap.get("FALLBACK_POOL"); + const fallback_port = try std.fmt.parseInt(u16, fallback_port_env orelse "8002", 10); + const fallback_pool = try std.fmt.parseInt(u16, fallback_pool_env orelse "20", 10); + + const payment_summary_exchange_host = envMap.get("PAYMENT_SUMMARY_EXCHANGE_HOST"); + const payment_summary_exchange_port_env = envMap.get("PAYMENT_SUMMARY_EXCHANGE_PORT"); + const payment_summary_exchange_port = try std.fmt.parseInt(u16, payment_summary_exchange_port_env orelse "0000", 10); + + var env = Env.DEV; + const server_env = envMap.get("SERVER_ENV"); + if (server_env != null and eql(u8, "PROD", server_env.?)) + env = .PROD; + + return Config{ + .env = env, + .port = port, + .initial_token = initial_token, + .default_host = default_host, + .default_port = default_port, + .default_pool = default_pool, + .fallback_host = fallback_host, + .fallback_port = fallback_port, + .fallback_pool = fallback_pool, + .payment_summary_exchange_host = payment_summary_exchange_host, + .payment_summary_exchange_port = payment_summary_exchange_port, + }; + } +}; diff --git a/src/context/main.zig b/src/context/main.zig new file mode 100644 index 0000000..075c1b2 --- /dev/null +++ b/src/context/main.zig @@ -0,0 +1,62 @@ +const std = @import("std"); +const heap = std.heap; +const mem = std.mem; +const Allocator = std.mem.Allocator; +const FixedBufferAllocator = heap.FixedBufferAllocator; + +const Config = @import("config.zig").Config; +const data = @import("data"); +const exchange = @import("exchange"); + +pub const ServerSettings = struct { + failure: bool = false, + delay: u64 = 0, +}; + +const payments = data.payments; + +var heap_alocated: []u8 = undefined; + +pub var config: Config = undefined; +pub var payments_repository: payments.PaymentsRepository = undefined; + +var summary_exchange_connection: exchange.ExchangeConnection = undefined; +pub var summary_exchange: exchange.PaymentSummaryExchange = undefined; + +pub var server_settings: ServerSettings = .{}; + +pub fn init() !void { + const total_elements_expected = 100_000; + const alloc_payments_repository = payments.calculateNecessaryMemory(total_elements_expected); + + heap_alocated = try std.heap.page_allocator.alloc(u8, 1024 * 100 + alloc_payments_repository); + var pba = FixedBufferAllocator.init(heap_alocated); + const allocator = pba.allocator(); + + config = try Config.init(allocator); + + const data_payments = try allocator.alloc(u8, alloc_payments_repository); + var pba_data_payments = FixedBufferAllocator.init(data_payments); + + payments_repository = try payments.PaymentsRepository.init(pba_data_payments.allocator(), total_elements_expected); + + if (config.payment_summary_exchange_host != null) { + summary_exchange_connection = try exchange.ExchangeConnection.init( + config.payment_summary_exchange_host.?, + config.payment_summary_exchange_port, + ); + + summary_exchange = exchange.PaymentSummaryExchange.init(&payments_repository, &summary_exchange_connection); + summary_exchange.start(); + } else { + summary_exchange_connection = exchange.ExchangeConnection{ + .in_address = undefined, + .out_address = undefined, + .out_status = .dead, + }; + + summary_exchange = exchange.PaymentSummaryExchange.init(&payments_repository, &summary_exchange_connection); + } +} + +pub fn deinit() void {} diff --git a/src/data/main.zig b/src/data/main.zig new file mode 100644 index 0000000..ee3f342 --- /dev/null +++ b/src/data/main.zig @@ -0,0 +1,7 @@ +const std = @import("std"); + +pub const payments = @import("payments.zig"); + +test { + std.testing.refAllDecls(@This()); +} diff --git a/src/data/payments.zig b/src/data/payments.zig new file mode 100644 index 0000000..33d3294 --- /dev/null +++ b/src/data/payments.zig @@ -0,0 +1,604 @@ +const std = @import("std"); +const expect = std.testing.expect; +const heap = std.heap; +const hash_map = std.hash_map; +const mem = std.mem; +const Thread = std.Thread; +const Mutex = Thread.Mutex; +const Allocator = mem.Allocator; +const testing = std.testing; + +const DateTime = @import("things").DateTime; + +const SubscriberFunc = fn (payment: *Payment) void; + +pub const PaymentIntegrationStatus = enum { processing, processed, not_integrated }; + +pub const Payment = struct { + id: [36]u8, + amount: f64, + requested_at: DateTime, + integration_status: PaymentIntegrationStatus = .processing, + processed_by: u64 = undefined, + + pub fn getIntegrationStatus(self: *const Payment) []const u8 { + return switch (self.integration_status) { + .processing => "processing", + .processed => "processed", + .not_integrated => "not integrated" + }; + } +}; + +pub const PaymentsSummary = struct { + total_payments_processed: usize, + total_value: f64, +}; + +pub const PaymentsIntegrationSummary = struct { + default_total_payments_processed: usize, + default_total_value: f64, + fallback_total_payments_processed: usize, + fallback_total_value: f64, +}; + +const CONTAINER_INCREASE_RATE = 32; +const MAX_CONTAINER_INCREASE = 32 * CONTAINER_INCREASE_RATE; + +inline fn calculateMaxIndexes(tee: usize) usize { + return ((tee / CONTAINER_INCREASE_RATE) + 1); +} + +pub inline fn calculateNecessaryMemory(tee: usize) usize { + return (@sizeOf(Payment) * tee) + (@sizeOf(IndexContainerUnsafe) * calculateMaxIndexes(tee)) + (calculateMaxIndexes(tee) * MAX_CONTAINER_INCREASE); +} + +inline fn newContainerSize(c: usize) usize { + return c + CONTAINER_INCREASE_RATE; +} + +const IndexContainerUnsafe = struct { + len: usize = 0, + container_size: usize = CONTAINER_INCREASE_RATE, + container: []*const Payment = undefined, + allocator: Allocator, + pub fn init(allocator: Allocator) !IndexContainerUnsafe { + const container = try allocator.alloc(*const Payment, CONTAINER_INCREASE_RATE); + + return IndexContainerUnsafe{ .container = container, .allocator = allocator }; + } + + pub fn add(self: *IndexContainerUnsafe, payment: *const Payment) !void { + if (self.len == self.container_size) { + const new_container_size = newContainerSize(self.len); + self.container = try self.allocator.realloc(self.container, new_container_size); + + self.container_size = new_container_size; + } + + self.container[self.len] = payment; + self.len += 1; + } + + pub fn find(self: *IndexContainerUnsafe, target: []const u8) ?*const Payment { + for (0..self.len) |i| { + if (mem.eql(u8, target, &self.container[i].id)) + return self.container[i]; + } + + return null; + } + + pub fn reset(self: *IndexContainerUnsafe) void { + self.len = 0; + } + + pub fn deinit(self: *IndexContainerUnsafe) void { + self.len = 0; + self.container_size = 0; + self.allocator.free(self.container); + } +}; + +pub const PaymentsRepository = struct { + len: usize = 0, + max_indexes: usize = 1, + database_size: usize, + payments: []Payment, + indexes: []IndexContainerUnsafe, + mutex: Mutex, + allocator: Allocator, + subscribers_insert: [2]*const SubscriberFunc = undefined, + subscribers_insert_len: usize = 0, + + pub fn init(allocator: Allocator, database_size: usize) !PaymentsRepository { + const payments = try allocator.alloc(Payment, database_size); + + const max_indexes = calculateMaxIndexes(database_size); + var indexes = try allocator.alloc(IndexContainerUnsafe, max_indexes); + + for (0..indexes.len) |i| { + indexes[i] = try IndexContainerUnsafe.init(allocator); + } + + return PaymentsRepository{ .allocator = allocator, .mutex = Mutex{}, .database_size = database_size, .payments = payments, .indexes = indexes, .max_indexes = max_indexes }; + } + + pub fn subscribeInsert(self: *PaymentsRepository, func: *const SubscriberFunc) void { + self.subscribers_insert[self.subscribers_insert_len] = func; + self.subscribers_insert_len += 1; + } + + pub fn insert(self: *PaymentsRepository, payment: Payment) !void { + self.mutex.lock(); + defer self.mutex.unlock(); + + if (self.len == self.database_size) + return Allocator.Error.OutOfMemory; + + self.payments[self.len] = payment; + const id_hash = self.hash(&payment.id); + try self.indexes[id_hash].add(&self.payments[self.len]); + + for (self.subscribers_insert[0..self.subscribers_insert_len]) |func| { + func(&self.payments[self.len]); + } + + self.len += 1; + } + + pub fn findById(self: *PaymentsRepository, id: []const u8) ?*const Payment { + self.mutex.lock(); + defer self.mutex.unlock(); + + if (self.len == 0) + return null; + + const id_hash = self.hash(id); + const ic = self.indexes[id_hash].find(id); + + return ic; + } + + pub fn reset(self: *PaymentsRepository) void { + self.mutex.lock(); + defer self.mutex.unlock(); + + self.len = 0; + + for (0..self.indexes.len) |i| { + self.indexes[i].reset(); + } + } + + pub fn periodSummary(self: *PaymentsRepository, from: ?DateTime, to: ?DateTime) PaymentsSummary { + self.mutex.lock(); + const len = self.len; + self.mutex.unlock(); + var payments_summary = PaymentsSummary{ .total_payments_processed = 0, .total_value = 0 }; + + if (from != null and to != null) { + for (0..len) |i| { + const payment = self.payments[i]; + + if (payment.requested_at.gt(from.?) and payment.requested_at.lt(to.?)) { + payments_summary.total_payments_processed += 1; + payments_summary.total_value += payment.amount; + } + } + } else if (from != null) { + for (0..len) |i| { + const payment = self.payments[i]; + + if (payment.requested_at.gt(from.?)) { + payments_summary.total_payments_processed += 1; + payments_summary.total_value += payment.amount; + } + } + } else if (to != null) { + for (0..len) |i| { + const payment = self.payments[i]; + + if (payment.requested_at.lt(to.?)) { + payments_summary.total_payments_processed += 1; + payments_summary.total_value += payment.amount; + } + } + } else { + for (0..len) |i| { + payments_summary.total_value += self.payments[i].amount; + } + payments_summary.total_payments_processed = len; + } + + return payments_summary; + } + + pub fn integrationSummary(self: *PaymentsRepository, from: ?DateTime, to: ?DateTime) PaymentsIntegrationSummary { + self.mutex.lock(); + const len = self.len; + self.mutex.unlock(); + var summary = PaymentsIntegrationSummary{ + .default_total_payments_processed = 0, + .default_total_value = 0, + .fallback_total_payments_processed = 0, + .fallback_total_value = 0, + }; + + if (from != null and to != null) { + for (0..len) |i| { + const payment = self.payments[i]; + + if (payment.requested_at.gt(from.?) and payment.requested_at.lt(to.?)) { + if (payment.integration_status != .processed) + continue; + + if (payment.processed_by == 1) { + summary.default_total_payments_processed += 1; + summary.default_total_value += payment.amount; + } else { + summary.fallback_total_payments_processed += 1; + summary.fallback_total_value += payment.amount; + } + } + } + } else if (from != null) { + for (0..len) |i| { + const payment = self.payments[i]; + + if (payment.requested_at.gt(from.?)) { + if (payment.integration_status != .processed) + continue; + + if (payment.processed_by == 1) { + summary.default_total_payments_processed += 1; + summary.default_total_value += payment.amount; + } else { + summary.fallback_total_payments_processed += 1; + summary.fallback_total_value += payment.amount; + } + } + } + } else if (to != null) { + for (0..len) |i| { + const payment = self.payments[i]; + + if (payment.requested_at.lt(to.?)) { + if (payment.integration_status != .processed) + continue; + + if (payment.processed_by == 1) { + summary.default_total_payments_processed += 1; + summary.default_total_value += payment.amount; + } else { + summary.fallback_total_payments_processed += 1; + summary.fallback_total_value += payment.amount; + } + } + } + } else { + for (0..len) |i| { + const payment = self.payments[i]; + + if (payment.integration_status != .processed) + continue; + + if (payment.processed_by == 1) { + summary.default_total_payments_processed += 1; + summary.default_total_value += payment.amount; + } else { + summary.fallback_total_payments_processed += 1; + summary.fallback_total_value += payment.amount; + } + } + } + + return summary; + } + + fn hash(self: *PaymentsRepository, s: []const u8) usize { + std.debug.assert(self.max_indexes > 0); + return hash_map.hashString(s) % self.max_indexes; + } + + pub fn deinit(self: *PaymentsRepository) void { + self.mutex.lock(); + defer self.mutex.unlock(); + + for (self.indexes) |ic| { + @constCast(&ic).deinit(); + } + + self.allocator.free(self.indexes); + + self.len = 0; + self.database_size = 0; + self.max_indexes = 0; + + self.allocator.free(self.payments); + } +}; + +fn fakeGuid(end: u32) [36]u8 { + var guid: [36]u8 = .{0} ** 36; + + mem.writeInt(u32, guid[0..4], end, .little); + + return guid; +} + +test "expect add payment to index container" { + var index_container = try IndexContainerUnsafe.init(testing.allocator); + defer index_container.deinit(); + + const payment = Payment{ .id = fakeGuid(1), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }; + + try index_container.add(&payment); + try index_container.add(&payment); + try index_container.add(&payment); + try index_container.add(&payment); + + try expect(index_container.len == 4); +} + +test "expect find inserted payment" { + var index_container = try IndexContainerUnsafe.init(testing.allocator); + defer index_container.deinit(); + + try index_container.add(&Payment{ .id = fakeGuid(1), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }); + try index_container.add(&Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }); + try index_container.add(&Payment{ .id = fakeGuid(3), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }); + try index_container.add(&Payment{ .id = fakeGuid(4), .amount = 23.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }); + try index_container.add(&Payment{ .id = fakeGuid(5), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }); + + const payment_target = index_container.find(&fakeGuid(4)); + + try expect(payment_target.?.amount == 23.0); +} + +test "expect return null payment not exists" { + var index_container = try IndexContainerUnsafe.init(testing.allocator); + defer index_container.deinit(); + + try index_container.add(&Payment{ .id = fakeGuid(1), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }); + + const payment_target = index_container.find(&fakeGuid(4)); + + try expect(payment_target == null); +} + +test "expect allocate memory when container is full" { + const buffer: []u8 = try testing.allocator.alloc(u8, @sizeOf(*void) * 1000); + defer testing.allocator.free(buffer); + + var fba = heap.FixedBufferAllocator.init(buffer); + const allocator = fba.allocator(); + + var index_container = try IndexContainerUnsafe.init(allocator); + defer index_container.deinit(); + + for (0..923) |i| { + try (&index_container).add(&Payment{ .id = fakeGuid(@intCast(i)), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }); + } + + try expect(index_container.container_size == ((923 / CONTAINER_INCREASE_RATE) + 1) * CONTAINER_INCREASE_RATE); +} + +test "expect OutOfMemory error when allocator not has memory" { + const buffer: []u8 = try testing.allocator.alloc(u8, @sizeOf(*void) * 109); + defer testing.allocator.free(buffer); + + var fba = heap.FixedBufferAllocator.init(buffer); + const allocator = fba.allocator(); + + var index_container = try IndexContainerUnsafe.init(allocator); + defer index_container.deinit(); + + for (0..101) |i| { + (&index_container).add(&Payment{ .id = fakeGuid(@intCast(i)), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }) catch |err| { + try expect(err == Allocator.Error.OutOfMemory); + return; + }; + } + + try expect(false); +} + +test "expect insert payment into repository" { + var repository = try PaymentsRepository.init(testing.allocator, 100); + defer repository.deinit(); + + const payment1 = Payment{ .id = fakeGuid(1), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }; + const payment2 = Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }; + + try repository.insert(payment1); + try repository.insert(payment2); + + try expect(repository.len == 2); +} + +test "expect OutOfMemory error when database is full" { + var repository = try PaymentsRepository.init(testing.allocator, 100); + defer (&repository).deinit(); + + for (0..101) |i| { + const payment = Payment{ .id = fakeGuid(@intCast(i)), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }; + (&repository).insert(payment) catch |err| { + try expect(err == Allocator.Error.OutOfMemory); + return; + }; + } + + try expect(false); +} +test "expect return payment if exists" { + var repository: *PaymentsRepository = @constCast(&try PaymentsRepository.init(testing.allocator, 100)); + + defer repository.deinit(); + + try repository.insert(Payment{ .id = fakeGuid(1), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(3), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(23), .amount = 42.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(4), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(7), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(10), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + + const payment_result = repository.findById(&fakeGuid(23)); + + try expect(payment_result.?.amount == 42); +} + +test "expect return null if payment not exists" { + var repository: *PaymentsRepository = @constCast(&try PaymentsRepository.init(testing.allocator, 100)); + + defer repository.deinit(); + + try repository.insert(Payment{ .id = fakeGuid(1), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(3), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(23), .amount = 42.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(4), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(7), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(10), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + + const payment_result = repository.findById(&fakeGuid(42)); + + try expect(payment_result == null); +} + +fn testConcurrenceInsert(repository: *PaymentsRepository, interations: usize) !void { + for (0..interations) |i| { + try repository.insert(Payment{ .id = fakeGuid(@intCast(i)), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2011-10-05T14:48:00.000Z") }); + } +} + +fn testConcurrenceFind(repository: *PaymentsRepository, interations: usize) void { + for (0..interations) |i| { + _ = repository.findById(&fakeGuid(@intCast(i))); + } +} + +test "expect avoid concurrency" { + const interations = 100; + + const buffer: []u8 = try testing.allocator.alloc(u8, calculateNecessaryMemory(interations)); + defer testing.allocator.free(buffer); + + var fba = heap.FixedBufferAllocator.init(buffer); + const allocator = fba.allocator(); + + var repository: *PaymentsRepository = @constCast(&try PaymentsRepository.init(allocator, interations)); + defer repository.deinit(); + + const threadInsert1 = try Thread.spawn(.{}, testConcurrenceInsert, .{ repository, interations / 2 }); + const threadInsert2 = try Thread.spawn(.{}, testConcurrenceInsert, .{ repository, interations / 2 }); + const threadFind = try Thread.spawn(.{}, testConcurrenceFind, .{ repository, interations }); + + threadInsert1.join(); + threadInsert2.join(); + threadFind.join(); + + try expect(repository.len == interations); +} + +test "expect reset repository and indexes" { + var repository: *PaymentsRepository = @constCast(&try PaymentsRepository.init(testing.allocator, 100)); + + defer repository.deinit(); + + try repository.insert(Payment{ .id = fakeGuid(1), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(3), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(23), .amount = 42.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(4), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(7), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(10), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + + repository.reset(); + + try expect(repository.len == 0); + for (repository.indexes) |ic| { + try expect(ic.len == 0); + } +} + +test "expect summary return correct value" { + var repository = try PaymentsRepository.init(testing.allocator, 100); + defer repository.deinit(); + + try repository.insert(Payment{ .id = fakeGuid(1), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(3), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(23), .amount = 42.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(4), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(7), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(10), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.000Z") }); + + const summary = repository.periodSummary(null, null); + + try expect(summary.total_payments_processed == 7); + try expect(summary.total_value == 102.0); +} + +test "expect summary return correct value with filter from" { + var repository = try PaymentsRepository.init(testing.allocator, 100); + defer repository.deinit(); + + const from = try DateTime.ParseFromIso("2025-10-05T14:48:00.030Z"); + + try repository.insert(Payment{ .id = fakeGuid(1), .amount = 42.0, .requested_at = try DateTime.ParseFromIso("2024-10-05T13:47:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2024-10-05T14:48:00.033Z") }); + try repository.insert(Payment{ .id = fakeGuid(3), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-09-05T14:48:00.100Z") }); + try repository.insert(Payment{ .id = fakeGuid(4), .amount = 23.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.030Z") }); + try repository.insert(Payment{ .id = fakeGuid(7), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.100Z") }); + try repository.insert(Payment{ .id = fakeGuid(6), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:50:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(5), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-11-05T14:48:00.030Z") }); + + const summary = repository.periodSummary(from, null); + + try expect(summary.total_payments_processed == 4); + try expect(summary.total_value == 53.0); +} + +test "expect summary return correct correct value with filter to" { + var repository = try PaymentsRepository.init(testing.allocator, 100); + defer repository.deinit(); + + const to = try DateTime.ParseFromIso("2025-10-05T14:48:00.030Z"); + + try repository.insert(Payment{ .id = fakeGuid(1), .amount = 42.0, .requested_at = try DateTime.ParseFromIso("2024-10-05T13:47:00.000Z") }); // x + try repository.insert(Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2024-10-05T14:48:00.033Z") }); // x + try repository.insert(Payment{ .id = fakeGuid(3), .amount = 11.0, .requested_at = try DateTime.ParseFromIso("2025-09-05T14:48:00.100Z") }); // x + try repository.insert(Payment{ .id = fakeGuid(4), .amount = 23.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.030Z") }); // x + // + try repository.insert(Payment{ .id = fakeGuid(6), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:50:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(7), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.100Z") }); + try repository.insert(Payment{ .id = fakeGuid(5), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-11-05T14:48:00.030Z") }); + + const summary = repository.periodSummary(null, to); + + try expect(summary.total_payments_processed == 4); + try expect(summary.total_value == 86.0); +} + +test "expect summary return correct value with filter from and to" { + var repository = try PaymentsRepository.init(testing.allocator, 100); + defer repository.deinit(); + + const from = try DateTime.ParseFromIso("2025-10-05T14:48:00.030Z"); + const to = try DateTime.ParseFromIso("2025-10-05T14:48:00.100Z"); + + try repository.insert(Payment{ .id = fakeGuid(1), .amount = 42.0, .requested_at = try DateTime.ParseFromIso("2024-10-05T13:47:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(2), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2024-10-05T14:48:00.033Z") }); + try repository.insert(Payment{ .id = fakeGuid(3), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-09-05T14:48:00.100Z") }); + try repository.insert(Payment{ .id = fakeGuid(4), .amount = 23.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.030Z") }); // x + try repository.insert(Payment{ .id = fakeGuid(5), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-11-05T14:48:00.030Z") }); + try repository.insert(Payment{ .id = fakeGuid(6), .amount = 10.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:50:00.000Z") }); + try repository.insert(Payment{ .id = fakeGuid(7), .amount = 42.0, .requested_at = try DateTime.ParseFromIso("2025-10-05T14:48:00.100Z") }); // x + + const summary = repository.periodSummary(from, to); + + try expect(summary.total_payments_processed == 2); + try expect(summary.total_value == 65.0); +} diff --git a/src/endpoints/endpoints.zig b/src/endpoints/endpoints.zig new file mode 100644 index 0000000..730b44a --- /dev/null +++ b/src/endpoints/endpoints.zig @@ -0,0 +1,260 @@ +const std = @import("std"); +const http = std.http; + +const expect = std.testing.expect; +const expectEqualStrings = std.testing.expectEqualStrings; +const assert = std.debug.assert; + +const MAX_ENDPOINTS_PER_MANAGER: usize = 128; + +pub const ContentType = enum { none, json, html }; + +pub const Request = struct { + method: http.Method, + query: []const u8, + path: []const u8, + body: []const u8 = &.{}, + auth_header: ?[]const u8 = null, + content_type: ?[]const u8 = null, +}; + +pub const ChunkFunc = fn (self: *ChunkedContent) ?[]const u8; + +pub const ChunkedContent = struct { + next: *const ChunkFunc = undefined, + args: [64]u8 = undefined, + buffer_chunk: []u8, + index: usize = 0, +}; + +pub const Response = struct { + status: http.Status, + buffer_response: []u8, + extra_headers: [16]http.Header = undefined, + extra_headers_len: usize = 0, + + content_type: ?[]const u8 = null, + content: []const u8 = &.{}, + is_chunked: bool = false, + chunked_content: ChunkedContent, + + pub fn withContentFormat(self: *Response, comptime fmt: []const u8, args: anytype) !void { + self.content = try std.fmt.bufPrint(self.buffer_response, fmt, args); + } + + pub fn withStatus(self: *Response, status: http.Status) *Response { + self.status = status; + return self; + } + + pub fn withContent(self: *Response, content: []const u8) *Response { + self.content = content; + return self; + } + + pub fn withContentType(self: *Response, content_type: ContentType) *Response { + self.content_type = switch (content_type) { + .json => "application/json", + .html => "text/html", + .none => &.{}, + }; + + return self; + } + + pub fn getExtraHeaders(self: *Response) []http.Header { + var headers = &self.extra_headers; + var i: usize = self.extra_headers_len; + + if (self.content_type != null) { + headers[i].name = "Content-Type"; + headers[i].value = self.content_type.?; + i += 1; + self.extra_headers_len += 1; + } + + return headers[0..i]; + } + + pub fn setChunkedResponse(self: *Response, args: anytype, callback: *const ChunkFunc) void { + const args_as_bytes = std.mem.asBytes(args); + + assert(self.chunked_content.args.len >= args_as_bytes.len); + + std.mem.copyForwards(u8, &self.chunked_content.args, args_as_bytes); + + self.chunked_content.next = callback; + self.is_chunked = true; + } + + pub fn end(_: *Response) void {} +}; + +pub const EndpointFunction = fn (req: *Request, res: *Response) void; + +pub inline fn removeEndBackslash(p: []const u8) []const u8 { + return if (p.len > 0 and p[p.len - 1] == '/') p[0 .. p.len - 1] else p; +} + +const Endpoint = struct { + path: []const u8, + function: *const EndpointFunction, + + pub fn match(self: Endpoint, target: []const u8) bool { + const target_no_backslash = removeEndBackslash(target); + + const plen = self.path.len; + const tlen = target_no_backslash.len; + + if (plen > 0 and self.path[plen - 1] == '*') + return tlen >= plen and std.mem.eql(u8, self.path[0 .. plen - 1], target_no_backslash[0 .. plen - 1]); + + return std.mem.eql(u8, self.path, target_no_backslash); + } +}; + +const EndpointManagerError = error{EndpointsLimitReached}; + +pub const EndpointsManager = struct { + endpoints: [MAX_ENDPOINTS_PER_MANAGER]Endpoint = undefined, + endpoints_len: usize = 0, + + pub fn add(self: *EndpointsManager, path: []const u8, function: *const EndpointFunction) EndpointManagerError!void { + if (self.endpoints_len >= MAX_ENDPOINTS_PER_MANAGER) { + return EndpointManagerError.EndpointsLimitReached; + } + + self.endpoints[self.endpoints_len].function = function; + self.endpoints[self.endpoints_len].path = removeEndBackslash(path); + self.endpoints_len += 1; + } + + pub fn getEndpointFunction(self: *EndpointsManager, target: []const u8) ?*const EndpointFunction { + for (0..self.endpoints_len) |i| { + const endpoint = self.endpoints[i]; + + if (endpoint.match(target)) { + return endpoint.function; + } + } + + return null; + } +}; + +fn testEndpointFunctionOk(_: *Request, res: *Response) void { + res.status = .ok; + res.content = "endpoint ok"; +} + +fn testEndpointFunctionNok(_: *Request, res: *Response) void { + res.status = .bad_request; + res.content = "endpoint nok"; +} + +test "expect add endpiont increase endpoints_len" { + var manager = EndpointsManager{}; + try manager.add("/", testEndpointFunctionOk); + try manager.add("/index", testEndpointFunctionOk); + + try expect(manager.endpoints_len == 2); +} + +test "expect overflow error when endpoints limit arrive" { + var manager = EndpointsManager{}; + + const path: []const u8 = "/"; + + for (0..MAX_ENDPOINTS_PER_MANAGER + 1) |_| { + manager.add(path, testEndpointFunctionOk) catch |err| { + try expect(err == EndpointManagerError.EndpointsLimitReached); + }; + } +} + +test "expect endpoint path match with target" { + const target = "/path"; + var endpoint = Endpoint{ .function = testEndpointFunctionOk, .path = "/path" }; + + try expect(endpoint.match(target)); +} + +test "expect endpoint path match with target with end backlash" { + const target = "/path"; + var endpoint = Endpoint{ .function = testEndpointFunctionOk, .path = "/path" }; + + try expect(endpoint.match(target)); +} + +test "expect endpoint path match with target using pattern" { + const target = "/path/teste"; + var endpoint = Endpoint{ .function = testEndpointFunctionOk, .path = "/path/*" }; + + try expect(endpoint.match(target)); +} + +test "expect endpoint_manager return null if none endpoint match with target" { + var manager = EndpointsManager{}; + try manager.add("/", testEndpointFunctionOk); + try manager.add("/index", testEndpointFunctionOk); + try manager.add("/path", testEndpointFunctionOk); + + try expect(manager.getEndpointFunction("/nopath") == null); +} + +test "expect endpoint_manager return the correct function to target" { + var manager = EndpointsManager{}; + try manager.add("/", testEndpointFunctionNok); + try manager.add("/index", testEndpointFunctionNok); + try manager.add("/path", testEndpointFunctionNok); + try manager.add("/my/path", testEndpointFunctionNok); + try manager.add("/my/path/*", testEndpointFunctionOk); + + const req = Request{ .path = "/my/path/jesus", .query = "", .body = "", .method = .GET }; + var res = Response{ + .status = .internal_server_error, + .buffer_response = &.{}, + .chunked_content = .{ .buffer_chunk = &.{} }, + }; + + const func_e = manager.getEndpointFunction(req.path); + + try expect(func_e != null); + + func_e.?(@constCast(&req), &res); + + try expect(std.mem.eql(u8, res.content, "endpoint ok")); +} + +const ChunkArgs = struct { arg1: u64, arg2: u32 }; +fn testChunkFunc(self: *ChunkedContent) ?[]const u8 { + const myargs: *ChunkArgs = @ptrCast(@alignCast(&self.args)); + const args: [2]u64 = .{ myargs.arg1, myargs.arg2 }; + + for (args[self.index..]) |v| { + self.index += 1; + return std.fmt.bufPrint(self.buffer_chunk, "Arg {d}", .{v}) catch { + return "error!"; + }; + } + + return null; +} + +test "expect chunk function return correct chunk response" { + var buf: [32]u8 = undefined; + + var res = Response{ + .status = .internal_server_error, + .buffer_response = &buf, + .chunked_content = .{ .buffer_chunk = &buf }, + }; + + const args = ChunkArgs{ .arg1 = 23, .arg2 = 42 }; + + res.setChunkedResponse(&args, &testChunkFunc); + + try expectEqualStrings(res.chunked_content.next(&res.chunked_content).?, "Arg 23"); + try expectEqualStrings(res.chunked_content.next(&res.chunked_content).?, "Arg 42"); + try expect(res.chunked_content.next(&res.chunked_content) == null); +} diff --git a/src/endpoints/main.zig b/src/endpoints/main.zig new file mode 100644 index 0000000..a428898 --- /dev/null +++ b/src/endpoints/main.zig @@ -0,0 +1,14 @@ +const std = @import("std"); + +const endpoints = @import("endpoints.zig"); + +pub const EndpointsManager = endpoints.EndpointsManager; +pub const Request = endpoints.Request; +pub const Response = endpoints.Response; + +pub const root = @import("root.zig"); +pub const payments = @import("payments.zig"); + +test { + std.testing.refAllDecls(@This()); +} diff --git a/src/endpoints/payments.zig b/src/endpoints/payments.zig new file mode 100644 index 0000000..2cd51fb --- /dev/null +++ b/src/endpoints/payments.zig @@ -0,0 +1,135 @@ +const endpoints = @import("endpoints.zig"); + +const EndpointsManager = endpoints.EndpointsManager; +const Request = endpoints.Request; +const Response = endpoints.Response; + +const data = @import("data"); +const Payment = data.payments.Payment; +const PaymentsRepository = data.payments.PaymentsRepository; + +const std = @import("std"); +const ctx = @import("context"); +const parses = @import("parses"); +const PropertySpec = @import("parses").PropertySpec; +const DateTime = @import("things").DateTime; + +pub fn registerEndpoints(get_endpoints: *EndpointsManager, post_endpoints: *EndpointsManager) !void { + // GET + try get_endpoints.add("/payments-summary", getSummary); + try get_endpoints.add("/payments/*", getPaymentsById); + + // POST + try post_endpoints.add("/payments", postPayments); +} + +fn postPayments(req: *Request, res: *Response) void { + if (ctx.server_settings.failure) + return res.withStatus(.service_unavailable).end(); + + if (ctx.server_settings.delay > 0) { + std.time.sleep(ctx.server_settings.delay * std.time.ns_per_ms); + } + + res.withStatus(.unprocessable_entity).withContentType(.json).end(); + + var prop_correlationId = parses.PropertySpec{ .name = "correlationId" }; + var prop_amount = parses.PropertySpec{ .name = "amount" }; + + parses.json(req.body, .{ .properties = &.{ &prop_correlationId, &prop_amount } }) catch { + return; + }; + + const payment = Payment{ .id = prop_correlationId.asUuid() catch { + return res.withContent("{ \"correlationId\" : \"invalid\" }").end(); + }, .amount = prop_amount.asFloat(f64) catch { + return res.withContent("{ \"amount\" : \"invalid\" }").end(); + }, .requested_at = DateTime.now() }; + + ctx.payments_repository.insert(payment) catch { + return res.withStatus(.internal_server_error).end(); + }; + + res.withStatus(.created).withContent("confia que vai ser integrado.").withContentType(.html).end(); +} + +fn getPaymentsById(req: *Request, res: *Response) void { + if (ctx.server_settings.failure) + return res.withStatus(.service_unavailable).end(); + + if (ctx.server_settings.delay > 0) { + std.time.sleep(ctx.server_settings.delay * std.time.ns_per_ms); + } + + const template_json_res: []const u8 = + \\{{ + \\ "correlationId": "{s}", + \\ "amount": {d:.2}, + \\ "requestedAt" : "{s}", + \\ "integration_status" : "{s}" + \\}} + ; + + res.withStatus(.not_found).end(); + + if (req.path.len < 36) { + return; + } + + const id = req.path[req.path.len - 36 ..]; + + const payment = ctx.payments_repository.findById(id); + + if (payment == null) return; + + const dateIso = payment.?.requested_at.toIso(); + + res.withContentFormat(template_json_res, .{ payment.?.id, payment.?.amount, dateIso, payment.?.getIntegrationStatus() }) catch { + return res.withStatus(.internal_server_error).end(); + }; + + res.withStatus(.ok).withContentType(.json).end(); +} + +const template_json_summary: []const u8 = + \\{{ + \\ "default": {{ "totalRequests": "{d}", "totalAmount": {d:.2} }}, + \\ "fallback": {{ "totalRequests": "{d}", "totalAmount": {d:.2} }} + \\}} +; + +fn getSummary(req: *Request, res: *Response) void { + var from: ?DateTime = null; + var to: ?DateTime = null; + + var prop_from = PropertySpec{ .name = "from" }; + var prop_to = PropertySpec{ .name = "to" }; + parses.url_params(req.query, .{ .properties = &.{ &prop_from, &prop_to } }); + + if (prop_from.value_dirty != null) + from = prop_from.asDateTime() catch { + return res.withStatus(.bad_request).withContent("query param 'from' is invalid").withContentType(.html).end(); + }; + + if (prop_to.value_dirty != null) + to = prop_to.asDateTime() catch { + return res.withStatus(.bad_request).withContent("query param 'to' is invalid").withContentType(.html).end(); + }; + + var summary = ctx.payments_repository.integrationSummary(from, to); + + const cousin_summary = ctx.summary_exchange.receive(from, to); + summary.default_total_payments_processed += cousin_summary.default_total_payments_processed; + summary.default_total_value += cousin_summary.default_total_value; + summary.fallback_total_payments_processed += cousin_summary.fallback_total_payments_processed; + summary.fallback_total_value += cousin_summary.fallback_total_value; + + res.withStatus(.ok).withContentType(.json).withContentFormat(template_json_summary, .{ + summary.default_total_payments_processed, + summary.default_total_value, + summary.fallback_total_payments_processed, + summary.fallback_total_value, + }) catch { + return res.withStatus(.internal_server_error).withContentType(.none).end(); + }; +} diff --git a/src/endpoints/root.zig b/src/endpoints/root.zig new file mode 100644 index 0000000..b1072ef --- /dev/null +++ b/src/endpoints/root.zig @@ -0,0 +1,39 @@ +const endpoints = @import("endpoints.zig"); + +const EndpointsManager = endpoints.EndpointsManager; +const Request = endpoints.Request; +const Response = endpoints.Response; + +const std = @import("std"); +const ctx = @import("context"); + +pub fn registerEndpoints(get_endpoints: *EndpointsManager) !void { + try get_endpoints.add("/", getRoot); +} + +fn getRoot(_: *Request, res: *Response) void { + const base_welcome_message: []const u8 = + \\ + \\ + \\ + \\ + \\ {s} + \\ + \\ + \\ + \\ + \\
+ \\

Welcome to fastest payment process

+ \\
+ \\ + \\ + ; + + res.withContentFormat(base_welcome_message, .{ctx.config.name}) catch { + res.withStatus(.internal_server_error).end(); + }; + + res.withStatus(.ok).withContentType(.html).end(); +} diff --git a/src/exchange/exchange_connection.zig b/src/exchange/exchange_connection.zig new file mode 100644 index 0000000..85945b2 --- /dev/null +++ b/src/exchange/exchange_connection.zig @@ -0,0 +1,132 @@ +const std = @import("std"); +const net = std.net; +const heap = std.heap; +const Thread = std.Thread; + +const log = std.log; + +const Address = net.Address; + +const Allocator = std.mem.Allocator; + +const testing = std.testing; +const expect = testing.expect; + +const FakeStream = @import("helpers").FakeStream; +const is_test = @import("builtin").is_test; + +const ExchangeConnectionStatus = enum { waiting, trying, active, dead }; + +pub const ExchangeConnection = struct { + in_address: Address, + out_address: Address, + in: if (is_test) *FakeStream else net.Stream = undefined, + out: if (is_test) *FakeStream else net.Stream = undefined, + server_status: ExchangeConnectionStatus = .waiting, + out_status: ExchangeConnectionStatus = .trying, + listen_thread: Thread = undefined, + + pub fn init(host: []const u8, port: u16) !ExchangeConnection { + var buf: [1024]u8 = undefined; + var pba = heap.FixedBufferAllocator.init(&buf); + + const addrList = try net.getAddressList(pba.allocator(), host, port); + defer addrList.deinit(); + + var final_addr: ?Address = null; + for (addrList.addrs) |addr| { + final_addr = addr; + } + + const in_address = Address.initIp4(.{ 0, 0, 0, 0 }, port); + + return ExchangeConnection{ + .out_address = final_addr.?, + .in_address = in_address, + }; + } + + pub fn start(self: *ExchangeConnection) void { + self.listen_thread = Thread.spawn(.{ .stack_size = 1024 * 16 }, ExchangeConnection.listen, .{self}) catch |err| { + log.err("Was not possible thread secret connection listen {any}", .{err}); + unreachable; + }; + + _ = Thread.spawn(.{ .stack_size = 1024 * 16 }, ExchangeConnection.tryConnectOut, .{self}) catch |err| { + log.err("Was not possible create thread tryConenctOut {any}", .{err}); + unreachable; + }; + } + + pub fn tryConnectOut(self: *ExchangeConnection) void { + if (is_test) { + return; + } + + for (0..10) |_| { + Thread.sleep(1_000_000 * 1000); + + self.out = net.tcpConnectToAddress(self.out_address) catch |err| { + log.err("Error connect to secret server {any}", .{err}); + continue; + }; + + self.out_status = .active; + return; + } + } + + fn listen(self: *ExchangeConnection) void { + if (is_test) { + return; + } + + std.debug.print("Listening ...\n", .{}); + + for (0..10) |_| { + var server = self.in_address.listen(.{ .kernel_backlog = 1 }) catch |err| { + log.err("Error starting secret server connection {any}", .{err}); + continue; + }; + + while (true) { + const server_conn = server.accept() catch |err| { + log.err("Error when accepting connection secret server {any}", .{err}); + self.server_status = .waiting; + break; + }; + + self.server_status = .active; + self.in = server_conn.stream; + } + + server.deinit(); + + Thread.sleep(1_000_000 * 1000); + } + + self.server_status = .dead; + } +}; + +test "expect create a secret connection" { + const conn = try ExchangeConnection.init("uchoamp.dev", 80); + + try expect(conn.in_address.getPort() == 80); +} + +//test "expect start secret connection" { +// var conn1 = try ExchangeConnection.init("localhost", 5002); +// conn1.out_address.setPort(2323); +// +// conn1.start(); +// +// //_ = try conn1.out.write("hello!\r\n"); +// //Thread.sleep(1_000_000 * 1000 * 10); +// conn1.listen_thread.join(); +// +// var buf: [100]u8 = undefined; +// try expect(conn1.server_status == .active); +// const size = try conn1.in.read(&buf); +// std.debug.print("Secret conn response: {s}", .{buf[0..size]}); +//} diff --git a/src/exchange/main.zig b/src/exchange/main.zig new file mode 100644 index 0000000..3b29bb1 --- /dev/null +++ b/src/exchange/main.zig @@ -0,0 +1,8 @@ +const std = @import("std"); + +pub const ExchangeConnection = @import("exchange_connection.zig").ExchangeConnection; +pub const PaymentSummaryExchange = @import("payment_summary_exchange.zig").PaymentSummaryExchange; + +test { + std.testing.refAllDecls(@This()); +} diff --git a/src/exchange/payment_summary_exchange.zig b/src/exchange/payment_summary_exchange.zig new file mode 100644 index 0000000..0293e3f --- /dev/null +++ b/src/exchange/payment_summary_exchange.zig @@ -0,0 +1,260 @@ +const std = @import("std"); +const log = std.log; +const Thread = std.Thread; +const is_test = @import("builtin").is_test; +const testing = std.testing; +const expect = testing.expect; + +const FakeStram = @import("helpers").FakeStream; + +const things = @import("things"); + +const DateTime = things.DateTime; + +const data = @import("data"); +const ExchangeConnection = @import("exchange_connection.zig").ExchangeConnection; + +const PaymentsRepository = data.payments.PaymentsRepository; +const Payment = data.payments.Payment; +const PaymentsIntegrationSummary = data.payments.PaymentsIntegrationSummary; + +const REQUEST_SIZE = @sizeOf(?DateTime) * 2; +const RESPONSE_SIZE = @sizeOf(PaymentsIntegrationSummary); + +pub const PaymentSummaryExchange = struct { + payment_repository: *PaymentsRepository, + exchange_connection: *ExchangeConnection, + + pub fn init(payment_repository: *PaymentsRepository, exchange_connection: *ExchangeConnection) PaymentSummaryExchange { + return PaymentSummaryExchange{ + .payment_repository = payment_repository, + .exchange_connection = exchange_connection, + }; + } + + pub fn start(self: *PaymentSummaryExchange) void { + self.exchange_connection.start(); + _ = Thread.spawn(.{ .stack_size = 1024 * 16 }, PaymentSummaryExchange.give, .{self}) catch |err| { + log.err("Was not possible create thread to give {any}", .{err}); + unreachable; + }; + } + + pub fn give(self: *PaymentSummaryExchange) void { + var buf: [REQUEST_SIZE]u8 = undefined; + var conn = self.exchange_connection; + + while (true) { + while (conn.server_status == .active) { + const size = conn.in.readAtLeast(&buf, buf.len) catch 0; + + if (size == 0) { + conn.server_status = .waiting; + conn.in.close(); + break; + } + + var summary = self.getPaymentSummary(&buf); + const summary_as_bytes = std.mem.asBytes(&summary); + + _ = conn.in.writeAll(summary_as_bytes) catch { + conn.server_status = .waiting; + conn.in.close(); + break; + }; + + if (is_test) { + return; + } + } + + Thread.sleep(1_000_000 * 1000 * 5); + } + } + + fn getPaymentSummary(self: *PaymentSummaryExchange, payload: []u8) PaymentsIntegrationSummary { + const from: *?DateTime = @ptrCast(@alignCast(payload[0..@sizeOf(?DateTime)])); + const to: *?DateTime = @ptrCast(@alignCast(payload[@sizeOf(?DateTime)..])); + + return self.payment_repository.integrationSummary(from.*, to.*); + } + + pub fn receive(self: *PaymentSummaryExchange, from: ?DateTime, to: ?DateTime) PaymentsIntegrationSummary { + const conn = self.exchange_connection; + + blk: { + if (conn.out_status != .active) { + break :blk; + } + + var payload: [REQUEST_SIZE]u8 = undefined; + var buf_res: [RESPONSE_SIZE]u8 = undefined; + @memcpy(payload[0 .. REQUEST_SIZE / 2], std.mem.asBytes(&from)); + @memcpy(payload[REQUEST_SIZE / 2 ..], std.mem.asBytes(&to)); + + conn.out.writeAll(&payload) catch { + break :blk; + }; + + const size_read: usize = conn.out.readAtLeast(&buf_res, buf_res.len) catch 0; + if (size_read == 0) { + break :blk; + } + + const summary: *PaymentsIntegrationSummary = @ptrCast(@alignCast(&buf_res)); + + return summary.*; + } + + if (conn.out_status == .active) { + conn.out.close(); + conn.out_status = .dead; + } + + return PaymentsIntegrationSummary{ + .default_total_payments_processed = 0, + .default_total_value = 0.0, + .fallback_total_payments_processed = 0, + .fallback_total_value = 0.0, + }; + } +}; + +fn initAndPopulateRepository() !PaymentsRepository { + var repository = try PaymentsRepository.init(testing.allocator, 100); + + const payment_1 = Payment{ + .id = .{'a'} ** 36, + .amount = 23, + .requested_at = try DateTime.ParseFromIso("2025-08-07T11:00:00.000Z"), + .integration_status = .processed, + .processed_by = 1, + }; + + const payment_2 = Payment{ + .id = .{'a'} ** 36, + .amount = 10, + .requested_at = try DateTime.ParseFromIso("2025-08-07T11:00:00.101Z"), + .integration_status = .processed, + .processed_by = 1, + }; + + const payment_3 = Payment{ + .id = .{'a'} ** 36, + .amount = 15, + .requested_at = try DateTime.ParseFromIso("2025-08-06T00:00:00.000Z"), + .integration_status = .processed, + .processed_by = 2, + }; + + try repository.insert(payment_1); + try repository.insert(payment_2); + try repository.insert(payment_3); + + return repository; +} + +test "expect give full summary when no date" { + var repository = try initAndPopulateRepository(); + defer repository.deinit(); + + var conn = try ExchangeConnection.init("uchoamp.dev", 80); + var exchange = PaymentSummaryExchange.init(&repository, &conn); + var buf: [REQUEST_SIZE]u8 = .{0} ** REQUEST_SIZE; + + const summary = exchange.getPaymentSummary(&buf); + + try expect(summary.default_total_payments_processed == 2); + try expect(summary.default_total_value == 33); + try expect(summary.fallback_total_payments_processed == 1); + try expect(summary.fallback_total_value == 15); +} + +test "expect summary with only payments after from date" { + var repository = try initAndPopulateRepository(); + defer repository.deinit(); + + var conn = try ExchangeConnection.init("uchoamp.dev", 80); + var exchange = PaymentSummaryExchange.init(&repository, &conn); + var buf: [REQUEST_SIZE]u8 = .{0} ** REQUEST_SIZE; + + const from: *?DateTime = @ptrCast(@alignCast(buf[0..@sizeOf(?DateTime)])); + from.* = try DateTime.ParseFromIso("2025-08-07T00:00:00.000Z"); + + const summary = exchange.getPaymentSummary(&buf); + + try expect(summary.default_total_payments_processed == 2); + try expect(summary.default_total_value == 33); + try expect(summary.fallback_total_payments_processed == 0); + try expect(summary.fallback_total_value == 0); +} + +test "expect receive return the correct summary" { + var fake_stream_buf: [1024]u8 = undefined; + var fake_stream = FakeStram.init(&fake_stream_buf); + + var repository = try initAndPopulateRepository(); + defer repository.deinit(); + + var conn = try ExchangeConnection.init("uchoamp.dev", 80); + conn.in = &fake_stream; + conn.out = &fake_stream; + + var exchange = PaymentSummaryExchange.init(&repository, &conn); + var buf: [REQUEST_SIZE]u8 = .{0} ** REQUEST_SIZE; + + const from: *?DateTime = @ptrCast(@alignCast(buf[0..@sizeOf(?DateTime)])); + from.* = try DateTime.ParseFromIso("2025-08-07T11:00:00.000Z"); + const to: *?DateTime = @ptrCast(@alignCast(buf[@sizeOf(?DateTime)..])); + to.* = try DateTime.ParseFromIso("2025-08-07T11:00:00.100Z"); + + _ = try fake_stream.write(&buf); + + conn.server_status = .active; + exchange.give(); + + fake_stream.not_write = true; + + conn.out_status = .active; + const summary = exchange.receive(from.*, to.*); + + try expect(summary.default_total_payments_processed == 1); + try expect(summary.default_total_value == 23); + try expect(summary.fallback_total_payments_processed == 0); + try expect(summary.fallback_total_value == 0); +} + +test "expect receive return summary with zeros if connection error" { + var fake_stream_buf: [1024]u8 = undefined; + var fake_stream = FakeStram.init(&fake_stream_buf); + + var repository = try initAndPopulateRepository(); + defer repository.deinit(); + + var conn = try ExchangeConnection.init("uchoamp.dev", 80); + conn.in = &fake_stream; + conn.out = &fake_stream; + + var exchange = PaymentSummaryExchange.init(&repository, &conn); + var buf: [REQUEST_SIZE]u8 = .{0} ** REQUEST_SIZE; + + const from: *?DateTime = @ptrCast(@alignCast(buf[0..@sizeOf(?DateTime)])); + from.* = try DateTime.ParseFromIso("2025-08-07T11:00:00.000Z"); + const to: *?DateTime = @ptrCast(@alignCast(buf[@sizeOf(?DateTime)..])); + to.* = try DateTime.ParseFromIso("2025-08-07T11:00:00.100Z"); + + _ = try fake_stream.write(&buf); + + conn.server_status = .active; + exchange.give(); + + fake_stream._error = true; + + conn.out_status = .active; + const summary = exchange.receive(from.*, null); + + try expect(summary.default_total_payments_processed == 0); + try expect(summary.default_total_value == 0); + try expect(summary.fallback_total_payments_processed == 0); + try expect(summary.fallback_total_value == 0); +} diff --git a/src/helpers/fake_stream.zig b/src/helpers/fake_stream.zig new file mode 100644 index 0000000..7e6e8f5 --- /dev/null +++ b/src/helpers/fake_stream.zig @@ -0,0 +1,79 @@ +const std = @import("std"); + +pub const FakeStream = struct { + buffer: []u8, + write_pos: usize = 0, + read_pos: usize = 0, + _error: bool = false, + not_write: bool = false, + + const Error = error{GenericError}; + + pub fn init(buf: []u8) FakeStream { + return FakeStream{ .buffer = buf }; + } + + pub fn read(self: *FakeStream, buf: []u8) FakeStream.Error!usize { + if (self._error) { + return Error.GenericError; + } + + const size = @min(buf.len, self.write_pos - self.read_pos); + + @memcpy(buf[0..size], self.buffer[self.read_pos .. self.read_pos + size]); + + self.read_pos += size; + + return size; + } + + pub fn write(self: *FakeStream, buf: []const u8) FakeStream.Error!usize { + if (self._error) { + return Error.GenericError; + } + + if (self.not_write) { + return buf.len; + } + + const size = @min(buf.len, self.buffer.len - self.write_pos); + @memcpy(self.buffer[self.write_pos .. self.write_pos + size], buf[0..size]); + + self.write_pos += size; + + return size; + } + + pub fn readAtLeast(self: *FakeStream, buf: []u8, len: usize) FakeStream.Error!usize { + if (self._error) { + return Error.GenericError; + } + + if (self.write_pos < len or buf.len < len) { + unreachable; + } + + @memcpy(buf[0..len], self.buffer[self.read_pos .. self.read_pos + len]); + + self.read_pos += len; + + return len; + } + + pub fn writeAll(self: *FakeStream, buf: []const u8) FakeStream.Error!void { + if (self._error) { + return Error.GenericError; + } + + if (self.not_write) { + return; + } + + const size = @min(buf.len, self.buffer.len - self.write_pos); + @memcpy(self.buffer[self.write_pos .. self.write_pos + size], buf[0..size]); + + self.write_pos += size; + } + + pub fn close(_: *FakeStream) void {} +}; diff --git a/src/helpers/main.zig b/src/helpers/main.zig new file mode 100644 index 0000000..1398d7d --- /dev/null +++ b/src/helpers/main.zig @@ -0,0 +1 @@ +pub const FakeStream = @import("fake_stream.zig").FakeStream; diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..938e6d0 --- /dev/null +++ b/src/main.zig @@ -0,0 +1,56 @@ +const std = @import("std"); + +const endpoints = @import("endpoints"); +pub const ctx = @import("context"); +const sec = @import("security"); + +const services = @import("services"); +const HttpService = services.HttpService; + +const server = @import("server.zig"); +const PaymentIntegrator = @import("payment_integrator.zig").PaymentIntegrator; + +pub fn main() !void { + var get_endpoints = endpoints.EndpointsManager{}; + var post_endpoints = endpoints.EndpointsManager{}; + var put_endpoints = endpoints.EndpointsManager{}; + + try ctx.init(); + defer ctx.deinit(); + sec.updateToken(ctx.config.initial_token); + + try endpoints.payments.registerEndpoints(&get_endpoints, &post_endpoints); + + var default_service = try HttpService.init(1, "default", ctx.config.default_host, ctx.config.default_port, ctx.config.default_pool, std.heap.page_allocator); + var fallback_service = try HttpService.init(2, "fallback", ctx.config.fallback_host, ctx.config.fallback_port, ctx.config.fallback_pool, std.heap.page_allocator); + var service_pool = services.ServicePool{}; + + defer default_service.deinit(); + defer fallback_service.deinit(); + + try service_pool.add(&default_service); + try service_pool.add(&fallback_service); + + var integrator = PaymentIntegrator.init(&service_pool); + try default_service.start(); + try fallback_service.start(); + try integrator.start(); + + ctx.payments_repository.subscribeInsert(&PaymentIntegrator.newPaymentEvent); + + var ip_map: []const u8 = "127.0.0.1"; + + if (ctx.config.env == .PROD) + ip_map = "0.0.0.0"; + + std.log.info("Server Enviroment: {}\n", .{ctx.config.env}); + + var myserver = try server.HttpServer.init(ip_map, ctx.config.port, &get_endpoints, &post_endpoints, &put_endpoints); + + std.Thread.sleep(1_000_000 * 1000 * 4); + try myserver.start(); +} + +test { + std.testing.refAllDecls(@This()); +} diff --git a/src/parses/json.zig b/src/parses/json.zig new file mode 100644 index 0000000..26a7718 --- /dev/null +++ b/src/parses/json.zig @@ -0,0 +1,205 @@ +const std = @import("std"); +const assert = std.debug.assert; +const mem = std.mem; +const fmt = std.fmt; +const eql = std.mem.eql; + +const specs = @import("specs.zig"); +const PropertySpec = specs.PropertySpec; +const EntitySpecs = specs.EntitySpecs; +const PropertySpecError = specs.PropertySpecError; + +const utils = @import("utils.zig"); +const ParseStack = utils.ParseStack; +const ParseStackError = utils.ParseStackError; + +pub const JsonParseError = error{InvalidJson} || ParseStackError; + +inline fn validEndValue(d: u8) bool { + return (d == '"' or d == '\'' or d == 'l' or d == 'e' or (d >= '0' and d <= '9')); +} + +pub fn parseMemO1(src: []const u8, entity_specs: EntitySpecs) JsonParseError!void { + var stack = ParseStack{}; + + var current_prop: ?*PropertySpec = null; + + var i_begin: ?usize = null; + + var escape_next = false; + var tracking_string = false; + var tracking_value = false; + + for (0..src.len) |i| { + if (escape_next) { + escape_next = false; + continue; + } + + switch (src[i]) { + '\n', '\t', '\r', ' ' => { + if (tracking_string) + continue; + + if (i_begin != null and current_prop != null) { + current_prop.?.value_dirty = src[i_begin.?..i]; + current_prop = null; + } + }, + '\\' => { + escape_next = true; + }, + '{', ':' => |v| { + if (tracking_string) + continue; + + tracking_value = ':' == v; + try stack.push(v); + }, + ',', '}' => |v| { + if (tracking_string) + continue; + + const stack_pop = stack.pop(); + + if (v == ',' and (stack_pop != ':' or !validEndValue(src[i - 1]))) { + return JsonParseError.InvalidJson; + } else if (v == '}' and ((stack_pop != ':' and stack_pop != '{') or (stack_pop == ':' and stack.pop() != '{'))) { + return JsonParseError.InvalidJson; + } + + if (i_begin != null and current_prop != null) { + current_prop.?.value_dirty = src[i_begin.?..i]; + current_prop = null; + } + + i_begin = null; + + tracking_value = false; + }, + '"', '\'' => |v| { + if (stack.peek() == v) { + _ = stack.pop(); + + if (!tracking_value) { + current_prop = entity_specs.findPropertySpec(src[i_begin.?..i]); + } else if (current_prop != null) { + current_prop.?.value_dirty = src[i_begin.?..i]; + current_prop = null; + } + + tracking_string = false; + i_begin = null; + } else if (!tracking_string) { + tracking_string = true; + i_begin = i + 1; + + try stack.push(v); + } + }, + '0'...'9', 'n', 't', 'f' => { + if (i_begin != null) + continue; + + if (stack.peek() != ':') + return JsonParseError.InvalidJson; + + i_begin = i; + }, + else => continue, + } + } + + if (stack.len > 0) + return JsonParseError.InvalidJson; +} + +test "expect simple json parse" { + const src = + \\{ "prop": "white space" } + ; + + var prop = PropertySpec{ .name = "prop" }; + var props = [_]*PropertySpec{&prop}; + const entity_specs = EntitySpecs{ .properties = &props }; + + try parseMemO1(src, entity_specs); + + assert(eql(u8, prop.value_dirty.?, "white space")); +} + +test "expect parse multi prop json" { + const src = + \\{ + \\ "correlationId": "4a7901b8-7d26-4d9d-aa19-4dc1c7cf60b3", + \\ "amount": 19.90, + \\ "requestedAt" : "2025-07-15T12:34:56.000Z", + \\ "nullField" : null, + \\ "isRequest" : true, + \\ "isExpensive" : false + \\} + ; + + var prop_correlationId = PropertySpec{ .name = "correlationId" }; + var prop_amount = PropertySpec{ .name = "amount" }; + var prop_requestedAt = PropertySpec{ .name = "requestedAt" }; + var prop_isExpensive = PropertySpec{ .name = "isExpensive" }; + + const entity_specs = EntitySpecs{ .properties = &[_]*PropertySpec{ &prop_correlationId, &prop_amount, &prop_requestedAt, &prop_isExpensive } }; + + try parseMemO1(src, entity_specs); + + assert(eql(u8, prop_correlationId.value_dirty.?, "4a7901b8-7d26-4d9d-aa19-4dc1c7cf60b3")); + assert(eql(u8, prop_amount.value_dirty.?, "19.90")); + assert(eql(u8, prop_requestedAt.value_dirty.?, "2025-07-15T12:34:56.000Z")); + assert(prop_isExpensive.value_dirty.?.len == 5); +} + +test "expect parse empty json" { + const src = + \\{ + \\} + ; + + const entity_specs = EntitySpecs{ .properties = &[_]*PropertySpec{} }; + + try parseMemO1(src, entity_specs); +} + +test "expect InvalidJson when name is not string" { + const src = + \\{ + \\ notstring: 10 + \\} + ; + + var prop_amount = PropertySpec{ .name = "amount" }; + + const entity_specs = EntitySpecs{ .properties = &[_]*PropertySpec{&prop_amount} }; + + parseMemO1(src, entity_specs) catch |err| { + assert(err == JsonParseError.InvalidJson); + return; + }; + + assert(false); +} + +test "expect InvalidJson when value is not valid" { + const src = + \\{ + \\ "amount": invalid, + \\} + ; + + var prop_amount = PropertySpec{ .name = "amount" }; + + const entity_specs = EntitySpecs{ .properties = &[_]*PropertySpec{&prop_amount} }; + + parseMemO1(src, entity_specs) catch |err| { + assert(err == JsonParseError.InvalidJson); + return; + }; + + assert(false); +} diff --git a/src/parses/main.zig b/src/parses/main.zig new file mode 100644 index 0000000..eb84bbb --- /dev/null +++ b/src/parses/main.zig @@ -0,0 +1,13 @@ +const std = @import("std"); + +const specs = @import("specs.zig"); + +pub const EntitySpecs = specs.EntitySpecs; +pub const PropertySpec = specs.PropertySpec; + +pub const json = @import("json.zig").parseMemO1; +pub const url_params = @import("url_params.zig").parse; + +test { + std.testing.refAllDecls(@This()); +} diff --git a/src/parses/specs.zig b/src/parses/specs.zig new file mode 100644 index 0000000..c5ff347 --- /dev/null +++ b/src/parses/specs.zig @@ -0,0 +1,136 @@ +const std = @import("std"); +const eql = std.mem.eql; +const fmt = std.fmt; + +const DateTime = @import("things").DateTime; + +pub const PropertySpecError = error{PropertyInvalid}; + +pub const ValueEnconding = enum { json, url }; + +pub const EntitySpecs = struct { + properties: []const *PropertySpec, + + pub fn findPropertySpec(self: EntitySpecs, target: []const u8) ?*PropertySpec { + for (self.properties) |prop_spec| { + if (std.mem.eql(u8, prop_spec.name, target)) + return prop_spec; + } + + return null; + } + + pub fn setEncodingJson(self: *EntitySpecs) void { + for (0..self.properties.len) |i| { + self.properties[i].value_encoding = .json; + } + } + + pub fn setEncodingUrl(self: EntitySpecs) void { + for (0..self.properties.len) |i| { + self.properties[i].value_encoding = .url; + } + } +}; + +pub const PropertySpec = struct { + name: []const u8, + value_dirty: ?[]const u8 = null, + value_encoding: ValueEnconding = .json, + + pub fn asUuid(self: PropertySpec) PropertySpecError![36]u8 { + if (self.value_dirty == null or self.value_dirty.?.len != 36) + return PropertySpecError.PropertyInvalid; + + var value: [36]u8 = undefined; + @memcpy(&value, self.value_dirty.?[0..36]); + return value; + } + + pub fn asFloat(self: PropertySpec, comptime T: type) PropertySpecError!T { + if (self.value_dirty == null) + return PropertySpecError.PropertyInvalid; + + return fmt.parseFloat(T, self.value_dirty.?) catch { + return PropertySpecError.PropertyInvalid; + }; + } + + pub fn asInt(self: PropertySpec, comptime T: type) PropertySpecError!T { + if (self.value_dirty == null) + return PropertySpecError.PropertyInvalid; + + return fmt.parseInt(T, self.value_dirty.?, 10) catch { + return PropertySpecError.PropertyInvalid; + }; + } + + pub fn asDateTime(self: PropertySpec) PropertySpecError!DateTime { + if (self.value_dirty == null or self.value_dirty.?.len < 24) + return PropertySpecError.PropertyInvalid; + + var buf: [24]u8 = undefined; + const vd = self.value_dirty.?; + + if (self.value_encoding == .json or self.value_dirty.?.len == 24) { + @memcpy(&buf, vd); + } else if (self.value_encoding == .url and self.value_dirty.?.len >= 28) { + @memcpy(buf[0..13], vd[0..13]); + buf[13] = ':'; + @memcpy(buf[14..16], vd[16..18]); + buf[16] = ':'; + @memcpy(buf[17..24], vd[21..28]); + } + + return DateTime.ParseFromIso(&buf) catch { + return PropertySpecError.PropertyInvalid; + }; + } + + pub fn asBool(self: PropertySpec) PropertySpecError!bool { + if (self.value_dirty == null) + return PropertySpecError.PropertyInvalid; + + return eql(u8, self.value_dirty.?, "true"); + } + + pub fn asValue(self: PropertySpec, buf: []u8) PropertySpecError![]u8 { + if (self.value_dirty == null) + return PropertySpecError.PropertyInvalid; + + var i: usize = 0; + var escape = false; + + const vd = self.value_dirty.?; + const v_len = vd.len; + for (0..v_len) |j| { + var v_buf = vd[j]; + + if (escape) { + v_buf = switch (v_buf) { + '\\' => '\\', + 'n' => '\n', + 't' => '\t', + '"' => '"', + '/' => '/', + 'r' => '\r', + 'b' => 8, + else => v_buf + }; + } + + if (v_buf == '\\' and !(j + 1 < v_len and vd[j + 1] == 'u')) { + escape = true; + continue; + } + + if (i == buf.len) + return PropertySpecError.PropertyInvalid; + + buf[i] = v_buf; + i += 1; + } + + return buf[0..i]; + } +}; diff --git a/src/parses/url_params.zig b/src/parses/url_params.zig new file mode 100644 index 0000000..a06ad55 --- /dev/null +++ b/src/parses/url_params.zig @@ -0,0 +1,65 @@ +const std = @import("std"); +const assert = std.debug.assert; +const mem = std.mem; +const fmt = std.fmt; +const eql = std.mem.eql; + +const expect = std.testing.expect; +const expectEqualStrings = std.testing.expectEqualStrings; + +const specs = @import("specs.zig"); +const PropertySpec = specs.PropertySpec; +const EntitySpecs = specs.EntitySpecs; +const PropertySpecError = specs.PropertySpecError; + +const utils = @import("utils.zig"); +const ParseStack = utils.ParseStack; +const ParseStackError = utils.ParseStackError; + +pub fn parse(src: []const u8, entity_specs: EntitySpecs) void { + entity_specs.setEncodingUrl(); + + var current_prop: ?*PropertySpec = null; + var i_begin: usize = 0; + + for (0..src.len) |i| { + switch (src[i]) { + '?', '&' => { + if (current_prop != null) { + current_prop.?.value_dirty = src[i_begin..i]; + current_prop = null; + } + + i_begin = i + 1; + }, + '=' => { + current_prop = entity_specs.findPropertySpec(src[i_begin..i]); + i_begin = i + 1; + }, + else => continue + } + } + + if (current_prop != null) { + current_prop.?.value_dirty = src[i_begin..src.len]; + current_prop = null; + } +} + +test "expect parse parse url params" { + const url_params = "?from=2020-07-10T12:34:56.000Z&to=2020-07-10T12:35:56.000Z"; + + var prop_from = PropertySpec{ .name = "from" }; + var prop_to = PropertySpec{ .name = "to" }; + + parse(url_params, .{ .properties = &.{ &prop_from, &prop_to } }); + + try expect(prop_from.value_encoding == .url); + try expect(prop_to.value_encoding == .url); + + try expect(prop_from.value_dirty.?.len == 24); + try expect(prop_to.value_dirty.?.len == 24); + + try expectEqualStrings("2020-07-10T12:34:56.000Z", prop_from.value_dirty.?); + try expectEqualStrings("2020-07-10T12:35:56.000Z", prop_to.value_dirty.?); +} diff --git a/src/parses/utils.zig b/src/parses/utils.zig new file mode 100644 index 0000000..70e0ed6 --- /dev/null +++ b/src/parses/utils.zig @@ -0,0 +1,32 @@ +const MAX_STACK_SIZE = 128; + +pub const ParseStackError = error{StackOverflow}; + +pub const ParseStack = struct { + stack: [MAX_STACK_SIZE]u8 = undefined, + len: usize = 0, + + pub fn push(self: *ParseStack, v: u8) ParseStackError!void { + if (self.len == MAX_STACK_SIZE) + return ParseStackError.StackOverflow; + + self.stack[self.len] = v; + self.len += 1; + } + + pub fn pop(self: *ParseStack) u8 { + if (self.len == 0) + return 0; + + self.len -= 1; + + return self.stack[self.len]; + } + + pub fn peek(self: *ParseStack) u8 { + if (self.len == 0) + return 0; + + return self.stack[self.len - 1]; + } +}; diff --git a/src/payment_integrator.zig b/src/payment_integrator.zig new file mode 100644 index 0000000..c9158fb --- /dev/null +++ b/src/payment_integrator.zig @@ -0,0 +1,227 @@ +const std = @import("std"); +const Thread = std.Thread; +const Mutex = std.Thread.Mutex; + +const testing = std.testing; +const expect = testing.expect; +const log = std.log; + +const services = @import("services"); +const payments = @import("data").payments; +const DateTime = @import("things").DateTime; + +const is_test = @import("builtin").is_test; + +const MAX_QUEUE_SIZE = if (is_test) 100 else 500_000; +const MAX_RETRY = if (is_test) 2 else 10_000_000; + +const PaymentIntegration = struct { + payment: *payments.Payment, + ticket: ?*services.ServiceTicket = null, + is_integrated: bool = false, + buffer: [512]u8 = undefined, + retries: i32 = MAX_RETRY, + + pub fn getMessage(self: *PaymentIntegration) []u8 { + const message_template = "POST /payments HTTP/1.1\r\nHost: 0.0.0.0\r\nAccept: application/json\r\nContent-Type: application/json\r\nContent-Length: 123\r\n\r\n{{ \"correlationId\": \"{s}\",\"amount\": {d: >10.2}, \"requestedAt\": \"{s}\" }}"; + + const iso_date = self.payment.requested_at.toIso(); + return std.fmt.bufPrint(&self.buffer, message_template, .{ self.payment.id, self.payment.amount, iso_date }) catch &.{}; + } +}; + +var payment_integrator: PaymentIntegrator = undefined; + +pub const PaymentIntegrator = struct { + service_pool: *services.ServicePool, + queue: [MAX_QUEUE_SIZE]PaymentIntegration = undefined, + head: usize = 0, + tail: usize = 0, + mutex: Mutex = undefined, + thread: Thread = undefined, + + pub fn init(service_pool: *services.ServicePool) *PaymentIntegrator { + payment_integrator.service_pool = service_pool; + payment_integrator.mutex = Mutex{}; + + return &payment_integrator; + } + + pub fn start(self: *PaymentIntegrator) !void { + self.thread = try Thread.spawn(.{ .stack_size = 1024 * 64 }, PaymentIntegrator.startProcess, .{self}); + } + + fn startProcess(self: *PaymentIntegrator) void { + while (true) { + Thread.sleep(1_000_000); + + self.verifyTailSize(); + self.processPayments(); + } + } + + fn processPayments(self: *PaymentIntegrator) void { + var not_integrated_found = false; + + for (self.tail..@min(self.head, MAX_QUEUE_SIZE)) |i| { + var pi = &self.queue[i]; + + if (pi.is_integrated) { + self.tail += if (not_integrated_found) 0 else 1; + continue; + } else { + not_integrated_found = true; + } + + if (pi.ticket == null) { + if (pi.retries <= 0) { + pi.payment.integration_status = .not_integrated; + pi.is_integrated = true; // liar + } else { + pi.ticket = self.service_pool.dive(pi.getMessage()) catch null; + pi.retries -= 1; + } + } else if (pi.ticket.?.status == .try_again) { + pi.ticket.?.status = .ack; + if (pi.retries <= 0) { + pi.payment.integration_status = .not_integrated; + pi.is_integrated = true; // liar + } else { + pi.ticket = self.service_pool.dive(pi.getMessage()) catch null; + pi.retries -= 1; + } + } else if (pi.ticket.?.status == .new or pi.ticket.?.status == .pending) { + continue; + } else { + pi.payment.integration_status = .processed; + pi.payment.processed_by = pi.ticket.?.service_id; + pi.is_integrated = true; + pi.ticket.?.status = .ack; + } + } + } + + fn verifyTailSize(self: *PaymentIntegrator) void { + if (self.tail == MAX_QUEUE_SIZE) { + self.mutex.lock(); + self.tail = 0; + self.head = self.head % MAX_QUEUE_SIZE; + self.mutex.unlock(); + } + } + + pub fn newPaymentEvent(payment: *payments.Payment) void { + payment_integrator.mutex.lock(); + defer payment_integrator.mutex.unlock(); + + const head = payment_integrator.head % MAX_QUEUE_SIZE; + payment_integrator.queue[head].payment = payment; + payment_integrator.queue[head].is_integrated = false; + payment_integrator.queue[head].ticket = null; + payment_integrator.queue[head].retries = MAX_RETRY; + payment_integrator.head += 1; + } +}; + +test "expect reset the tail if it is the size of the queue" { + var service_pool = services.ServicePool{}; + var integrator = PaymentIntegrator.init(&service_pool); + + integrator.tail = MAX_QUEUE_SIZE; + integrator.head = MAX_QUEUE_SIZE + 5; + + integrator.verifyTailSize(); + + try expect(integrator.tail == 0); + try expect(integrator.head == 5); +} + +test "expect increment tail if payment is integrated" { + var service_pool = services.ServicePool{}; + var integrator = PaymentIntegrator.init(&service_pool); + + integrator.tail = 0; + integrator.head = 10; + + var payment = payments.Payment{ .id = .{'a'} ** 36, .amount = 10, .requested_at = DateTime.now() }; + + for (0..integrator.head - 5) |i| { + integrator.queue[i].is_integrated = true; + integrator.queue[i].payment = &payment; + } + + for (5..integrator.head) |i| { + integrator.queue[i].is_integrated = if (i == 7) true else false; + integrator.queue[i].retries = MAX_RETRY; + integrator.queue[i].payment = &payment; + } + + integrator.processPayments(); + + try expect(integrator.tail == 5); +} + +test "expect change payment integration status to processed when success" { + var service_pool = services.ServicePool{}; + var integrator = PaymentIntegrator.init(&service_pool); + + integrator.tail = 0; + integrator.head = 1; + + var payment = payments.Payment{ .id = .{'a'} ** 36, .amount = 10, .requested_at = DateTime.now() }; + var ticket = services.ServiceTicket{ .content = undefined, .service_id = 1, .status = .success }; + + integrator.queue[0].payment = &payment; + integrator.queue[0].ticket = &ticket; + integrator.queue[0].is_integrated = false; + + integrator.processPayments(); + + try expect(integrator.queue[0].is_integrated); + try expect(ticket.status == .ack); + try expect(payment.integration_status == .processed); + try expect(payment.processed_by == 1); +} + +test "expect queue payment when event raise" { + var service_pool = services.ServicePool{}; + var integrator = PaymentIntegrator.init(&service_pool); + + integrator.tail = 0; + integrator.head = 0; + + var payment = payments.Payment{ .id = .{'a'} ** 36, .amount = 10, .requested_at = DateTime.now() }; + PaymentIntegrator.newPaymentEvent(&payment); + + try expect(integrator.head == 1); + try expect(integrator.queue[0].payment == &payment); + try expect(integrator.queue[0].ticket == null); + try expect(integrator.queue[0].retries == MAX_RETRY); + try expect(integrator.queue[0].is_integrated == false); +} + +test "expect change payment integration status to not_integrated in a number of attempts" { + var service_pool = services.ServicePool{}; + var integrator = PaymentIntegrator.init(&service_pool); + + integrator.tail = 0; + integrator.head = 0; + + var payment = payments.Payment{ .id = .{'a'} ** 36, .amount = 10, .requested_at = DateTime.now() }; + PaymentIntegrator.newPaymentEvent(&payment); + + integrator.processPayments(); + integrator.processPayments(); + integrator.processPayments(); + + try expect(payment.integration_status == .not_integrated); + try expect(integrator.queue[0].is_integrated); +} + +test "expect get message" { + var payment = payments.Payment{ .id = .{'a'} ** 36, .amount = 100000, .requested_at = DateTime.now() }; + var payment_integration = PaymentIntegration{ .payment = &payment }; + + const message = payment_integration.getMessage(); + try expect(message.len == 244); +} diff --git a/src/security/main.zig b/src/security/main.zig new file mode 100644 index 0000000..794b7fb --- /dev/null +++ b/src/security/main.zig @@ -0,0 +1,71 @@ +const std = @import("std"); +const eql = std.mem.eql; +const expect = std.testing.expect; +const crypto = std.crypto; + +const hash_length = 64; +var hash_token: [hash_length]u8 = undefined; + +var secret_key = [_]u8{ + 's', + 'e', + 'c', + 'u', + 'r', + 'i', + 't', + 'y', + ' ', + 'i', + 's', + ' ', + 'm', + 'y', + ' ', + 'p', + 'a', + 's', + 's', + 'i', + 'o', + 'n', + '2', + '3', + '2', + '3', + '2', + '3', + '2', + '3', + '2', + '3', +}; + +pub fn updateToken(new_token: []const u8) void { + crypto.hash.Blake3.hash(new_token, &hash_token, .{ .key = secret_key }); +} + +pub fn verifyToken(token: ?[]const u8) bool { + if (token == null) + return false; + + var out: [hash_length]u8 = undefined; + + crypto.hash.Blake3.hash(token.?, &out, .{ .key = secret_key }); + + return eql(u8, &hash_token, &out); +} + +test "expect verify return true for same token" { + const token = "1234"; + updateToken(token); + + try expect(verifyToken("1234")); +} + +test "expect verify return false if token not match" { + const token = "19391029310"; + updateToken(token); + + try expect(!verifyToken("000000")); +} diff --git a/src/server.zig b/src/server.zig new file mode 100644 index 0000000..6485085 --- /dev/null +++ b/src/server.zig @@ -0,0 +1,190 @@ +const std = @import("std"); +const endpoints = @import("endpoints"); + +const http = std.http; +const net = std.net; +const log = std.log; +const expect = std.testing.expect; +const status = std.http.Status; +const method = std.http.Method; +const time = std.time; +const mem = std.mem; + +const EndpointsManager = endpoints.EndpointsManager; +const Request = endpoints.Request; +const Response = endpoints.Response; + +const HEADER_SIZE: usize = 1024; +const BODY_SIZE: usize = 1024; +const RESPONSE_SIZE: usize = 1024; +const SEND_BUFFER_SIZE: usize = 1024; + +fn separatePathAndQuery(target: []const u8) [2][]const u8 { + for (0..target.len) |i| { + if (target[i] == '?') + return .{ + target[0..i], + target[i..], + }; + } + + return .{ target[0..], &[_]u8{} }; +} + +pub const HttpServer = struct { + address: net.Address, + address_options: net.Address.ListenOptions, + get_endpoints: *EndpointsManager, + post_endpoints: *EndpointsManager, + put_endpoints: *EndpointsManager, + + pub fn init(ip_map: []const u8, port: u16, get_endpoints: *EndpointsManager, post_endpoints: *EndpointsManager, put_endpoints: *EndpointsManager) !HttpServer { + const address = try net.Address.parseIp4(ip_map, port); + + return HttpServer{ + .address = address, + .address_options = net.Address.ListenOptions{ .kernel_backlog = 256 }, + .get_endpoints = get_endpoints, + .post_endpoints = post_endpoints, + .put_endpoints = put_endpoints, + }; + } + + pub fn start(self: *HttpServer) !void { + var server = try self.address.listen(self.address_options); + + log.info("Listeting server http://{}\n", .{self.address}); + + defer server.deinit(); + + while (true) { + const conn = server.accept() catch |err| { + log.err("Error socket {}\n", .{err}); + continue; + }; + + var thread = std.Thread.spawn(.{ .stack_size = 1024 * 64 }, handleConnection, .{ self, conn }) catch |err| { + log.err("Creating thread error: {}\n", .{err}); + conn.stream.close(); + continue; + }; + + thread.detach(); + } + } + + fn handleConnection(self: *HttpServer, conn: net.Server.Connection) void { + defer conn.stream.close(); + + var buffer_request: [HEADER_SIZE]u8 = undefined; + var buffer_response: [RESPONSE_SIZE]u8 = undefined; + var send_buffer: [SEND_BUFFER_SIZE]u8 = undefined; + + var response: Response = undefined; + var req_endpoint: Request = undefined; + + while (true) { + var req_len: usize = 0; + + while (true) { + const aux_len = conn.stream.read(&buffer_request) catch { + return; + }; + + if (aux_len == 0) { + return; + } + + req_len += aux_len; + + if (buffer_request[0] == 'G' or buffer_request[7] == 'u') break; + + if (req_len >= 25 + 22 + 30 + 20 + 32 + 2 + 70) { + break; + } + } + + const b_target = nextWhiteSpace(&buffer_request, 0, req_len) + 1; + const e_target = nextWhiteSpace(&buffer_request, b_target, req_len); + const full_path = buffer_request[b_target..e_target]; + + const path, const query = separatePathAndQuery(full_path); + + const http_method: http.Method = switch (buffer_request[0]) { + 'P' => .POST, + 'G' => .GET, + else => unreachable + }; + + req_endpoint = Request{ + .method = http_method, + .path = path, + .query = query, + .body = if (req_len > 70) buffer_request[req_len - 70 .. req_len] else buffer_request[0..0], + }; + + response = Response{ + .status = .service_unavailable, + .content = &.{}, + .buffer_response = &buffer_response, + .chunked_content = .{ .buffer_chunk = &buffer_response }, + }; + + self.handleReqRes(&req_endpoint, &response); + + const response_message = std.fmt.bufPrint( + &send_buffer, + "HTTP/1.1 200 OK\r\nContent-Length: {d}\r\n\r\n{s}", + .{ response.content.len, response.content }, + ) catch return; + + _ = conn.stream.write(response_message) catch return; + } + } + + fn nextWhiteSpace(buf: []const u8, b: usize, e: usize) usize { + for (b..e) |i| if (buf[i] == ' ') return i; + + return b; + } + + pub fn handleReqRes(self: HttpServer, req: *Request, res: *Response) void { + switch (req.method) { + .GET => resolveEndpoint(req, res, self.get_endpoints), + .POST => resolveEndpoint(req, res, self.post_endpoints), + .PUT => resolveEndpoint(req, res, self.put_endpoints), + else => res.withStatus(.method_not_allowed).end(), + } + } + + pub fn resolveEndpoint(request: *Request, res: *Response, method_endpoints: *EndpointsManager) void { + const path = request.path; + + const func = method_endpoints.getEndpointFunction(path); + + if (func != null) + return func.?(request, res); + + log.warn("function not found to path {s}", .{path}); + + res.withStatus(.not_found).end(); + } +}; + +test "expect empty query when target don't have query" { + const target = "/"; + + const path, const query = separatePathAndQuery(target); + + try expect(path.len == 1); + try expect(query.len == 0); +} + +test "expect separate query and path" { + const target = "/path?query=value"; + + const path, const query = separatePathAndQuery(target); + + try expect(path.len == 5); + try expect(query.len == 12); +} diff --git a/src/services/http_service.zig b/src/services/http_service.zig new file mode 100644 index 0000000..f050440 --- /dev/null +++ b/src/services/http_service.zig @@ -0,0 +1,567 @@ +const std = @import("std"); +const mem = std.mem; +const heap = std.heap; +const net = std.net; +const Allocator = mem.Allocator; +const Stream = net.Stream; +const Thread = std.Thread; +const Mutex = Thread.Mutex; +const Address = net.Address; + +const testing = std.testing; +const expect = testing.expect; + +const log = std.log; + +const s = @import("service.zig"); +const ServiceConnection = s.ServiceConnection; +const ServiceError = s.ServiceError; +const ServiceTicket = s.ServiceTicket; +const ServiceHealth = s.ServiceHealth; + +pub const HttpService = struct { + id: u64, + name: []const u8, + address: Address, + connections: []ServiceConnection, + tickets: []ServiceTicket, + thread_stop: []bool, + threads: []?Thread, + allocator: Allocator, + + health_connection: ServiceConnection = ServiceConnection{}, + capacity: usize = 0, + health: ServiceHealth = .unavailable, + response_time: u64 = 0, + + mutex: Mutex, + + pub fn init(id: u64, name: []const u8, host: []const u8, port: u16, num_connections: usize, allocator: Allocator) ServiceError!HttpService { + var buf: [1024]u8 = undefined; + var pba = heap.FixedBufferAllocator.init(&buf); + + const addrList = net.getAddressList(pba.allocator(), host, port) catch return ServiceError.NotFound; + defer addrList.deinit(); + + if (addrList.addrs.len == 0) + return ServiceError.NotFound; + + var final_addr: ?Address = null; + for (addrList.addrs) |addr| { + const ping = net.tcpConnectToAddress(addr) catch { + continue; + }; + + ping.close(); + final_addr = addr; + } + + if (final_addr == null) + return ServiceError.Unreachable; + + if (num_connections != 0 and num_connections % 10 != 0) { + return ServiceError.NumConnectionsShouldBeMultipleOfTen; + } + + const num_tickets = num_connections * 2; + const num_threads = (num_connections / 10) + 2; + + var connections = try allocator.alloc(ServiceConnection, num_connections); + const tickets = try allocator.alloc(ServiceTicket, num_tickets); + const threads = try allocator.alloc(?Thread, num_threads); + const thread_stop = try allocator.alloc(bool, num_threads); + + for (0..num_connections) |i| { + connections[i].status = .closed; + } + + for (0..num_tickets) |i| { + tickets[i].status = .ack; + tickets[i].service_id = id; + } + + for (0..num_threads) |i| { + thread_stop[i] = false; + } + + for (0..num_threads) |i| { + threads[i] = null; + } + + return HttpService{ + .id = id, + .name = name, + .address = final_addr.?, + .connections = connections, + .tickets = tickets, + .allocator = allocator, + .threads = threads, + .thread_stop = thread_stop, + .mutex = Mutex{}, + }; + } + + pub fn start(self: *HttpService) !void { + if (self.connections.len == 0) return; + + var conn_i: usize = 10; + var msg_i: usize = 20; + + for (0..self.threads.len - 2) |i| { + const connections = self.connections[conn_i - 10 .. conn_i]; + const tickets = self.tickets[msg_i - 20 .. msg_i]; + + conn_i += 10; + msg_i += 20; + + self.threads[i] = try Thread.spawn(.{ .stack_size = 1024 * 64 }, HttpService.startMessenger, .{ + self, + connections, + tickets, + i, + }); + } + + const update_health_thread_id: usize = self.threads.len - 2; + const update_capacity_thread_id: usize = update_health_thread_id + 1; + + self.threads[update_health_thread_id] = try Thread.spawn(.{ .stack_size = 1024 * 64 }, HttpService.updateHealth, .{ self, update_health_thread_id }); + self.threads[update_capacity_thread_id] = try Thread.spawn(.{ .stack_size = 1024 * 64 }, HttpService.updateCapacity, .{ self, update_capacity_thread_id }); + } + + pub fn queue(self: *HttpService, message: []const u8) ?*ServiceTicket { + self.mutex.lock(); + defer self.mutex.unlock(); + + for (self.tickets) |*ticket| { + if (ticket.status == .ack) { + ticket.content = message; + ticket.status = .new; + return ticket; + } + } + + return null; + } + + fn handleResponse(_: *HttpService, ticket: *ServiceTicket) void { + var conn_success = false; + + const res_len = ticket.conn.readAsHttp(&ticket.res_buf); + + //log.info("res in {s}: {s}", .{ self.name, ticket.res_buf[0..res_len] }); + + if (res_len == 0) { + ticket.conn.close(); + } else { + ticket.conn.status = .disponible; + conn_success = true; + } + + const res_content = ticket.res_buf[0..res_len]; + + ticket.status = if (conn_success and res_content.len > 9 and res_content[9] == '2') .success else .try_again; + } + + fn trySendticket(self: *HttpService, ticket: *ServiceTicket, connections: []ServiceConnection) void { + for (connections) |*conn| { + if (conn.status == .ocuppied) { + continue; + } + + if (conn.status == .closed) { + conn.tryConnect(&self.address) catch { + continue; + }; + } + + _ = conn.stream.write(ticket.content) catch { + continue; + }; + + conn.status = .ocuppied; + ticket.conn = conn; + ticket.status = .pending; + break; + } + + if (ticket.status != .pending) { + ticket.status = .try_again; + } + } + + pub fn startMessenger(self: *HttpService, connections: []ServiceConnection, tickets: []ServiceTicket, thread_id: usize) void { + while (true) { + Thread.sleep(1_000_000); + if (self.thread_stop[thread_id]) { + var conn_open = false; + + for (connections) |*conn| { + if (conn.status == .ocuppied) { + conn_open = true; + break; + } + } + + if (!conn_open) { + for (tickets) |*msg| { + if (msg.status == .new) { + msg.status = .try_again; + } + } + return; + } + } + + for (tickets) |*ticket| { + if (self.thread_stop[thread_id] and ticket.status == .new) { + continue; + } + + if (ticket.status == .ack or ticket.status == .success or ticket.status == .try_again) { + continue; + } + + if (ticket.status == .pending) { + self.handleResponse(ticket); + continue; + } + + self.trySendticket(ticket, connections); + } + } + } + + fn updateHealth(self: *HttpService, thread_id: usize) void { + while (true) { + if (self.thread_stop[thread_id]) { + return; + } + + self.checkHealth(); + //log.info("Service {s} health {any} {d} ms\n", .{ self.name, self.health, self.response_time }); + Thread.sleep(1_000_000 * 1000); + } + } + + fn checkHealth(self: *HttpService) void { + var conn = &self.health_connection; + const req_ticket = "GET /payments/service-health HTTP/1.1\r\nHost: 0.0.0.0\r\nAccept: application/json\r\n\r\n"; + + var buf_res: [1024]u8 = undefined; + + if (conn.status == .closed) { + conn.tryConnect(&self.address) catch { + self.health = .unavailable; + conn.close(); + return; + }; + + conn.status = .disponible; + } + + _ = conn.stream.write(req_ticket) catch { + self.health = .unavailable; + conn.close(); + return; + }; + + const res_len = conn.readAsHttp(&buf_res); + + if (res_len == 0) { + self.health = .unavailable; + conn.close(); + return; + } + + const res_content = buf_res[0 .. res_len - 5]; + const end_content = buf_res[res_len - 5 .. res_len]; + + if (res_content.len > 9 and res_content[9] == '2' and end_content[0] == '0' and end_content[1] == '\r' and end_content[2] == '\n') { + var response_time: u64 = 0; + var multiply: u64 = 1; + var i = res_content.len - 4; + + while (i >= 0) { + const d = res_content[i]; + if (d < '0' or d > '9') { + break; + } + + response_time += multiply * (d - '0'); + multiply *= 10; + i -= 1; + } + + self.response_time = response_time; + self.health = if (i > 19 and res_content[i - 20] == 's') .available else .unavailable; + } else { + self.health = .unavailable; + self.response_time = 0; + } + } + + fn updateCapacity(self: *HttpService, thread_id: usize) void { + while (true) { + Thread.sleep(1_000_000); + var count: usize = 0; + for (self.connections) |conn| { + if (conn.status == .ocuppied) { + count += 1; + } + } + + self.capacity = (count * 100) / self.connections.len; + + if (self.thread_stop[thread_id]) { + return; + } + } + } + + pub fn deinit(self: *HttpService) void { + for (self.thread_stop) |*v| { + v.* = true; + } + + for (self.threads) |thread| { + if (thread == null) { + continue; + } + + thread.?.join(); + } + + for (self.connections) |*conn| { + conn.close(); + } + + self.health_connection.close(); + + self.allocator.free(self.connections); + self.allocator.free(self.tickets); + self.allocator.free(self.threads); + self.allocator.free(self.thread_stop); + } +}; + +test "expect init service if host exists and service is reachable" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 100, testing.allocator); + defer service.deinit(); + + try testing.expectEqualStrings(service.name, "default"); +} + +test "expect init service error if number of connections is not multiple of 10" { + var service = HttpService.init(1, "default", "one.one.one.one", 53, 97, testing.allocator) catch |err| { + try expect(err == ServiceError.NumConnectionsShouldBeMultipleOfTen); + return; + }; + + defer service.deinit(); + + try expect(false); +} + +test "expect use only disponible or closed connections to send the ticket" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 10, testing.allocator); + defer service.deinit(); + + try service.connections[0].tryConnect(&service.address); + service.connections[0].status = .ocuppied; + try service.connections[1].tryConnect(&service.address); + service.connections[1].status = .ocuppied; + + var ticket = ServiceTicket{ .content = "", .status = .new }; + const conns = service.connections[0..10]; + + service.trySendticket(&ticket, conns); + + try expect(&service.connections[2] == ticket.conn); + try expect(service.connections[2].status == .ocuppied); +} + +test "expect ticket status try_again if all connection ocuppied" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 10, testing.allocator); + defer service.deinit(); + + for (service.connections) |*conn| { + try conn.tryConnect(&service.address); + conn.status = .ocuppied; + } + + var ticket = ServiceTicket{ .content = "my payload", .status = .new }; + const conns = service.connections[0..10]; + + service.trySendticket(&ticket, conns); + + try expect(ticket.status == .try_again); +} + +test "expect ticket status success if response is success" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 10, testing.allocator); + defer service.deinit(); + + var conn = &service.connections[0]; + + try conn.tryConnect(&service.address); + conn.status = .ocuppied; + _ = try conn.stream.write("HTTP/1.1 200 OK"); + + var ticket = ServiceTicket{ .content = undefined, .status = .pending, .conn = conn }; + + service.handleResponse(&ticket); + + try expect(conn.status == .disponible); + try expect(ticket.status == .success); +} + +test "expect ticket status try_again if connection closed" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 10, testing.allocator); + defer service.deinit(); + + var conn = &service.connections[0]; + + try conn.tryConnect(&service.address); + conn.status = .ocuppied; + + var ticket = ServiceTicket{ .content = undefined, .status = .new, .conn = conn }; + + service.handleResponse(&ticket); + + try expect(conn.status == .closed); + try expect(ticket.status == .try_again); +} + +test "expect ticket status try_again if response is http status error" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 10, testing.allocator); + defer service.deinit(); + + var conn = &service.connections[0]; + + try conn.tryConnect(&service.address); + conn.status = .ocuppied; + _ = try conn.stream.write("HTTP/1.1 400 OK"); + + var ticket = ServiceTicket{ .content = undefined, .status = .pending, .conn = conn }; + + service.handleResponse(&ticket); + + try expect(conn.status == .disponible); + try expect(ticket.status == .try_again); +} + +test "expect complete all ticket before thread stop" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 100, testing.allocator); + defer service.deinit(); + + var conn = &service.connections[7]; + + try conn.tryConnect(&service.address); + conn.status = .ocuppied; + _ = try conn.stream.write("HTTP/1.1 200 OK"); + + service.tickets[8] = ServiceTicket{ .content = undefined, .status = .new, .conn = undefined }; + service.tickets[9] = ServiceTicket{ .content = undefined, .status = .pending, .conn = conn }; + + service.thread_stop[0] = true; + service.startMessenger(service.connections[0..10], service.tickets[0..100], 0); + + for (service.connections) |c| { + try expect(c.status != .ocuppied); + } + + for (service.tickets) |m| { + try expect(m.status != .pending); + } +} + +test "expect checkHealth update the service health: available" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 10, testing.allocator); + defer service.deinit(); + + var conn = &service.health_connection; + try conn.tryConnect(&service.address); + conn.status = .disponible; + _ = try conn.stream.write("HTTP/1.1 200 OK\r\n2C\r\n{\"failing\":false,\"minResponseTime\":10}\r\n0\r\n\r\n"); + conn.stream.not_write = true; + + service.checkHealth(); + + try expect(service.health == .available); + try expect(service.response_time == 10); +} + +test "expect checkHealth update the service health: unavailable" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 10, testing.allocator); + defer service.deinit(); + + var conn = &service.health_connection; + try conn.tryConnect(&service.address); + conn.status = .disponible; + _ = try conn.stream.write("HTTP/1.1 200 OK\r\n2C\r\n{\"failing\":true,\"minResponseTime\":0}\r\n0\r\n\r\n"); + conn.stream.not_write = true; + + service.checkHealth(); + + try expect(service.health == .unavailable); + try expect(service.response_time == 0); +} + +test "expect unavailable if any connection ocorrur" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 10, testing.allocator); + defer service.deinit(); + + var conn = &service.health_connection; + try conn.tryConnect(&service.address); + conn.status = .disponible; + conn.stream._error = true; + conn.stream.not_write = true; + + service.checkHealth(); + + try expect(service.health == .unavailable); + try expect(service.response_time == 0); +} + +test "expect update capacity with correct percentage" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 1000, testing.allocator); + defer service.deinit(); + + for (0..500) |i| { + service.connections[i].status = .ocuppied; + try service.connections[i].tryConnect(&service.address); + } + + service.thread_stop[0] = true; + service.updateCapacity(0); + + try expect(service.capacity == 50); +} + +test "expect service start" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 1000, testing.allocator); + + try service.start(); + + try expect(service.threads.len == 102); + + service.deinit(); +} + +test "expect queue the message in the right spot" { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 40, testing.allocator); + defer service.deinit(); + + for (0..23) |i| { + service.tickets[i].status = .new; + } + + const message = "Hello, World!"; + + const ticket = service.queue(message); + + try expect(ticket != null); + + try expect(&service.tickets[23] == ticket); +} diff --git a/src/services/main.zig b/src/services/main.zig new file mode 100644 index 0000000..91f2ef8 --- /dev/null +++ b/src/services/main.zig @@ -0,0 +1,12 @@ +const std = @import("std"); + +const http_service = @import("http_service.zig"); +pub const HttpService = http_service.HttpService; + +pub const ServicePool = @import("service_pool.zig").ServicePool; + +pub const ServiceTicket = @import("service.zig").ServiceTicket; + +test { + std.testing.refAllDecls(@This()); +} diff --git a/src/services/service.zig b/src/services/service.zig new file mode 100644 index 0000000..66127cc --- /dev/null +++ b/src/services/service.zig @@ -0,0 +1,80 @@ +const std = @import("std"); +const mem = std.mem; +const heap = std.heap; +const net = std.net; +const Allocator = mem.Allocator; +const Stream = net.Stream; +const Thread = std.Thread; +const Mutex = Thread.Mutex; +const Address = net.Address; + +const FakeStream = @import("helpers").FakeStream; + +const is_test = @import("builtin").is_test; + +const testing = std.testing; +const expect = testing.expect; + +pub const ServiceConnectionStatus = enum { closed, disponible, ocuppied }; + +pub const ServiceConnection = struct { + stream: if (is_test) FakeStream else Stream = undefined, + status: ServiceConnectionStatus = .closed, + + pub fn readAsHttp(self: *ServiceConnection, buf: []u8) usize { + var res_len: usize = 0; + + while (true) { // trying clean the stream + const aux_len = self.stream.read(buf[res_len..]) catch 0; + + if (aux_len == 0) { + break; + } + + res_len += aux_len; + + if (res_len > 3 and buf[res_len - 1] == '\n' and buf[res_len - 2] == '\r' and buf[res_len - 3] == '\n' and buf[res_len - 4] == '\r') { + break; + } + } + + return res_len; + } + + pub fn tryConnect(self: *ServiceConnection, address: *const Address) !void { + if (is_test) { + const buf = try testing.allocator.alloc(u8, 1024); + self.stream = FakeStream.init(buf); + } else { + self.stream = try net.tcpConnectToAddress(address.*); + } + } + + pub fn close(self: *ServiceConnection) void { + if (self.status == .closed) { + return; + } + + if (is_test) { + testing.allocator.free(self.stream.buffer); + } else { + self.stream.close(); + } + + self.status = .closed; + } +}; + +pub const ServiceHealth = enum { available, unavailable }; + +pub const ServiceError = error{ NotFound, Unreachable, NumConnectionsShouldBeMultipleOfTen } || Allocator.Error; + +pub const TicketStatus = enum { new, pending, success, try_again, ack }; + +pub const ServiceTicket = struct { + content: []const u8, + status: TicketStatus = .ack, + conn: *ServiceConnection = undefined, + res_buf: [1024]u8 = undefined, + service_id: u64 = 0, +}; diff --git a/src/services/service_pool.zig b/src/services/service_pool.zig new file mode 100644 index 0000000..b36e3c1 --- /dev/null +++ b/src/services/service_pool.zig @@ -0,0 +1,211 @@ +const std = @import("std"); + +const testing = std.testing; +const expect = testing.expect; + +const HttpService = @import("http_service.zig").HttpService; + +const s = @import("service.zig"); +const ServiceTicket = s.ServiceTicket; + +const ServicePoolError = error{ FullPoll, NoServiceAvailable }; + +pub const ServicePool = struct { + services: [10]*HttpService = undefined, + services_len: usize = 0, + + pub fn add(self: *ServicePool, service: *HttpService) ServicePoolError!void { + if (self.services_len == self.services.len) { + return ServicePoolError.FullPoll; + } + + self.services[self.services_len] = service; + self.services_len += 1; + } + + pub fn dive(self: *ServicePool, message: []const u8) ServicePoolError!*ServiceTicket { + var skip: [10]bool = .{false} ** 10; + + for (0..self.services_len) |_| { + var best_service = self.findBestService(&skip); + + if (best_service == null) { + return error.NoServiceAvailable; + } + + const ticket = best_service.?.queue(message); + + if (ticket == null) { + continue; + } + + return ticket.?; + } + + return error.NoServiceAvailable; + } + + fn findBestService(self: *ServicePool, skip: []bool) ?*HttpService { + var first_service_available_i: ?usize = null; + var best_perfomance_i: ?usize = null; + + for (0..self.services_len) |i| { + if (skip[i]) { + continue; + } + + const service = self.services[i]; + + if (service.health == .unavailable or service.capacity >= 90) { + continue; + } + + if (first_service_available_i == null) { + first_service_available_i = i; + } + + if (best_perfomance_i == null or self.services[best_perfomance_i.?].response_time > service.response_time) { + best_perfomance_i = i; + } + } + + if (best_perfomance_i != null) { + skip[best_perfomance_i.?] = true; + return self.services[best_perfomance_i.?]; + } + + if (first_service_available_i != null) { + skip[first_service_available_i.?] = true; + return self.services[first_service_available_i.?]; + } + + return null; + } +}; + +test "expect error FullPoll if more then 10 service is added" { + var service_pool = ServicePool{}; + + for (0..10) |_| { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 40, testing.allocator); + defer service.deinit(); + try service_pool.add(&service); + } + + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 40, testing.allocator); + defer service.deinit(); + + service_pool.add(&service) catch |err| { + try expect(err == ServicePoolError.FullPoll); + return; + }; + + try expect(false); +} + +test "expect NoServiceAvailable if no service has been add" { + var service_pool = ServicePool{}; + + _ = service_pool.dive("test") catch |err| { + try expect(err == ServicePoolError.NoServiceAvailable); + return; + }; + + try expect(false); +} + +test "expect if NoServiceAvailable all sevice are unavailable" { + var service_pool = ServicePool{}; + + for (0..10) |_| { + var service = try HttpService.init(1, "default", "one.one.one.one", 53, 40, testing.allocator); + service.health = .unavailable; + defer service.deinit(); + try service_pool.add(&service); + } + + var service = try HttpService.init(2, "default", "one.one.one.one", 53, 40, testing.allocator); + defer service.deinit(); + + service_pool.add(&service) catch |err| { + try expect(err == ServicePoolError.FullPoll); + return; + }; + + try expect(false); +} + +test "expect choice service with best perfomance" { + var service_pool = ServicePool{}; + + var service1 = try HttpService.init(1, "default", "one.one.one.one", 53, 40, testing.allocator); + service1.health = .available; + service1.response_time = 100; + defer service1.deinit(); + try service_pool.add(&service1); + + var service2 = try HttpService.init(2, "fallback", "one.one.one.one", 53, 40, testing.allocator); + service2.health = .available; + service2.response_time = 10; + defer service2.deinit(); + try service_pool.add(&service2); + + var skip: [10]bool = .{false} ** 10; + const res = service_pool.findBestService(&skip); + + try expect(res.? == &service2); + try expect(skip[1]); +} + +test "expect choice service first service available if all has the same perfomance" { + var service_pool = ServicePool{}; + + var service1 = try HttpService.init(1, "default", "one.one.one.one", 53, 40, testing.allocator); + service1.health = .available; + service1.response_time = 10; + defer service1.deinit(); + try service_pool.add(&service1); + + var service2 = try HttpService.init(2, "fallback", "one.one.one.one", 53, 40, testing.allocator); + service2.health = .available; + service2.response_time = 10; + defer service2.deinit(); + try service_pool.add(&service2); + + var skip: [10]bool = .{false} ** 10; + const res = service_pool.findBestService(&skip); + + try expect(res.? == &service1); + try expect(skip[0]); +} + +test "expect choice service with overloaded" { + var service_pool = ServicePool{}; + + var service1 = try HttpService.init(1, "default", "one.one.one.one", 53, 40, testing.allocator); + service1.health = .available; + service1.response_time = 10; + service1.capacity = 90; + defer service1.deinit(); + try service_pool.add(&service1); + + var service2 = try HttpService.init(2, "fallback", "one.one.one.one", 53, 40, testing.allocator); + service2.health = .available; + service2.response_time = 10; + service2.capacity = 100; + defer service2.deinit(); + try service_pool.add(&service2); + + var service3 = try HttpService.init(3, "fallback_fallback", "one.one.one.one", 53, 40, testing.allocator); + service3.health = .available; + service3.response_time = 10; + service3.capacity = 50; + defer service3.deinit(); + try service_pool.add(&service3); + + var skip: [10]bool = .{false} ** 10; + const res = service_pool.findBestService(&skip); + + try expect(res.? == &service3); + try expect(skip[2]); +} diff --git a/src/things/DateTime.zig b/src/things/DateTime.zig new file mode 100644 index 0000000..ab575ff --- /dev/null +++ b/src/things/DateTime.zig @@ -0,0 +1,177 @@ +const std = @import("std"); +const fmt = std.fmt; +const time = std.time; +const expect = std.testing.expect; +const expectEqualStrings = std.testing.expectEqualStrings; + +pub const DateTimeParseError = error{InvalidDateFormat}; + +pub const DateTime = struct { + year: u16, + month: u8, + day: u8, + hour: u8, + minutes: u8, + seconds: u8, + milliseconds: u16, + pub fn ParseFromIso(iso: []const u8) DateTimeParseError!DateTime { + if (iso.len != 24) + return DateTimeParseError.InvalidDateFormat; + + const year = fmt.parseInt(u16, iso[0..4], 10) catch { + return DateTimeParseError.InvalidDateFormat; + }; + + const month = fmt.parseInt(u8, iso[5..7], 10) catch { + return DateTimeParseError.InvalidDateFormat; + }; + + const day = fmt.parseInt(u8, iso[8..10], 10) catch { + return DateTimeParseError.InvalidDateFormat; + }; + + const hour = fmt.parseInt(u8, iso[11..13], 10) catch { + return DateTimeParseError.InvalidDateFormat; + }; + + const minutes = fmt.parseInt(u8, iso[14..16], 10) catch { + return DateTimeParseError.InvalidDateFormat; + }; + + const seconds = fmt.parseInt(u8, iso[17..19], 10) catch { + return DateTimeParseError.InvalidDateFormat; + }; + + const miliseconds = fmt.parseInt(u16, iso[20..23], 10) catch { + return DateTimeParseError.InvalidDateFormat; + }; + + return DateTime{ .year = year, .month = month, .day = day, .hour = hour, .minutes = minutes, .seconds = seconds, .milliseconds = miliseconds }; + } + + pub fn toIsoBuf(self: *const DateTime, buf: []u8) ![]u8 { + return try fmt.bufPrint(buf, "{d}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}Z", .{ self.year, self.month, self.day, self.hour, self.minutes, self.seconds, self.milliseconds }); + } + + pub fn toIso(self: *const DateTime) [24]u8 { + var buf: [24]u8 = undefined; + + _ = self.toIsoBuf(&buf) catch { + return buf; + }; + + return buf; + } + + pub fn now() DateTime { + const timestamp = time.milliTimestamp(); + + return TimestampToDateTime(timestamp); + } + + fn TimestampToDateTime(timestamp: i64) DateTime { + var months_days: [12]u16 = .{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + + var datetime: DateTime = undefined; + var ts = timestamp; + + const ms_to_s: i64 = 1_000; + const d60: i64 = 60; + const d24: i64 = 24; + + datetime.milliseconds = @intCast(@mod(ts, ms_to_s)); + ts = @divFloor(ts, ms_to_s); + datetime.seconds = @intCast(@mod(ts, d60)); + ts = @divFloor(ts, d60); + datetime.minutes = @intCast(@mod(ts, d60)); + ts = @divFloor(ts, d60); + datetime.hour = @intCast(@mod(ts, d24)); + + var days = @divFloor(ts, d24) + 1; + + for (1970..3000) |y| { + const year_days: i64 = if ((y % 4 == 0 and y % 100 != 0) or y % 400 == 0) 366 else 365; + + if (days <= year_days) { + months_days[1] = if (year_days == 365) 28 else 29; + datetime.year = @intCast(y); + break; + } + + days -= year_days; + } + + for (0..12) |i| { + const days_month = months_days[i]; + + if (days <= days_month) { + datetime.month = @intCast(i + 1); + datetime.day = @intCast(days); + break; + } else { + days -= days_month; + } + } + + return datetime; + } + + inline fn _gtaux(s: anytype, t: anytype, e: anytype) bool { + return (s > t) or (s == t and e); + } + + pub inline fn gt(self: DateTime, then: DateTime) bool { + return (_gtaux(self.year, then.year, _gtaux(self.month, then.month, _gtaux(self.day, then.day, _gtaux(self.hour, then.hour, _gtaux(self.minutes, then.minutes, _gtaux(self.seconds, then.seconds, (self.milliseconds >= then.milliseconds)))))))); + } + + inline fn _ltaux(s: anytype, t: anytype, e: anytype) bool { + return (s < t) or (s == t and e); + } + + pub inline fn lt(self: DateTime, then: DateTime) bool { + return (_ltaux(self.year, then.year, _ltaux(self.month, then.month, _ltaux(self.day, then.day, _ltaux(self.hour, then.hour, _ltaux(self.minutes, then.minutes, _ltaux(self.seconds, then.seconds, (self.milliseconds <= then.milliseconds)))))))); + } +}; + +test "expect parse iso date" { + const date_time = try DateTime.ParseFromIso("2025-07-15T12:34:56.101Z"); + + try expect(date_time.year == 2025); + try expect(date_time.month == 7); + try expect(date_time.day == 15); + try expect(date_time.hour == 12); + try expect(date_time.minutes == 34); + try expect(date_time.seconds == 56); + try expect(date_time.milliseconds == 101); +} + +test "expect return correct iso" { + const date_time = &DateTime{ .year = 2025, .month = 9, .day = 24, .hour = 3, .minutes = 2, .seconds = 1, .milliseconds = 88 }; + + var iso_buf: [24]u8 = undefined; + + const iso = try date_time.toIsoBuf(&iso_buf); + + try expectEqualStrings(iso, "2025-09-24T03:02:01.088Z"); +} + +test "expect error when parse iso date with wrong len" { + _ = DateTime.ParseFromIso("2025-07-15") catch { + return; + }; + + try expect(false); +} + +test "expect return today datetime" { + const timestamp = 1001214383222; + const date_time = DateTime.TimestampToDateTime(timestamp); + + try expect(date_time.year == 2001); + try expect(date_time.month == 9); + try expect(date_time.day == 23); + try expect(date_time.hour == 3); + try expect(date_time.minutes == 6); + try expect(date_time.seconds == 23); + try expect(date_time.milliseconds == 222); +} diff --git a/src/things/main.zig b/src/things/main.zig new file mode 100644 index 0000000..327de81 --- /dev/null +++ b/src/things/main.zig @@ -0,0 +1,7 @@ +const std = @import("std"); + +pub const DateTime = @import("DateTime.zig").DateTime; + +test { + std.testing.refAllDecls(@This()); +}