diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml
index fd4e0fd5c..41b40feaa 100644
--- a/.github/workflows/deployment.yaml
+++ b/.github/workflows/deployment.yaml
@@ -57,6 +57,7 @@ jobs:
run: |
cargo publish -p bittorrent-http-protocol
cargo publish -p bittorrent-tracker-client
+ cargo publish -p bittorrent-tracker-core
cargo publish -p torrust-tracker
cargo publish -p torrust-tracker-api-client
cargo publish -p torrust-tracker-client
diff --git a/Cargo.lock b/Cargo.lock
index 355457721..d0d4d7e8f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -591,6 +591,36 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "bittorrent-tracker-core"
+version = "3.0.0-develop"
+dependencies = [
+ "aquatic_udp_protocol",
+ "bittorrent-http-protocol",
+ "bittorrent-primitives",
+ "chrono",
+ "derive_more",
+ "futures",
+ "local-ip-address",
+ "mockall",
+ "r2d2",
+ "r2d2_mysql",
+ "r2d2_sqlite",
+ "rand",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.11",
+ "tokio",
+ "torrust-tracker-api-client",
+ "torrust-tracker-clock",
+ "torrust-tracker-configuration",
+ "torrust-tracker-located-error",
+ "torrust-tracker-primitives",
+ "torrust-tracker-test-helpers",
+ "torrust-tracker-torrent-repository",
+ "tracing",
+]
+
[[package]]
name = "bitvec"
version = "1.0.1"
@@ -3931,6 +3961,7 @@ dependencies = [
"bittorrent-http-protocol",
"bittorrent-primitives",
"bittorrent-tracker-client",
+ "bittorrent-tracker-core",
"bloom",
"blowfish",
"camino",
diff --git a/Cargo.toml b/Cargo.toml
index 4b4862cca..6c9f7f22d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -42,6 +42,7 @@ axum-server = { version = "0", features = ["tls-rustls-no-provider"] }
bittorrent-http-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" }
bittorrent-primitives = "0.1.0"
bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" }
+bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" }
bloom = "0.3.2"
blowfish = "0"
camino = { version = "1", features = ["serde", "serde1"] }
@@ -90,7 +91,17 @@ uuid = { version = "1", features = ["v4"] }
zerocopy = "0.7"
[package.metadata.cargo-machete]
-ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes"]
+ignored = [
+ "crossbeam-skiplist",
+ "dashmap",
+ "figment",
+ "parking_lot",
+ "r2d2",
+ "r2d2_mysql",
+ "r2d2_sqlite",
+ "serde_bytes",
+ "torrust-tracker-torrent-repository",
+]
[dev-dependencies]
local-ip-address = "0"
@@ -109,6 +120,7 @@ members = [
"packages/torrent-repository",
"packages/tracker-api-client",
"packages/tracker-client",
+ "packages/tracker-core",
]
[profile.dev]
diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml
new file mode 100644
index 000000000..b38f7c90f
--- /dev/null
+++ b/packages/tracker-core/Cargo.toml
@@ -0,0 +1,43 @@
+[package]
+description = "A library with the core functionality needed to implement a BitTorrent tracker."
+keywords = ["api", "bittorrent", "core", "library", "tracker"]
+name = "bittorrent-tracker-core"
+readme = "README.md"
+
+authors.workspace = true
+documentation.workspace = true
+edition.workspace = true
+homepage.workspace = true
+license.workspace = true
+publish.workspace = true
+repository.workspace = true
+rust-version.workspace = true
+version.workspace = true
+
+[dependencies]
+aquatic_udp_protocol = "0"
+bittorrent-http-protocol = { version = "3.0.0-develop", path = "../http-protocol" }
+bittorrent-primitives = "0.1.0"
+chrono = { version = "0", default-features = false, features = ["clock"] }
+derive_more = { version = "1", features = ["as_ref", "constructor", "from"] }
+futures = "0"
+r2d2 = "0"
+r2d2_mysql = "25"
+r2d2_sqlite = { version = "0", features = ["bundled"] }
+rand = "0"
+serde = { version = "1", features = ["derive"] }
+serde_json = { version = "1", features = ["preserve_order"] }
+thiserror = "2"
+tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] }
+torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" }
+torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" }
+torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" }
+torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" }
+torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" }
+tracing = "0"
+
+[dev-dependencies]
+local-ip-address = "0"
+mockall = "0"
+torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" }
+torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" }
diff --git a/packages/tracker-core/LICENSE b/packages/tracker-core/LICENSE
new file mode 100644
index 000000000..0ad25db4b
--- /dev/null
+++ b/packages/tracker-core/LICENSE
@@ -0,0 +1,661 @@
+ 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.
+
+
+ Copyright (C)
+
+ 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/packages/tracker-core/README.md b/packages/tracker-core/README.md
new file mode 100644
index 000000000..1575cda49
--- /dev/null
+++ b/packages/tracker-core/README.md
@@ -0,0 +1,15 @@
+# BitTorrent Core Tracker library
+
+A library with the core functionality needed to implement a BitTorrent tracker.
+
+You usually don’t need to use this library directly. Instead, you should use the [Torrust Tracker](https://github.com/torrust/torrust-tracker). If you want to build your own tracker, you can use this library as the core functionality. In that case, you should add the delivery layer (HTTP or UDP) on top of this library.
+
+> **Disclaimer**: This library is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects.
+
+## Documentation
+
+[Crate documentation](https://docs.rs/bittorrent-tracker-core).
+
+## License
+
+The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE).
diff --git a/migrations/README.md b/packages/tracker-core/migrations/README.md
similarity index 100%
rename from migrations/README.md
rename to packages/tracker-core/migrations/README.md
diff --git a/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql b/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql
similarity index 100%
rename from migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql
rename to packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql
diff --git a/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql b/packages/tracker-core/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql
similarity index 100%
rename from migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql
rename to packages/tracker-core/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql
diff --git a/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql b/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql
similarity index 100%
rename from migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql
rename to packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql
diff --git a/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql b/packages/tracker-core/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql
similarity index 100%
rename from migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql
rename to packages/tracker-core/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql
diff --git a/src/core/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs
similarity index 92%
rename from src/core/announce_handler.rs
rename to packages/tracker-core/src/announce_handler.rs
index 816663bf6..877555d1c 100644
--- a/src/core/announce_handler.rs
+++ b/packages/tracker-core/src/announce_handler.rs
@@ -176,9 +176,9 @@ mod tests {
use torrust_tracker_primitives::DurationSinceUnixEpoch;
use torrust_tracker_test_helpers::configuration;
- use crate::core::announce_handler::AnnounceHandler;
- use crate::core::core_tests::initialize_handlers;
- use crate::core::scrape_handler::ScrapeHandler;
+ use crate::announce_handler::AnnounceHandler;
+ use crate::core_tests::initialize_handlers;
+ use crate::scrape_handler::ScrapeHandler;
fn public_tracker() -> (Arc, Arc) {
let config = configuration::ephemeral_public();
@@ -222,17 +222,17 @@ mod tests {
use std::sync::Arc;
- use crate::core::announce_handler::tests::the_announce_handler::{
+ use crate::announce_handler::tests::the_announce_handler::{
peer_ip, public_tracker, sample_peer_1, sample_peer_2,
};
- use crate::core::announce_handler::PeersWanted;
- use crate::core::core_tests::{sample_info_hash, sample_peer};
+ use crate::announce_handler::PeersWanted;
+ use crate::core_tests::{sample_info_hash, sample_peer};
mod should_assign_the_ip_to_the_peer {
use std::net::{IpAddr, Ipv4Addr};
- use crate::core::announce_handler::assign_ip_address_to_peer;
+ use crate::announce_handler::assign_ip_address_to_peer;
#[test]
fn using_the_source_ip_instead_of_the_ip_in_the_announce_request() {
@@ -248,7 +248,7 @@ mod tests {
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
- use crate::core::announce_handler::assign_ip_address_to_peer;
+ use crate::announce_handler::assign_ip_address_to_peer;
#[test]
fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() {
@@ -289,7 +289,7 @@ mod tests {
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
- use crate::core::announce_handler::assign_ip_address_to_peer;
+ use crate::announce_handler::assign_ip_address_to_peer;
#[test]
fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() {
@@ -357,9 +357,9 @@ mod tests {
mod it_should_update_the_swarm_stats_for_the_torrent {
- use crate::core::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker};
- use crate::core::announce_handler::PeersWanted;
- use crate::core::core_tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer};
+ use crate::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker};
+ use crate::announce_handler::PeersWanted;
+ use crate::core_tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer};
#[tokio::test]
async fn when_the_peer_is_a_seeder() {
@@ -411,13 +411,13 @@ mod tests {
use torrust_tracker_test_helpers::configuration;
use torrust_tracker_torrent_repository::entry::EntrySync;
- use crate::core::announce_handler::tests::the_announce_handler::peer_ip;
- use crate::core::announce_handler::{AnnounceHandler, PeersWanted};
- use crate::core::core_tests::{sample_info_hash, sample_peer};
- use crate::core::databases::setup::initialize_database;
- use crate::core::torrent::manager::TorrentsManager;
- use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
- use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository;
+ use crate::announce_handler::tests::the_announce_handler::peer_ip;
+ use crate::announce_handler::{AnnounceHandler, PeersWanted};
+ use crate::core_tests::{sample_info_hash, sample_peer};
+ use crate::databases::setup::initialize_database;
+ use crate::torrent::manager::TorrentsManager;
+ use crate::torrent::repository::in_memory::InMemoryTorrentRepository;
+ use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository;
#[tokio::test]
async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() {
diff --git a/src/core/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs
similarity index 91%
rename from src/core/authentication/handler.rs
rename to packages/tracker-core/src/authentication/handler.rs
index d6477a948..1d74c7dfa 100644
--- a/src/core/authentication/handler.rs
+++ b/packages/tracker-core/src/authentication/handler.rs
@@ -8,8 +8,8 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch;
use super::key::repository::in_memory::InMemoryKeyRepository;
use super::key::repository::persisted::DatabaseKeyRepository;
use super::{key, CurrentClock, Key, PeerKey};
-use crate::core::databases;
-use crate::core::error::PeerKeyError;
+use crate::databases;
+use crate::error::PeerKeyError;
/// This type contains the info needed to add a new tracker key.
///
@@ -243,10 +243,10 @@ mod tests {
use torrust_tracker_configuration::Configuration;
use torrust_tracker_test_helpers::configuration;
- use crate::core::authentication::handler::KeysHandler;
- use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository;
- use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository;
- use crate::core::databases::setup::initialize_database;
+ use crate::authentication::handler::KeysHandler;
+ use crate::authentication::key::repository::in_memory::InMemoryKeyRepository;
+ use crate::authentication::key::repository::persisted::DatabaseKeyRepository;
+ use crate::databases::setup::initialize_database;
fn instantiate_keys_handler() -> KeysHandler {
let config = configuration::ephemeral_private();
@@ -280,7 +280,7 @@ mod tests {
use torrust_tracker_clock::clock::Time;
- use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler;
+ use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler;
use crate::CurrentClock;
#[tokio::test]
@@ -301,9 +301,9 @@ mod tests {
use torrust_tracker_clock::clock::Time;
- use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler;
- use crate::core::authentication::handler::AddKeyRequest;
- use crate::core::authentication::Key;
+ use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler;
+ use crate::authentication::handler::AddKeyRequest;
+ use crate::authentication::Key;
use crate::CurrentClock;
#[tokio::test]
@@ -329,7 +329,7 @@ mod tests {
mod with_permanent_and {
mod randomly_generated_keys {
- use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler;
+ use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler;
#[tokio::test]
async fn it_should_generate_the_key() {
@@ -343,9 +343,9 @@ mod tests {
mod pre_generated_keys {
- use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler;
- use crate::core::authentication::handler::AddKeyRequest;
- use crate::core::authentication::Key;
+ use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler;
+ use crate::authentication::handler::AddKeyRequest;
+ use crate::authentication::Key;
#[tokio::test]
async fn it_should_add_a_pre_generated_key() {
diff --git a/src/core/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs
similarity index 95%
rename from src/core/authentication/key/mod.rs
rename to packages/tracker-core/src/authentication/key/mod.rs
index 49d559e42..37fc4764b 100644
--- a/src/core/authentication/key/mod.rs
+++ b/packages/tracker-core/src/authentication/key/mod.rs
@@ -12,7 +12,7 @@
//! Keys are stored in this struct:
//!
//! ```rust,no_run
-//! use torrust_tracker_lib::core::authentication::Key;
+//! use bittorrent_tracker_core::authentication::Key;
//! use torrust_tracker_primitives::DurationSinceUnixEpoch;
//!
//! pub struct PeerKey {
@@ -28,7 +28,7 @@
//! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following:
//!
//! ```rust,no_run
-//! use torrust_tracker_lib::core::authentication;
+//! use bittorrent_tracker_core::authentication;
//! use std::time::Duration;
//!
//! let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0)));
@@ -54,9 +54,14 @@ use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc;
use torrust_tracker_located_error::{DynError, LocatedError};
use torrust_tracker_primitives::DurationSinceUnixEpoch;
-use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH;
use crate::CurrentClock;
+/// HTTP tracker authentication key length.
+///
+/// For more information see function [`generate_key`](crate::authentication::key::generate_key) to generate the
+/// [`PeerKey`](crate::authentication::PeerKey).
+pub const AUTH_KEY_LENGTH: usize = 32;
+
/// It generates a new permanent random key [`PeerKey`].
#[must_use]
pub fn generate_permanent_key() -> PeerKey {
@@ -200,7 +205,7 @@ impl Key {
/// Error returned when a key cannot be parsed from a string.
///
/// ```text
-/// use torrust_tracker_lib::core::authentication::Key;
+/// use bittorrent_tracker_core::authentication::Key;
/// use std::str::FromStr;
///
/// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ";
@@ -230,7 +235,7 @@ impl FromStr for Key {
}
/// Verification error. Error returned when an [`PeerKey`] cannot be
-/// verified with the (`crate::core::authentication::verify_key`) function.
+/// verified with the (`crate::authentication::verify_key`) function.
#[derive(Debug, Error)]
#[allow(dead_code)]
pub enum Error {
@@ -261,7 +266,7 @@ mod tests {
mod key {
use std::str::FromStr;
- use crate::core::authentication::Key;
+ use crate::authentication::Key;
#[test]
fn should_be_parsed_from_an_string() {
@@ -296,7 +301,7 @@ mod tests {
use torrust_tracker_clock::clock;
use torrust_tracker_clock::clock::stopped::Stopped as _;
- use crate::core::authentication;
+ use crate::authentication;
#[test]
fn should_be_parsed_from_an_string() {
diff --git a/src/core/authentication/key/repository/in_memory.rs b/packages/tracker-core/src/authentication/key/repository/in_memory.rs
similarity index 95%
rename from src/core/authentication/key/repository/in_memory.rs
rename to packages/tracker-core/src/authentication/key/repository/in_memory.rs
index a15f9ecfa..41d34604b 100644
--- a/src/core/authentication/key/repository/in_memory.rs
+++ b/packages/tracker-core/src/authentication/key/repository/in_memory.rs
@@ -1,4 +1,4 @@
-use crate::core::authentication::key::{Key, PeerKey};
+use crate::authentication::key::{Key, PeerKey};
/// In-memory implementation of the authentication key repository.
#[derive(Debug, Default)]
diff --git a/src/core/authentication/key/repository/mod.rs b/packages/tracker-core/src/authentication/key/repository/mod.rs
similarity index 100%
rename from src/core/authentication/key/repository/mod.rs
rename to packages/tracker-core/src/authentication/key/repository/mod.rs
diff --git a/src/core/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs
similarity index 92%
rename from src/core/authentication/key/repository/persisted.rs
rename to packages/tracker-core/src/authentication/key/repository/persisted.rs
index 736a409eb..322ab2913 100644
--- a/src/core/authentication/key/repository/persisted.rs
+++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs
@@ -1,7 +1,7 @@
use std::sync::Arc;
-use crate::core::authentication::key::{Key, PeerKey};
-use crate::core::databases::{self, Database};
+use crate::authentication::key::{Key, PeerKey};
+use crate::databases::{self, Database};
/// The database repository for the authentication keys.
pub struct DatabaseKeyRepository {
diff --git a/src/core/authentication/mod.rs b/packages/tracker-core/src/authentication/mod.rs
similarity index 86%
rename from src/core/authentication/mod.rs
rename to packages/tracker-core/src/authentication/mod.rs
index eddcc1ae7..9609733da 100644
--- a/src/core/authentication/mod.rs
+++ b/packages/tracker-core/src/authentication/mod.rs
@@ -22,12 +22,12 @@ mod tests {
use torrust_tracker_configuration::Configuration;
use torrust_tracker_test_helpers::configuration;
- use crate::core::authentication::handler::KeysHandler;
- use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository;
- use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository;
- use crate::core::authentication::service;
- use crate::core::authentication::service::AuthenticationService;
- use crate::core::databases::setup::initialize_database;
+ use crate::authentication::handler::KeysHandler;
+ use crate::authentication::key::repository::in_memory::InMemoryKeyRepository;
+ use crate::authentication::key::repository::persisted::DatabaseKeyRepository;
+ use crate::authentication::service;
+ use crate::authentication::service::AuthenticationService;
+ use crate::databases::setup::initialize_database;
fn instantiate_keys_manager_and_authentication() -> (Arc, Arc) {
let config = configuration::ephemeral_private();
@@ -97,11 +97,11 @@ mod tests {
mod randomly_generated_keys {
use std::time::Duration;
- use crate::core::authentication::tests::the_tracker_configured_as_private::{
+ use crate::authentication::tests::the_tracker_configured_as_private::{
instantiate_keys_manager_and_authentication,
instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled,
};
- use crate::core::authentication::Key;
+ use crate::authentication::Key;
#[tokio::test]
async fn it_should_authenticate_a_peer_with_the_key() {
@@ -132,12 +132,12 @@ mod tests {
mod pre_generated_keys {
- use crate::core::authentication::handler::AddKeyRequest;
- use crate::core::authentication::tests::the_tracker_configured_as_private::{
+ use crate::authentication::handler::AddKeyRequest;
+ use crate::authentication::tests::the_tracker_configured_as_private::{
instantiate_keys_manager_and_authentication,
instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled,
};
- use crate::core::authentication::Key;
+ use crate::authentication::Key;
#[tokio::test]
async fn it_should_authenticate_a_peer_with_the_key() {
@@ -177,7 +177,7 @@ mod tests {
mod with_permanent_and {
mod randomly_generated_keys {
- use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication;
+ use crate::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication;
#[tokio::test]
async fn it_should_authenticate_a_peer_with_the_key() {
@@ -192,9 +192,9 @@ mod tests {
}
mod pre_generated_keys {
- use crate::core::authentication::handler::AddKeyRequest;
- use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication;
- use crate::core::authentication::Key;
+ use crate::authentication::handler::AddKeyRequest;
+ use crate::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication;
+ use crate::authentication::Key;
#[tokio::test]
async fn it_should_authenticate_a_peer_with_the_key() {
diff --git a/src/core/authentication/service.rs b/packages/tracker-core/src/authentication/service.rs
similarity index 93%
rename from src/core/authentication/service.rs
rename to packages/tracker-core/src/authentication/service.rs
index d100e3a70..3e32bfbcb 100644
--- a/src/core/authentication/service.rs
+++ b/packages/tracker-core/src/authentication/service.rs
@@ -79,9 +79,9 @@ mod tests {
use torrust_tracker_test_helpers::configuration;
- use crate::core::authentication;
- use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository;
- use crate::core::authentication::service::AuthenticationService;
+ use crate::authentication;
+ use crate::authentication::key::repository::in_memory::InMemoryKeyRepository;
+ use crate::authentication::service::AuthenticationService;
fn instantiate_authentication() -> AuthenticationService {
let config = configuration::ephemeral_private();
diff --git a/src/core/core_tests.rs b/packages/tracker-core/src/core_tests.rs
similarity index 100%
rename from src/core/core_tests.rs
rename to packages/tracker-core/src/core_tests.rs
diff --git a/src/core/databases/driver.rs b/packages/tracker-core/src/databases/driver.rs
similarity index 90%
rename from src/core/databases/driver.rs
rename to packages/tracker-core/src/databases/driver.rs
index b5cb797aa..7b532f3f0 100644
--- a/src/core/databases/driver.rs
+++ b/packages/tracker-core/src/databases/driver.rs
@@ -30,8 +30,8 @@ pub enum Driver {
/// Example for `SQLite3`:
///
/// ```text
-/// use torrust_tracker_lib::core::databases;
-/// use torrust_tracker_lib::core::databases::driver::Driver;
+/// use bittorrent_tracker_core::databases;
+/// use bittorrent_tracker_core::databases::driver::Driver;
///
/// let db_driver = Driver::Sqlite3;
/// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string();
@@ -41,8 +41,8 @@ pub enum Driver {
/// Example for `MySQL`:
///
/// ```text
-/// use torrust_tracker_lib::core::databases;
-/// use torrust_tracker_lib::core::databases::driver::Driver;
+/// use bittorrent_tracker_core::databases;
+/// use bittorrent_tracker_core::databases::driver::Driver;
///
/// let db_driver = Driver::MySQL;
/// let db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker".to_string();
diff --git a/src/core/databases/error.rs b/packages/tracker-core/src/databases/error.rs
similarity index 100%
rename from src/core/databases/error.rs
rename to packages/tracker-core/src/databases/error.rs
diff --git a/src/core/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs
similarity index 98%
rename from src/core/databases/mod.rs
rename to packages/tracker-core/src/databases/mod.rs
index dec6b799d..9b9ac8e9e 100644
--- a/src/core/databases/mod.rs
+++ b/packages/tracker-core/src/databases/mod.rs
@@ -55,7 +55,7 @@ use bittorrent_primitives::info_hash::InfoHash;
use torrust_tracker_primitives::PersistentTorrents;
use self::error::Error;
-use crate::core::authentication::{self, Key};
+use crate::authentication::{self, Key};
struct Builder
where
@@ -200,7 +200,7 @@ pub trait Database: Sync + Send {
/// It gets an expiring authentication key from the database.
///
- /// It returns `Some(PeerKey)` if a [`PeerKey`](crate::core::authentication::PeerKey)
+ /// It returns `Some(PeerKey)` if a [`PeerKey`](crate::authentication::PeerKey)
/// with the input [`Key`] exists, `None` otherwise.
///
/// # Context: Authentication Keys
diff --git a/src/core/databases/mysql.rs b/packages/tracker-core/src/databases/mysql.rs
similarity index 98%
rename from src/core/databases/mysql.rs
rename to packages/tracker-core/src/databases/mysql.rs
index 213f6300a..fb39b781d 100644
--- a/src/core/databases/mysql.rs
+++ b/packages/tracker-core/src/databases/mysql.rs
@@ -11,8 +11,8 @@ use torrust_tracker_primitives::PersistentTorrents;
use super::driver::Driver;
use super::{Database, Error};
-use crate::core::authentication::{self, Key};
-use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH;
+use crate::authentication::key::AUTH_KEY_LENGTH;
+use crate::authentication::{self, Key};
const DRIVER: Driver = Driver::MySQL;
diff --git a/src/core/databases/setup.rs b/packages/tracker-core/src/databases/setup.rs
similarity index 100%
rename from src/core/databases/setup.rs
rename to packages/tracker-core/src/databases/setup.rs
diff --git a/src/core/databases/sqlite.rs b/packages/tracker-core/src/databases/sqlite.rs
similarity index 99%
rename from src/core/databases/sqlite.rs
rename to packages/tracker-core/src/databases/sqlite.rs
index 6fe9ac599..a7552ec11 100644
--- a/src/core/databases/sqlite.rs
+++ b/packages/tracker-core/src/databases/sqlite.rs
@@ -11,7 +11,7 @@ use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents};
use super::driver::Driver;
use super::{Database, Error};
-use crate::core::authentication::{self, Key};
+use crate::authentication::{self, Key};
const DRIVER: Driver = Driver::Sqlite3;
diff --git a/src/core/error.rs b/packages/tracker-core/src/error.rs
similarity index 100%
rename from src/core/error.rs
rename to packages/tracker-core/src/error.rs
diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs
new file mode 100644
index 000000000..2fb2d936d
--- /dev/null
+++ b/packages/tracker-core/src/lib.rs
@@ -0,0 +1,585 @@
+//! The core `tracker` module contains the generic `BitTorrent` tracker logic which is independent of the delivery layer.
+//!
+//! It contains the tracker services and their dependencies. It's a domain layer which does not
+//! specify how the end user should connect to the `Tracker`.
+//!
+//! Typically this module is intended to be used by higher modules like:
+//!
+//! - A UDP tracker
+//! - A HTTP tracker
+//! - A tracker REST API
+//!
+//! ```text
+//! Delivery layer Domain layer
+//!
+//! HTTP tracker |
+//! UDP tracker |> Core tracker
+//! Tracker REST API |
+//! ```
+//!
+//! # Table of contents
+//!
+//! - [Tracker](#tracker)
+//! - [Announce request](#announce-request)
+//! - [Scrape request](#scrape-request)
+//! - [Torrents](#torrents)
+//! - [Peers](#peers)
+//! - [Configuration](#configuration)
+//! - [Services](#services)
+//! - [Authentication](#authentication)
+//! - [Statistics](#statistics)
+//! - [Persistence](#persistence)
+//!
+//! # Tracker
+//!
+//! The `Tracker` is the main struct in this module. `The` tracker has some groups of responsibilities:
+//!
+//! - **Core tracker**: it handles the information about torrents and peers.
+//! - **Authentication**: it handles authentication keys which are used by HTTP trackers.
+//! - **Authorization**: it handles the permission to perform requests.
+//! - **Whitelist**: when the tracker runs in `listed` or `private_listed` mode all operations are restricted to whitelisted torrents.
+//! - **Statistics**: it keeps and serves the tracker statistics.
+//!
+//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) crate docs to get more information about the tracker settings.
+//!
+//! ## Announce request
+//!
+//! Handling `announce` requests is the most important task for a `BitTorrent` tracker.
+//!
+//! A `BitTorrent` swarm is a network of peers that are all trying to download the same torrent.
+//! When a peer wants to find other peers it announces itself to the swarm via the tracker.
+//! The peer sends its data to the tracker so that the tracker can add it to the swarm.
+//! The tracker responds to the peer with the list of other peers in the swarm so that
+//! the peer can contact them to start downloading pieces of the file from them.
+//!
+//! Once you have instantiated the `AnnounceHandler` you can `announce` a new [`peer::Peer`](torrust_tracker_primitives::peer::Peer) with:
+//!
+//! ```rust,no_run
+//! use std::net::SocketAddr;
+//! use std::net::IpAddr;
+//! use std::net::Ipv4Addr;
+//! use std::str::FromStr;
+//!
+//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId};
+//! use torrust_tracker_primitives::DurationSinceUnixEpoch;
+//! use torrust_tracker_primitives::peer;
+//! use bittorrent_primitives::info_hash::InfoHash;
+//!
+//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap();
+//!
+//! let peer = peer::Peer {
+//! peer_id: PeerId(*b"-qB00000000000000001"),
+//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081),
+//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0),
+//! uploaded: NumberOfBytes::new(0),
+//! downloaded: NumberOfBytes::new(0),
+//! left: NumberOfBytes::new(0),
+//! event: AnnounceEvent::Completed,
+//! };
+//!
+//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap());
+//! ```
+//!
+//! ```text
+//! let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip).await;
+//! ```
+//!
+//! The `Tracker` returns the list of peers for the torrent with the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`,
+//! filtering out the peer that is making the `announce` request.
+//!
+//! > **NOTICE**: that the peer argument is mutable because the `Tracker` can change the peer IP if the peer is using a loopback IP.
+//!
+//! The `peer_ip` argument is the resolved peer ip. It's a common practice that trackers ignore the peer ip in the `announce` request params,
+//! and resolve the peer ip using the IP of the client making the request. As the tracker is a domain service, the peer IP must be provided
+//! for the `Tracker` user, which is usually a higher component with access the the request metadata, for example, connection data, proxy headers,
+//! etcetera.
+//!
+//! The returned struct is:
+//!
+//! ```rust,no_run
+//! use torrust_tracker_primitives::peer;
+//! use torrust_tracker_configuration::AnnouncePolicy;
+//!
+//! pub struct AnnounceData {
+//! pub peers: Vec,
+//! pub swarm_stats: SwarmMetadata,
+//! pub policy: AnnouncePolicy, // the tracker announce policy.
+//! }
+//!
+//! pub struct SwarmMetadata {
+//! pub completed: u32, // The number of peers that have ever completed downloading
+//! pub seeders: u32, // The number of active peers that have completed downloading (seeders)
+//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers)
+//! }
+//!
+//! // Core tracker configuration
+//! pub struct AnnounceInterval {
+//! // ...
+//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker
+//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this
+//! // ...
+//! }
+//! ```
+//!
+//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request:
+//!
+//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html)
+//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html)
+//! - [Vuze docs](https://wiki.vuze.com/w/Announce)
+//!
+//! ## Scrape request
+//!
+//! The `scrape` request allows clients to query metadata about the swarm in bulk.
+//!
+//! An `scrape` request includes a list of infohashes whose swarm metadata you want to collect.
+//!
+//! The returned struct is:
+//!
+//! ```rust,no_run
+//! use bittorrent_primitives::info_hash::InfoHash;
+//! use std::collections::HashMap;
+//!
+//! pub struct ScrapeData {
+//! pub files: HashMap,
+//! }
+//!
+//! pub struct SwarmMetadata {
+//! pub complete: u32, // The number of active peers that have completed downloading (seeders)
+//! pub downloaded: u32, // The number of peers that have ever completed downloading
+//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers)
+//! }
+//! ```
+//!
+//! The JSON representation of a sample `scrape` response would be like the following:
+//!
+//! ```json
+//! {
+//! 'files': {
+//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19},
+//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20}
+//! }
+//! }
+//! ```
+//!
+//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays.
+//! There are two data structures for infohashes: byte arrays and hex strings:
+//!
+//! ```rust,no_run
+//! use bittorrent_primitives::info_hash::InfoHash;
+//! use std::str::FromStr;
+//!
+//! let info_hash: InfoHash = [255u8; 20].into();
+//!
+//! assert_eq!(
+//! info_hash,
+//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap()
+//! );
+//! ```
+//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request:
+//!
+//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html)
+//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html)
+//! - [Vuze docs](https://wiki.vuze.com/w/Scrape)
+//!
+//! ## Torrents
+//!
+//! The [`torrent`] module contains all the data structures stored by the `Tracker` except for peers.
+//!
+//! We can represent the data stored in memory internally by the `Tracker` with this JSON object:
+//!
+//! ```json
+//! {
+//! "c1277613db1d28709b034a017ab2cae4be07ae10": {
+//! "completed": 0,
+//! "peers": {
+//! "-qB00000000000000001": {
+//! "peer_id": "-qB00000000000000001",
+//! "peer_addr": "2.137.87.41:1754",
+//! "updated": 1672419840,
+//! "uploaded": 120,
+//! "downloaded": 60,
+//! "left": 60,
+//! "event": "started"
+//! },
+//! "-qB00000000000000002": {
+//! "peer_id": "-qB00000000000000002",
+//! "peer_addr": "23.17.287.141:2345",
+//! "updated": 1679415984,
+//! "uploaded": 80,
+//! "downloaded": 20,
+//! "left": 40,
+//! "event": "started"
+//! }
+//! }
+//! }
+//! }
+//! ```
+//!
+//! The `Tracker` maintains an indexed-by-info-hash list of torrents. For each torrent, it stores a torrent `Entry`.
+//! The torrent entry has two attributes:
+//!
+//! - `completed`: which is hte number of peers that have completed downloading the torrent file/s. As they have completed downloading,
+//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders".
+//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request.
+//!
+//! The [`torrent`] module not only contains the original data obtained from peer via `announce` requests, it also contains
+//! aggregate data that can be derived from the original data. For example:
+//!
+//! ```rust,no_run
+//! pub struct SwarmMetadata {
+//! pub complete: u32, // The number of active peers that have completed downloading (seeders)
+//! pub downloaded: u32, // The number of peers that have ever completed downloading
+//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers)
+//! }
+//!
+//! ```
+//!
+//! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders".
+//!
+//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata`
+//! is used for the rest of cases.
+//!
+//! Refer to [`torrent`] module for more details about these data structures.
+//!
+//! ## Peers
+//!
+//! A `Peer` is the struct used by the `Tracker` to keep peers data:
+//!
+//! ```rust,no_run
+//! use std::net::SocketAddr;
+
+//! use aquatic_udp_protocol::PeerId;
+//! use torrust_tracker_primitives::DurationSinceUnixEpoch;
+//! use aquatic_udp_protocol::NumberOfBytes;
+//! use aquatic_udp_protocol::AnnounceEvent;
+//!
+//! pub struct Peer {
+//! pub peer_id: PeerId, // The peer ID
+//! pub peer_addr: SocketAddr, // Peer socket address
+//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated
+//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far
+//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far
+//! pub left: NumberOfBytes, // The number of bytes this peer still has to download
+//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped`
+//! }
+//! ```
+//!
+//! Notice that most of the attributes are obtained from the `announce` request.
+//! For example, an HTTP announce request would contain the following `GET` parameters:
+//!
+//!
+//!
+//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics.
+//!
+//! We can represent the data stored in memory with this JSON object:
+//!
+//! ```json
+//! {
+//! "c1277613db1d28709b034a017ab2cae4be07ae10": {
+//! "completed": 0,
+//! "peers": {
+//! "-qB00000000000000001": {
+//! "peer_id": "-qB00000000000000001",
+//! "peer_addr": "2.137.87.41:1754",
+//! "updated": 1672419840,
+//! "uploaded": 120,
+//! "downloaded": 60,
+//! "left": 60,
+//! "event": "started"
+//! },
+//! "-qB00000000000000002": {
+//! "peer_id": "-qB00000000000000002",
+//! "peer_addr": "23.17.287.141:2345",
+//! "updated": 1679415984,
+//! "uploaded": 80,
+//! "downloaded": 20,
+//! "left": 40,
+//! "event": "started"
+//! }
+//! }
+//! }
+//! }
+//! ```
+//!
+//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data.
+//!
+//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers
+//! that have a full version of the torrent data, also known as seeders.
+//!
+//! Refer to [`peer`](torrust_tracker_primitives::peer) for more information about peers.
+//!
+//! # Configuration
+//!
+//! You can control the behavior of this module with the module settings:
+//!
+//! ```toml
+//! [logging]
+//! threshold = "debug"
+//!
+//! [core]
+//! inactive_peer_cleanup_interval = 600
+//! listed = false
+//! private = false
+//! tracker_usage_statistics = true
+//!
+//! [core.announce_policy]
+//! interval = 120
+//! interval_min = 120
+//!
+//! [core.database]
+//! driver = "sqlite3"
+//! path = "./storage/tracker/lib/database/sqlite3.db"
+//!
+//! [core.net]
+//! on_reverse_proxy = false
+//! external_ip = "2.137.87.41"
+//!
+//! [core.tracker_policy]
+//! max_peer_timeout = 900
+//! persistent_torrent_completed_stat = false
+//! remove_peerless_torrents = true
+//! ```
+//!
+//! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options.
+//!
+//! # Services
+//!
+//! Services are domain services on top of the core tracker domain. Right now there are two types of service:
+//!
+//! - For statistics: [`crate::core::statistics::services`]
+//! - For torrents: [`crate::core::torrent::services`]
+//!
+//! Services usually format the data inside the tracker to make it easier to consume by other parts.
+//! They also decouple the internal data structure, used by the tracker, from the way we deliver that data to the consumers.
+//! The internal data structure is designed for performance or low memory consumption. And it should be changed
+//! without affecting the external consumers.
+//!
+//! Services can include extra features like pagination, for example.
+//!
+//! # Authentication
+//!
+//! One of the core `Tracker` responsibilities is to create and keep authentication keys. Auth keys are used by HTTP trackers
+//! when the tracker is running in `private` or `private_listed` mode.
+//!
+//! HTTP tracker's clients need to obtain an auth key before starting requesting the tracker. Once the get one they have to include
+//! a `PATH` param with the key in all the HTTP requests. For example, when a peer wants to `announce` itself it has to use the
+//! HTTP tracker endpoint `GET /announce/:key`.
+//!
+//! The common way to obtain the keys is by using the tracker API directly or via other applications like the [Torrust Index](https://github.com/torrust/torrust-index).
+//!
+//! To learn more about tracker authentication, refer to the following modules :
+//!
+//! - [`authentication`] module.
+//! - [`core`](crate::core) module.
+//! - [`http`](crate::servers::http) module.
+//!
+//! # Statistics
+//!
+//! The `Tracker` keeps metrics for some events:
+//!
+//! ```rust,no_run
+//! pub struct Metrics {
+//! // IP version 4
+//!
+//! // HTTP tracker
+//! pub tcp4_connections_handled: u64,
+//! pub tcp4_announces_handled: u64,
+//! pub tcp4_scrapes_handled: u64,
+//!
+//! // UDP tracker
+//! pub udp4_connections_handled: u64,
+//! pub udp4_announces_handled: u64,
+//! pub udp4_scrapes_handled: u64,
+//!
+//! // IP version 6
+//!
+//! // HTTP tracker
+//! pub tcp6_connections_handled: u64,
+//! pub tcp6_announces_handled: u64,
+//! pub tcp6_scrapes_handled: u64,
+//!
+//! // UDP tracker
+//! pub udp6_connections_handled: u64,
+//! pub udp6_announces_handled: u64,
+//! pub udp6_scrapes_handled: u64,
+//! }
+//! ```
+//!
+//! The metrics maintained by the `Tracker` are:
+//!
+//! - `connections_handled`: number of connections handled by the tracker
+//! - `announces_handled`: number of `announce` requests handled by the tracker
+//! - `scrapes_handled`: number of `scrape` handled requests by the tracker
+//!
+//! > **NOTICE**: as the HTTP tracker does not have an specific `connection` request like the UDP tracker, `connections_handled` are
+//! > increased on every `announce` and `scrape` requests.
+//!
+//! The tracker exposes an event sender API that allows the tracker users to send events. When a higher application service handles a
+//! `connection` , `announce` or `scrape` requests, it notifies the `Tracker` by sending statistics events.
+//!
+//! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4.
+//!
+//! ```text
+//! stats_event_sender.send_stats_event(statistics::event::Event::Tcp4Announce).await
+//! ```
+//!
+//! Refer to [`statistics`] module for more information about statistics.
+//!
+//! # Persistence
+//!
+//! Right now the `Tracker` is responsible for storing and load data into and
+//! from the database, when persistence is enabled.
+//!
+//! There are three types of persistent object:
+//!
+//! - Authentication keys (only expiring keys)
+//! - Torrent whitelist
+//! - Torrent metrics
+//!
+//! Refer to [`databases`] module for more information about persistence.
+pub mod announce_handler;
+pub mod authentication;
+pub mod databases;
+pub mod error;
+pub mod scrape_handler;
+pub mod statistics;
+pub mod torrent;
+pub mod whitelist;
+
+pub mod core_tests;
+pub mod peer_tests;
+
+use torrust_tracker_clock::clock;
+/// This code needs to be copied into each crate.
+/// Working version, for production.
+#[cfg(not(test))]
+#[allow(dead_code)]
+pub(crate) type CurrentClock = clock::Working;
+
+/// Stopped version, for testing.
+#[cfg(test)]
+#[allow(dead_code)]
+pub(crate) type CurrentClock = clock::Stopped;
+
+#[cfg(test)]
+mod tests {
+ mod the_tracker {
+ use std::net::{IpAddr, Ipv4Addr};
+ use std::str::FromStr;
+ use std::sync::Arc;
+
+ use torrust_tracker_test_helpers::configuration;
+
+ use crate::announce_handler::AnnounceHandler;
+ use crate::core_tests::initialize_handlers;
+ use crate::scrape_handler::ScrapeHandler;
+
+ fn initialize_handlers_for_public_tracker() -> (Arc, Arc) {
+ let config = configuration::ephemeral_public();
+ initialize_handlers(&config)
+ }
+
+ fn initialize_handlers_for_listed_tracker() -> (Arc, Arc) {
+ let config = configuration::ephemeral_listed();
+ initialize_handlers(&config)
+ }
+
+ // The client peer IP
+ fn peer_ip() -> IpAddr {
+ IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap())
+ }
+
+ mod for_all_config_modes {
+
+ mod handling_a_scrape_request {
+
+ use std::net::{IpAddr, Ipv4Addr};
+
+ use bittorrent_primitives::info_hash::InfoHash;
+ use torrust_tracker_primitives::core::ScrapeData;
+ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata;
+
+ use crate::announce_handler::PeersWanted;
+ use crate::core_tests::{complete_peer, incomplete_peer};
+ use crate::tests::the_tracker::initialize_handlers_for_public_tracker;
+
+ #[tokio::test]
+ async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() {
+ let (announce_handler, scrape_handler) = initialize_handlers_for_public_tracker();
+
+ let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237
+
+ // Announce a "complete" peer for the torrent
+ let mut complete_peer = complete_peer();
+ announce_handler.announce(
+ &info_hash,
+ &mut complete_peer,
+ &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)),
+ &PeersWanted::All,
+ );
+
+ // Announce an "incomplete" peer for the torrent
+ let mut incomplete_peer = incomplete_peer();
+ announce_handler.announce(
+ &info_hash,
+ &mut incomplete_peer,
+ &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)),
+ &PeersWanted::All,
+ );
+
+ // Scrape
+ let scrape_data = scrape_handler.scrape(&vec![info_hash]).await;
+
+ // The expected swarm metadata for the file
+ let mut expected_scrape_data = ScrapeData::empty();
+ expected_scrape_data.add_file(
+ &info_hash,
+ SwarmMetadata {
+ complete: 0, // the "complete" peer does not count because it was not previously known
+ downloaded: 0,
+ incomplete: 1, // the "incomplete" peer we have just announced
+ },
+ );
+
+ assert_eq!(scrape_data, expected_scrape_data);
+ }
+ }
+ }
+
+ mod configured_as_whitelisted {
+
+ mod handling_a_scrape_request {
+
+ use bittorrent_primitives::info_hash::InfoHash;
+ use torrust_tracker_primitives::core::ScrapeData;
+ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata;
+
+ use crate::announce_handler::PeersWanted;
+ use crate::core_tests::{complete_peer, incomplete_peer};
+ use crate::tests::the_tracker::{initialize_handlers_for_listed_tracker, peer_ip};
+
+ #[tokio::test]
+ async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() {
+ let (announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker();
+
+ let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237
+
+ let mut peer = incomplete_peer();
+ announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All);
+
+ // Announce twice to force non zeroed swarm metadata
+ let mut peer = complete_peer();
+ announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All);
+
+ let scrape_data = scrape_handler.scrape(&vec![info_hash]).await;
+
+ // The expected zeroed swarm metadata for the file
+ let mut expected_scrape_data = ScrapeData::empty();
+ expected_scrape_data.add_file(&info_hash, SwarmMetadata::zeroed());
+
+ assert_eq!(scrape_data, expected_scrape_data);
+ }
+ }
+ }
+ }
+}
diff --git a/src/core/peer_tests.rs b/packages/tracker-core/src/peer_tests.rs
similarity index 100%
rename from src/core/peer_tests.rs
rename to packages/tracker-core/src/peer_tests.rs
diff --git a/src/core/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs
similarity index 95%
rename from src/core/scrape_handler.rs
rename to packages/tracker-core/src/scrape_handler.rs
index 33bb6ca6a..60d15de71 100644
--- a/src/core/scrape_handler.rs
+++ b/packages/tracker-core/src/scrape_handler.rs
@@ -54,9 +54,9 @@ mod tests {
use torrust_tracker_test_helpers::configuration;
use super::ScrapeHandler;
- use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
- use crate::core::whitelist::repository::in_memory::InMemoryWhitelist;
- use crate::core::whitelist::{self};
+ use crate::torrent::repository::in_memory::InMemoryTorrentRepository;
+ use crate::whitelist::repository::in_memory::InMemoryWhitelist;
+ use crate::whitelist::{self};
fn scrape_handler() -> ScrapeHandler {
let config = configuration::ephemeral_public();
diff --git a/src/core/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs
similarity index 96%
rename from src/core/statistics/event/handler.rs
rename to packages/tracker-core/src/statistics/event/handler.rs
index 3c435145a..93ac05dde 100644
--- a/src/core/statistics/event/handler.rs
+++ b/packages/tracker-core/src/statistics/event/handler.rs
@@ -1,5 +1,5 @@
-use crate::core::statistics::event::{Event, UdpResponseKind};
-use crate::core::statistics::repository::Repository;
+use crate::statistics::event::{Event, UdpResponseKind};
+use crate::statistics::repository::Repository;
pub async fn handle_event(event: Event, stats_repository: &Repository) {
match event {
@@ -102,9 +102,9 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) {
#[cfg(test)]
mod tests {
- use crate::core::statistics::event::handler::handle_event;
- use crate::core::statistics::event::Event;
- use crate::core::statistics::repository::Repository;
+ use crate::statistics::event::handler::handle_event;
+ use crate::statistics::event::Event;
+ use crate::statistics::repository::Repository;
#[tokio::test]
async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() {
diff --git a/src/core/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs
similarity index 84%
rename from src/core/statistics/event/listener.rs
rename to packages/tracker-core/src/statistics/event/listener.rs
index 89ed7b41a..f1a2e25de 100644
--- a/src/core/statistics/event/listener.rs
+++ b/packages/tracker-core/src/statistics/event/listener.rs
@@ -2,7 +2,7 @@ use tokio::sync::mpsc;
use super::handler::handle_event;
use super::Event;
-use crate::core::statistics::repository::Repository;
+use crate::statistics::repository::Repository;
pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) {
while let Some(event) = receiver.recv().await {
diff --git a/src/core/statistics/event/mod.rs b/packages/tracker-core/src/statistics/event/mod.rs
similarity index 100%
rename from src/core/statistics/event/mod.rs
rename to packages/tracker-core/src/statistics/event/mod.rs
diff --git a/src/core/statistics/event/sender.rs b/packages/tracker-core/src/statistics/event/sender.rs
similarity index 100%
rename from src/core/statistics/event/sender.rs
rename to packages/tracker-core/src/statistics/event/sender.rs
diff --git a/src/core/statistics/keeper.rs b/packages/tracker-core/src/statistics/keeper.rs
similarity index 93%
rename from src/core/statistics/keeper.rs
rename to packages/tracker-core/src/statistics/keeper.rs
index 5427734e1..a3d4542f7 100644
--- a/src/core/statistics/keeper.rs
+++ b/packages/tracker-core/src/statistics/keeper.rs
@@ -51,9 +51,9 @@ impl Keeper {
#[cfg(test)]
mod tests {
- use crate::core::statistics::event::Event;
- use crate::core::statistics::keeper::Keeper;
- use crate::core::statistics::metrics::Metrics;
+ use crate::statistics::event::Event;
+ use crate::statistics::keeper::Keeper;
+ use crate::statistics::metrics::Metrics;
#[tokio::test]
async fn should_contain_the_tracker_statistics() {
diff --git a/src/core/statistics/metrics.rs b/packages/tracker-core/src/statistics/metrics.rs
similarity index 100%
rename from src/core/statistics/metrics.rs
rename to packages/tracker-core/src/statistics/metrics.rs
diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs
new file mode 100644
index 000000000..2ffbc0c8f
--- /dev/null
+++ b/packages/tracker-core/src/statistics/mod.rs
@@ -0,0 +1,32 @@
+//! Structs to collect and keep tracker metrics.
+//!
+//! The tracker collects metrics such as:
+//!
+//! - Number of connections handled
+//! - Number of `announce` requests handled
+//! - Number of `scrape` request handled
+//!
+//! These metrics are collected for each connection type: UDP and HTTP and
+//! also for each IP version used by the peers: IPv4 and IPv6.
+//!
+//! > Notice: that UDP tracker have an specific `connection` request. For the
+//! > `HTTP` metrics the counter counts one connection for each `announce` or
+//! > `scrape` request.
+//!
+//! The data is collected by using an `event-sender -> event listener` model.
+//!
+//! The tracker uses a [`Sender`](crate::core::statistics::event::sender::Sender)
+//! instance to send an event.
+//!
+//! The [`statistics::keeper::Keeper`](crate::core::statistics::keeper::Keeper) listens to new
+//! events and uses the [`statistics::repository::Repository`](crate::core::statistics::repository::Repository) to
+//! upgrade and store metrics.
+//!
+//! See the [`statistics::event::Event`](crate::core::statistics::event::Event) enum to check
+//! which events are available.
+pub mod event;
+pub mod keeper;
+pub mod metrics;
+pub mod repository;
+pub mod services;
+pub mod setup;
diff --git a/src/core/statistics/repository.rs b/packages/tracker-core/src/statistics/repository.rs
similarity index 100%
rename from src/core/statistics/repository.rs
rename to packages/tracker-core/src/statistics/repository.rs
diff --git a/packages/tracker-core/src/statistics/services.rs b/packages/tracker-core/src/statistics/services.rs
new file mode 100644
index 000000000..196c6b340
--- /dev/null
+++ b/packages/tracker-core/src/statistics/services.rs
@@ -0,0 +1,55 @@
+//! Statistics services.
+//!
+//! It includes:
+//!
+//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics.
+//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics).
+//!
+//! Tracker metrics are collected using a Publisher-Subscribe pattern.
+//!
+//! The factory function builds two structs:
+//!
+//! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender)
+//! - An statistics [`Repository`]
+//!
+//! ```text
+//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics);
+//! ```
+//!
+//! The statistics repository is responsible for storing the metrics in memory.
+//! The statistics event sender allows sending events related to metrics.
+//! There is an event listener that is receiving all the events and processing them with an event handler.
+//! Then, the event handler updates the metrics depending on the received event.
+//!
+//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::event::Event::Udp4Connect):
+//!
+//! ```text
+//! let result = event_sender.send_event(Event::Udp4Connect).await;
+//! ```
+//!
+//! Eventually the counter for UDP connections from IPv4 peers will be increased.
+//!
+//! ```rust,no_run
+//! pub struct Metrics {
+//! // ...
+//! pub udp4_connections_handled: u64, // This will be incremented
+//! // ...
+//! }
+//! ```
+use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics;
+
+use crate::statistics::metrics::Metrics;
+
+/// All the metrics collected by the tracker.
+#[derive(Debug, PartialEq)]
+pub struct TrackerMetrics {
+ /// Domain level metrics.
+ ///
+ /// General metrics for all torrents (number of seeders, leechers, etcetera)
+ pub torrents_metrics: TorrentsMetrics,
+
+ /// Application level metrics. Usage statistics/metrics.
+ ///
+ /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera)
+ pub protocol_metrics: Metrics,
+}
diff --git a/src/core/statistics/setup.rs b/packages/tracker-core/src/statistics/setup.rs
similarity index 98%
rename from src/core/statistics/setup.rs
rename to packages/tracker-core/src/statistics/setup.rs
index e440a709c..701392176 100644
--- a/src/core/statistics/setup.rs
+++ b/packages/tracker-core/src/statistics/setup.rs
@@ -1,7 +1,7 @@
//! Setup for the tracker statistics.
//!
//! The [`factory`] function builds the structs needed for handling the tracker metrics.
-use crate::core::statistics;
+use crate::statistics;
/// It builds the structs needed for handling the tracker metrics.
///
diff --git a/src/core/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs
similarity index 97%
rename from src/core/torrent/manager.rs
rename to packages/tracker-core/src/torrent/manager.rs
index 261376755..4199e9944 100644
--- a/src/core/torrent/manager.rs
+++ b/packages/tracker-core/src/torrent/manager.rs
@@ -6,8 +6,7 @@ use torrust_tracker_configuration::Core;
use super::repository::in_memory::InMemoryTorrentRepository;
use super::repository::persisted::DatabasePersistentTorrentRepository;
-use crate::core::databases;
-use crate::CurrentClock;
+use crate::{databases, CurrentClock};
pub struct TorrentsManager {
/// The tracker configuration.
diff --git a/src/core/torrent/mod.rs b/packages/tracker-core/src/torrent/mod.rs
similarity index 100%
rename from src/core/torrent/mod.rs
rename to packages/tracker-core/src/torrent/mod.rs
diff --git a/src/core/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs
similarity index 98%
rename from src/core/torrent/repository/in_memory.rs
rename to packages/tracker-core/src/torrent/repository/in_memory.rs
index 2e80a2e9b..b9979577a 100644
--- a/src/core/torrent/repository/in_memory.rs
+++ b/packages/tracker-core/src/torrent/repository/in_memory.rs
@@ -11,7 +11,7 @@ use torrust_tracker_torrent_repository::entry::EntrySync;
use torrust_tracker_torrent_repository::repository::Repository;
use torrust_tracker_torrent_repository::EntryMutexStd;
-use crate::core::torrent::Torrents;
+use crate::torrent::Torrents;
/// The in-memory torrents repository.
///
@@ -114,8 +114,8 @@ mod tests {
use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics;
use torrust_tracker_primitives::DurationSinceUnixEpoch;
- use crate::core::core_tests::{leecher, sample_info_hash, sample_peer};
- use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
+ use crate::core_tests::{leecher, sample_info_hash, sample_peer};
+ use crate::torrent::repository::in_memory::InMemoryTorrentRepository;
/// It generates a peer id from a number where the number is the last
/// part of the peer ID. For example, for `12` it returns
diff --git a/src/core/torrent/repository/mod.rs b/packages/tracker-core/src/torrent/repository/mod.rs
similarity index 100%
rename from src/core/torrent/repository/mod.rs
rename to packages/tracker-core/src/torrent/repository/mod.rs
diff --git a/src/core/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs
similarity index 94%
rename from src/core/torrent/repository/persisted.rs
rename to packages/tracker-core/src/torrent/repository/persisted.rs
index 86a3db0e3..77a9c23eb 100644
--- a/src/core/torrent/repository/persisted.rs
+++ b/packages/tracker-core/src/torrent/repository/persisted.rs
@@ -3,8 +3,8 @@ use std::sync::Arc;
use bittorrent_primitives::info_hash::InfoHash;
use torrust_tracker_primitives::PersistentTorrents;
-use crate::core::databases::error::Error;
-use crate::core::databases::Database;
+use crate::databases::error::Error;
+use crate::databases::Database;
/// Torrent repository implementation that persists the torrents in a database.
///
diff --git a/src/core/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs
similarity index 85%
rename from src/core/torrent/services.rs
rename to packages/tracker-core/src/torrent/services.rs
index 5a4810412..2275f20d0 100644
--- a/src/core/torrent/services.rs
+++ b/packages/tracker-core/src/torrent/services.rs
@@ -11,7 +11,7 @@ use torrust_tracker_primitives::pagination::Pagination;
use torrust_tracker_primitives::peer;
use torrust_tracker_torrent_repository::entry::EntrySync;
-use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
+use crate::torrent::repository::in_memory::InMemoryTorrentRepository;
/// It contains all the information the tracker has about a torrent
#[derive(Debug, PartialEq)]
@@ -44,10 +44,8 @@ pub struct BasicInfo {
}
/// It returns all the information the tracker has about one torrent in a [Info] struct.
-pub async fn get_torrent_info(
- in_memory_torrent_repository: Arc,
- info_hash: &InfoHash,
-) -> Option {
+#[must_use]
+pub fn get_torrent_info(in_memory_torrent_repository: &Arc, info_hash: &InfoHash) -> Option {
let torrent_entry_option = in_memory_torrent_repository.get(info_hash);
let torrent_entry = torrent_entry_option?;
@@ -68,8 +66,9 @@ pub async fn get_torrent_info(
}
/// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list.
-pub async fn get_torrents_page(
- in_memory_torrent_repository: Arc,
+#[must_use]
+pub fn get_torrents_page(
+ in_memory_torrent_repository: &Arc,
pagination: Option<&Pagination>,
) -> Vec {
let mut basic_infos: Vec = vec![];
@@ -89,10 +88,8 @@ pub async fn get_torrents_page(
}
/// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list.
-pub async fn get_torrents(
- in_memory_torrent_repository: Arc,
- info_hashes: &[InfoHash],
-) -> Vec {
+#[must_use]
+pub fn get_torrents(in_memory_torrent_repository: &Arc, info_hashes: &[InfoHash]) -> Vec {
let mut basic_infos: Vec = vec![];
for info_hash in info_hashes {
@@ -135,19 +132,18 @@ mod tests {
use bittorrent_primitives::info_hash::InfoHash;
- use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
- use crate::core::torrent::services::tests::sample_peer;
- use crate::core::torrent::services::{get_torrent_info, Info};
+ use crate::torrent::repository::in_memory::InMemoryTorrentRepository;
+ use crate::torrent::services::tests::sample_peer;
+ use crate::torrent::services::{get_torrent_info, Info};
#[tokio::test]
async fn should_return_none_if_the_tracker_does_not_have_the_torrent() {
let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default());
let torrent_info = get_torrent_info(
- in_memory_torrent_repository.clone(),
+ &in_memory_torrent_repository,
&InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(), // DevSkim: ignore DS173237
- )
- .await;
+ );
assert!(torrent_info.is_none());
}
@@ -160,9 +156,7 @@ mod tests {
let info_hash = InfoHash::from_str(&hash).unwrap();
let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer());
- let torrent_info = get_torrent_info(in_memory_torrent_repository.clone(), &info_hash)
- .await
- .unwrap();
+ let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).unwrap();
assert_eq!(
torrent_info,
@@ -184,15 +178,15 @@ mod tests {
use bittorrent_primitives::info_hash::InfoHash;
- use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
- use crate::core::torrent::services::tests::sample_peer;
- use crate::core::torrent::services::{get_torrents_page, BasicInfo, Pagination};
+ use crate::torrent::repository::in_memory::InMemoryTorrentRepository;
+ use crate::torrent::services::tests::sample_peer;
+ use crate::torrent::services::{get_torrents_page, BasicInfo, Pagination};
#[tokio::test]
async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() {
let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default());
- let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await;
+ let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default()));
assert_eq!(torrents, vec![]);
}
@@ -206,7 +200,7 @@ mod tests {
let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer());
- let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await;
+ let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default()));
assert_eq!(
torrents,
@@ -235,7 +229,7 @@ mod tests {
let offset = 0;
let limit = 1;
- let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::new(offset, limit))).await;
+ let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit)));
assert_eq!(torrents.len(), 1);
}
@@ -256,7 +250,7 @@ mod tests {
let offset = 1;
let limit = 4000;
- let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::new(offset, limit))).await;
+ let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit)));
assert_eq!(torrents.len(), 1);
assert_eq!(
@@ -282,7 +276,7 @@ mod tests {
let info_hash2 = InfoHash::from_str(&hash2).unwrap();
let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer());
- let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await;
+ let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default()));
assert_eq!(
torrents,
diff --git a/src/core/whitelist/authorization.rs b/packages/tracker-core/src/whitelist/authorization.rs
similarity index 93%
rename from src/core/whitelist/authorization.rs
rename to packages/tracker-core/src/whitelist/authorization.rs
index 1a6d8b758..285f6613e 100644
--- a/src/core/whitelist/authorization.rs
+++ b/packages/tracker-core/src/whitelist/authorization.rs
@@ -6,7 +6,7 @@ use torrust_tracker_configuration::Core;
use tracing::instrument;
use super::repository::in_memory::InMemoryWhitelist;
-use crate::core::error::Error;
+use crate::error::Error;
pub struct WhitelistAuthorization {
/// Core tracker configuration.
@@ -64,8 +64,8 @@ mod tests {
mod configured_as_whitelisted {
mod handling_authorization {
- use crate::core::core_tests::sample_info_hash;
- use crate::core::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker;
+ use crate::core_tests::sample_info_hash;
+ use crate::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker;
#[tokio::test]
async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() {
diff --git a/src/core/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs
similarity index 91%
rename from src/core/whitelist/manager.rs
rename to packages/tracker-core/src/whitelist/manager.rs
index 0d9751994..c78a59470 100644
--- a/src/core/whitelist/manager.rs
+++ b/packages/tracker-core/src/whitelist/manager.rs
@@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash;
use super::repository::in_memory::InMemoryWhitelist;
use super::repository::persisted::DatabaseWhitelist;
-use crate::core::databases;
+use crate::databases;
/// It handles the list of allowed torrents. Only for listed trackers.
pub struct WhitelistManager {
@@ -97,8 +97,8 @@ mod tests {
use torrust_tracker_test_helpers::configuration;
- use crate::core::whitelist::manager::WhitelistManager;
- use crate::core::whitelist::whitelist_tests::initialize_whitelist_services;
+ use crate::whitelist::manager::WhitelistManager;
+ use crate::whitelist::whitelist_tests::initialize_whitelist_services;
fn initialize_whitelist_manager_for_whitelisted_tracker() -> Arc {
let config = configuration::ephemeral_listed();
@@ -111,8 +111,8 @@ mod tests {
mod configured_as_whitelisted {
mod handling_the_torrent_whitelist {
- use crate::core::core_tests::sample_info_hash;
- use crate::core::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker;
+ use crate::core_tests::sample_info_hash;
+ use crate::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker;
#[tokio::test]
async fn it_should_add_a_torrent_to_the_whitelist() {
@@ -139,8 +139,8 @@ mod tests {
}
mod persistence {
- use crate::core::core_tests::sample_info_hash;
- use crate::core::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker;
+ use crate::core_tests::sample_info_hash;
+ use crate::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker;
#[tokio::test]
async fn it_should_load_the_whitelist_from_the_database() {
diff --git a/src/core/whitelist/mod.rs b/packages/tracker-core/src/whitelist/mod.rs
similarity index 88%
rename from src/core/whitelist/mod.rs
rename to packages/tracker-core/src/whitelist/mod.rs
index 1f5f87626..8521485f7 100644
--- a/src/core/whitelist/mod.rs
+++ b/packages/tracker-core/src/whitelist/mod.rs
@@ -10,8 +10,8 @@ mod tests {
mod configured_as_whitelisted {
mod handling_authorization {
- use crate::core::core_tests::sample_info_hash;
- use crate::core::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker;
+ use crate::core_tests::sample_info_hash;
+ use crate::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker;
#[tokio::test]
async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() {
diff --git a/src/core/whitelist/repository/in_memory.rs b/packages/tracker-core/src/whitelist/repository/in_memory.rs
similarity index 94%
rename from src/core/whitelist/repository/in_memory.rs
rename to packages/tracker-core/src/whitelist/repository/in_memory.rs
index f023c1610..befd6fed6 100644
--- a/src/core/whitelist/repository/in_memory.rs
+++ b/packages/tracker-core/src/whitelist/repository/in_memory.rs
@@ -33,8 +33,8 @@ impl InMemoryWhitelist {
#[cfg(test)]
mod tests {
- use crate::core::core_tests::sample_info_hash;
- use crate::core::whitelist::repository::in_memory::InMemoryWhitelist;
+ use crate::core_tests::sample_info_hash;
+ use crate::whitelist::repository::in_memory::InMemoryWhitelist;
#[tokio::test]
async fn should_allow_adding_a_new_torrent_to_the_whitelist() {
diff --git a/src/core/whitelist/repository/mod.rs b/packages/tracker-core/src/whitelist/repository/mod.rs
similarity index 100%
rename from src/core/whitelist/repository/mod.rs
rename to packages/tracker-core/src/whitelist/repository/mod.rs
diff --git a/src/core/whitelist/repository/persisted.rs b/packages/tracker-core/src/whitelist/repository/persisted.rs
similarity index 97%
rename from src/core/whitelist/repository/persisted.rs
rename to packages/tracker-core/src/whitelist/repository/persisted.rs
index fd56d56b5..c3c4a2601 100644
--- a/src/core/whitelist/repository/persisted.rs
+++ b/packages/tracker-core/src/whitelist/repository/persisted.rs
@@ -2,7 +2,7 @@ use std::sync::Arc;
use bittorrent_primitives::info_hash::InfoHash;
-use crate::core::databases::{self, Database};
+use crate::databases::{self, Database};
/// The persisted list of allowed torrents.
pub struct DatabaseWhitelist {
diff --git a/src/core/whitelist/setup.rs b/packages/tracker-core/src/whitelist/setup.rs
similarity index 92%
rename from src/core/whitelist/setup.rs
rename to packages/tracker-core/src/whitelist/setup.rs
index bdd35737c..5b2a5de40 100644
--- a/src/core/whitelist/setup.rs
+++ b/packages/tracker-core/src/whitelist/setup.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
use super::manager::WhitelistManager;
use super::repository::in_memory::InMemoryWhitelist;
use super::repository::persisted::DatabaseWhitelist;
-use crate::core::databases::Database;
+use crate::databases::Database;
#[must_use]
pub fn initialize_whitelist_manager(
diff --git a/src/core/whitelist/whitelist_tests.rs b/packages/tracker-core/src/whitelist/whitelist_tests.rs
similarity index 89%
rename from src/core/whitelist/whitelist_tests.rs
rename to packages/tracker-core/src/whitelist/whitelist_tests.rs
index 38c2bbde3..33f5a97f7 100644
--- a/src/core/whitelist/whitelist_tests.rs
+++ b/packages/tracker-core/src/whitelist/whitelist_tests.rs
@@ -5,8 +5,8 @@ use torrust_tracker_configuration::Configuration;
use super::authorization::WhitelistAuthorization;
use super::manager::WhitelistManager;
use super::repository::in_memory::InMemoryWhitelist;
-use crate::core::databases::setup::initialize_database;
-use crate::core::whitelist::setup::initialize_whitelist_manager;
+use crate::databases::setup::initialize_database;
+use crate::whitelist::setup::initialize_whitelist_manager;
#[must_use]
pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) {
diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs
index 8a084dc7f..f7506800e 100644
--- a/src/bootstrap/app.rs
+++ b/src/bootstrap/app.rs
@@ -13,6 +13,20 @@
//! 4. Initialize the domain tracker.
use std::sync::Arc;
+use bittorrent_tracker_core::announce_handler::AnnounceHandler;
+use bittorrent_tracker_core::authentication::handler::KeysHandler;
+use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository;
+use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository;
+use bittorrent_tracker_core::authentication::service;
+use bittorrent_tracker_core::databases::setup::initialize_database;
+use bittorrent_tracker_core::scrape_handler::ScrapeHandler;
+use bittorrent_tracker_core::statistics;
+use bittorrent_tracker_core::torrent::manager::TorrentsManager;
+use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
+use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository;
+use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization;
+use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist;
+use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager;
use tokio::sync::RwLock;
use torrust_tracker_clock::static_time;
use torrust_tracker_configuration::validator::Validator;
@@ -22,20 +36,6 @@ use tracing::instrument;
use super::config::initialize_configuration;
use crate::bootstrap;
use crate::container::AppContainer;
-use crate::core::announce_handler::AnnounceHandler;
-use crate::core::authentication::handler::KeysHandler;
-use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository;
-use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository;
-use crate::core::authentication::service;
-use crate::core::databases::setup::initialize_database;
-use crate::core::scrape_handler::ScrapeHandler;
-use crate::core::statistics;
-use crate::core::torrent::manager::TorrentsManager;
-use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
-use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository;
-use crate::core::whitelist::authorization::WhitelistAuthorization;
-use crate::core::whitelist::repository::in_memory::InMemoryWhitelist;
-use crate::core::whitelist::setup::initialize_whitelist_manager;
use crate::servers::udp::server::banning::BanService;
use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP;
use crate::shared::crypto::ephemeral_instance_keys;
diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs
index 45e6e9e68..7085aa7e2 100644
--- a/src/bootstrap/jobs/torrent_cleanup.rs
+++ b/src/bootstrap/jobs/torrent_cleanup.rs
@@ -12,13 +12,12 @@
use std::sync::Arc;
+use bittorrent_tracker_core::torrent::manager::TorrentsManager;
use chrono::Utc;
use tokio::task::JoinHandle;
use torrust_tracker_configuration::Core;
use tracing::instrument;
-use crate::core::torrent::manager::TorrentsManager;
-
/// It starts a jobs for cleaning up the torrent data in the tracker.
///
/// The cleaning task is executed on an `inactive_peer_cleanup_interval`.
diff --git a/src/container.rs b/src/container.rs
index 1a2a029ee..cae2d07ce 100644
--- a/src/container.rs
+++ b/src/container.rs
@@ -1,20 +1,20 @@
use std::sync::Arc;
+use bittorrent_tracker_core::announce_handler::AnnounceHandler;
+use bittorrent_tracker_core::authentication::handler::KeysHandler;
+use bittorrent_tracker_core::authentication::service::AuthenticationService;
+use bittorrent_tracker_core::databases::Database;
+use bittorrent_tracker_core::scrape_handler::ScrapeHandler;
+use bittorrent_tracker_core::statistics::event::sender::Sender;
+use bittorrent_tracker_core::statistics::repository::Repository;
+use bittorrent_tracker_core::torrent::manager::TorrentsManager;
+use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
+use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository;
+use bittorrent_tracker_core::whitelist;
+use bittorrent_tracker_core::whitelist::manager::WhitelistManager;
use tokio::sync::RwLock;
use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker};
-use crate::core::announce_handler::AnnounceHandler;
-use crate::core::authentication::handler::KeysHandler;
-use crate::core::authentication::service::AuthenticationService;
-use crate::core::databases::Database;
-use crate::core::scrape_handler::ScrapeHandler;
-use crate::core::statistics::event::sender::Sender;
-use crate::core::statistics::repository::Repository;
-use crate::core::torrent::manager::TorrentsManager;
-use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
-use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository;
-use crate::core::whitelist;
-use crate::core::whitelist::manager::WhitelistManager;
use crate::servers::udp::server::banning::BanService;
pub struct AppContainer {
diff --git a/src/core/mod.rs b/src/core/mod.rs
index 125a67b5a..3449ec7b4 100644
--- a/src/core/mod.rs
+++ b/src/core/mod.rs
@@ -1,573 +1 @@
-//! The core `tracker` module contains the generic `BitTorrent` tracker logic which is independent of the delivery layer.
-//!
-//! It contains the tracker services and their dependencies. It's a domain layer which does not
-//! specify how the end user should connect to the `Tracker`.
-//!
-//! Typically this module is intended to be used by higher modules like:
-//!
-//! - A UDP tracker
-//! - A HTTP tracker
-//! - A tracker REST API
-//!
-//! ```text
-//! Delivery layer Domain layer
-//!
-//! HTTP tracker |
-//! UDP tracker |> Core tracker
-//! Tracker REST API |
-//! ```
-//!
-//! # Table of contents
-//!
-//! - [Tracker](#tracker)
-//! - [Announce request](#announce-request)
-//! - [Scrape request](#scrape-request)
-//! - [Torrents](#torrents)
-//! - [Peers](#peers)
-//! - [Configuration](#configuration)
-//! - [Services](#services)
-//! - [Authentication](#authentication)
-//! - [Statistics](#statistics)
-//! - [Persistence](#persistence)
-//!
-//! # Tracker
-//!
-//! The `Tracker` is the main struct in this module. `The` tracker has some groups of responsibilities:
-//!
-//! - **Core tracker**: it handles the information about torrents and peers.
-//! - **Authentication**: it handles authentication keys which are used by HTTP trackers.
-//! - **Authorization**: it handles the permission to perform requests.
-//! - **Whitelist**: when the tracker runs in `listed` or `private_listed` mode all operations are restricted to whitelisted torrents.
-//! - **Statistics**: it keeps and serves the tracker statistics.
-//!
-//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) crate docs to get more information about the tracker settings.
-//!
-//! ## Announce request
-//!
-//! Handling `announce` requests is the most important task for a `BitTorrent` tracker.
-//!
-//! A `BitTorrent` swarm is a network of peers that are all trying to download the same torrent.
-//! When a peer wants to find other peers it announces itself to the swarm via the tracker.
-//! The peer sends its data to the tracker so that the tracker can add it to the swarm.
-//! The tracker responds to the peer with the list of other peers in the swarm so that
-//! the peer can contact them to start downloading pieces of the file from them.
-//!
-//! Once you have instantiated the `AnnounceHandler` you can `announce` a new [`peer::Peer`](torrust_tracker_primitives::peer::Peer) with:
-//!
-//! ```rust,no_run
-//! use std::net::SocketAddr;
-//! use std::net::IpAddr;
-//! use std::net::Ipv4Addr;
-//! use std::str::FromStr;
-//!
-//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId};
-//! use torrust_tracker_primitives::DurationSinceUnixEpoch;
-//! use torrust_tracker_primitives::peer;
-//! use bittorrent_primitives::info_hash::InfoHash;
-//!
-//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap();
-//!
-//! let peer = peer::Peer {
-//! peer_id: PeerId(*b"-qB00000000000000001"),
-//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081),
-//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0),
-//! uploaded: NumberOfBytes::new(0),
-//! downloaded: NumberOfBytes::new(0),
-//! left: NumberOfBytes::new(0),
-//! event: AnnounceEvent::Completed,
-//! };
-//!
-//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap());
-//! ```
-//!
-//! ```text
-//! let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip).await;
-//! ```
-//!
-//! The `Tracker` returns the list of peers for the torrent with the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`,
-//! filtering out the peer that is making the `announce` request.
-//!
-//! > **NOTICE**: that the peer argument is mutable because the `Tracker` can change the peer IP if the peer is using a loopback IP.
-//!
-//! The `peer_ip` argument is the resolved peer ip. It's a common practice that trackers ignore the peer ip in the `announce` request params,
-//! and resolve the peer ip using the IP of the client making the request. As the tracker is a domain service, the peer IP must be provided
-//! for the `Tracker` user, which is usually a higher component with access the the request metadata, for example, connection data, proxy headers,
-//! etcetera.
-//!
-//! The returned struct is:
-//!
-//! ```rust,no_run
-//! use torrust_tracker_primitives::peer;
-//! use torrust_tracker_configuration::AnnouncePolicy;
-//!
-//! pub struct AnnounceData {
-//! pub peers: Vec,
-//! pub swarm_stats: SwarmMetadata,
-//! pub policy: AnnouncePolicy, // the tracker announce policy.
-//! }
-//!
-//! pub struct SwarmMetadata {
-//! pub completed: u32, // The number of peers that have ever completed downloading
-//! pub seeders: u32, // The number of active peers that have completed downloading (seeders)
-//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers)
-//! }
-//!
-//! // Core tracker configuration
-//! pub struct AnnounceInterval {
-//! // ...
-//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker
-//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this
-//! // ...
-//! }
-//! ```
-//!
-//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request:
-//!
-//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html)
-//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html)
-//! - [Vuze docs](https://wiki.vuze.com/w/Announce)
-//!
-//! ## Scrape request
-//!
-//! The `scrape` request allows clients to query metadata about the swarm in bulk.
-//!
-//! An `scrape` request includes a list of infohashes whose swarm metadata you want to collect.
-//!
-//! The returned struct is:
-//!
-//! ```rust,no_run
-//! use bittorrent_primitives::info_hash::InfoHash;
-//! use std::collections::HashMap;
-//!
-//! pub struct ScrapeData {
-//! pub files: HashMap,
-//! }
-//!
-//! pub struct SwarmMetadata {
-//! pub complete: u32, // The number of active peers that have completed downloading (seeders)
-//! pub downloaded: u32, // The number of peers that have ever completed downloading
-//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers)
-//! }
-//! ```
-//!
-//! The JSON representation of a sample `scrape` response would be like the following:
-//!
-//! ```json
-//! {
-//! 'files': {
-//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19},
-//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20}
-//! }
-//! }
-//! ```
-//!
-//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays.
-//! There are two data structures for infohashes: byte arrays and hex strings:
-//!
-//! ```rust,no_run
-//! use bittorrent_primitives::info_hash::InfoHash;
-//! use std::str::FromStr;
-//!
-//! let info_hash: InfoHash = [255u8; 20].into();
-//!
-//! assert_eq!(
-//! info_hash,
-//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap()
-//! );
-//! ```
-//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request:
-//!
-//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html)
-//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html)
-//! - [Vuze docs](https://wiki.vuze.com/w/Scrape)
-//!
-//! ## Torrents
-//!
-//! The [`torrent`] module contains all the data structures stored by the `Tracker` except for peers.
-//!
-//! We can represent the data stored in memory internally by the `Tracker` with this JSON object:
-//!
-//! ```json
-//! {
-//! "c1277613db1d28709b034a017ab2cae4be07ae10": {
-//! "completed": 0,
-//! "peers": {
-//! "-qB00000000000000001": {
-//! "peer_id": "-qB00000000000000001",
-//! "peer_addr": "2.137.87.41:1754",
-//! "updated": 1672419840,
-//! "uploaded": 120,
-//! "downloaded": 60,
-//! "left": 60,
-//! "event": "started"
-//! },
-//! "-qB00000000000000002": {
-//! "peer_id": "-qB00000000000000002",
-//! "peer_addr": "23.17.287.141:2345",
-//! "updated": 1679415984,
-//! "uploaded": 80,
-//! "downloaded": 20,
-//! "left": 40,
-//! "event": "started"
-//! }
-//! }
-//! }
-//! }
-//! ```
-//!
-//! The `Tracker` maintains an indexed-by-info-hash list of torrents. For each torrent, it stores a torrent `Entry`.
-//! The torrent entry has two attributes:
-//!
-//! - `completed`: which is hte number of peers that have completed downloading the torrent file/s. As they have completed downloading,
-//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders".
-//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request.
-//!
-//! The [`torrent`] module not only contains the original data obtained from peer via `announce` requests, it also contains
-//! aggregate data that can be derived from the original data. For example:
-//!
-//! ```rust,no_run
-//! pub struct SwarmMetadata {
-//! pub complete: u32, // The number of active peers that have completed downloading (seeders)
-//! pub downloaded: u32, // The number of peers that have ever completed downloading
-//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers)
-//! }
-//!
-//! ```
-//!
-//! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders".
-//!
-//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata`
-//! is used for the rest of cases.
-//!
-//! Refer to [`torrent`] module for more details about these data structures.
-//!
-//! ## Peers
-//!
-//! A `Peer` is the struct used by the `Tracker` to keep peers data:
-//!
-//! ```rust,no_run
-//! use std::net::SocketAddr;
-
-//! use aquatic_udp_protocol::PeerId;
-//! use torrust_tracker_primitives::DurationSinceUnixEpoch;
-//! use aquatic_udp_protocol::NumberOfBytes;
-//! use aquatic_udp_protocol::AnnounceEvent;
-//!
-//! pub struct Peer {
-//! pub peer_id: PeerId, // The peer ID
-//! pub peer_addr: SocketAddr, // Peer socket address
-//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated
-//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far
-//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far
-//! pub left: NumberOfBytes, // The number of bytes this peer still has to download
-//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped`
-//! }
-//! ```
-//!
-//! Notice that most of the attributes are obtained from the `announce` request.
-//! For example, an HTTP announce request would contain the following `GET` parameters:
-//!
-//!
-//!
-//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics.
-//!
-//! We can represent the data stored in memory with this JSON object:
-//!
-//! ```json
-//! {
-//! "c1277613db1d28709b034a017ab2cae4be07ae10": {
-//! "completed": 0,
-//! "peers": {
-//! "-qB00000000000000001": {
-//! "peer_id": "-qB00000000000000001",
-//! "peer_addr": "2.137.87.41:1754",
-//! "updated": 1672419840,
-//! "uploaded": 120,
-//! "downloaded": 60,
-//! "left": 60,
-//! "event": "started"
-//! },
-//! "-qB00000000000000002": {
-//! "peer_id": "-qB00000000000000002",
-//! "peer_addr": "23.17.287.141:2345",
-//! "updated": 1679415984,
-//! "uploaded": 80,
-//! "downloaded": 20,
-//! "left": 40,
-//! "event": "started"
-//! }
-//! }
-//! }
-//! }
-//! ```
-//!
-//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data.
-//!
-//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers
-//! that have a full version of the torrent data, also known as seeders.
-//!
-//! Refer to [`peer`](torrust_tracker_primitives::peer) for more information about peers.
-//!
-//! # Configuration
-//!
-//! You can control the behavior of this module with the module settings:
-//!
-//! ```toml
-//! [logging]
-//! threshold = "debug"
-//!
-//! [core]
-//! inactive_peer_cleanup_interval = 600
-//! listed = false
-//! private = false
-//! tracker_usage_statistics = true
-//!
-//! [core.announce_policy]
-//! interval = 120
-//! interval_min = 120
-//!
-//! [core.database]
-//! driver = "sqlite3"
-//! path = "./storage/tracker/lib/database/sqlite3.db"
-//!
-//! [core.net]
-//! on_reverse_proxy = false
-//! external_ip = "2.137.87.41"
-//!
-//! [core.tracker_policy]
-//! max_peer_timeout = 900
-//! persistent_torrent_completed_stat = false
-//! remove_peerless_torrents = true
-//! ```
-//!
-//! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options.
-//!
-//! # Services
-//!
-//! Services are domain services on top of the core tracker domain. Right now there are two types of service:
-//!
-//! - For statistics: [`crate::core::statistics::services`]
-//! - For torrents: [`crate::core::torrent::services`]
-//!
-//! Services usually format the data inside the tracker to make it easier to consume by other parts.
-//! They also decouple the internal data structure, used by the tracker, from the way we deliver that data to the consumers.
-//! The internal data structure is designed for performance or low memory consumption. And it should be changed
-//! without affecting the external consumers.
-//!
-//! Services can include extra features like pagination, for example.
-//!
-//! # Authentication
-//!
-//! One of the core `Tracker` responsibilities is to create and keep authentication keys. Auth keys are used by HTTP trackers
-//! when the tracker is running in `private` or `private_listed` mode.
-//!
-//! HTTP tracker's clients need to obtain an auth key before starting requesting the tracker. Once the get one they have to include
-//! a `PATH` param with the key in all the HTTP requests. For example, when a peer wants to `announce` itself it has to use the
-//! HTTP tracker endpoint `GET /announce/:key`.
-//!
-//! The common way to obtain the keys is by using the tracker API directly or via other applications like the [Torrust Index](https://github.com/torrust/torrust-index).
-//!
-//! To learn more about tracker authentication, refer to the following modules :
-//!
-//! - [`authentication`] module.
-//! - [`core`](crate::core) module.
-//! - [`http`](crate::servers::http) module.
-//!
-//! # Statistics
-//!
-//! The `Tracker` keeps metrics for some events:
-//!
-//! ```rust,no_run
-//! pub struct Metrics {
-//! // IP version 4
-//!
-//! // HTTP tracker
-//! pub tcp4_connections_handled: u64,
-//! pub tcp4_announces_handled: u64,
-//! pub tcp4_scrapes_handled: u64,
-//!
-//! // UDP tracker
-//! pub udp4_connections_handled: u64,
-//! pub udp4_announces_handled: u64,
-//! pub udp4_scrapes_handled: u64,
-//!
-//! // IP version 6
-//!
-//! // HTTP tracker
-//! pub tcp6_connections_handled: u64,
-//! pub tcp6_announces_handled: u64,
-//! pub tcp6_scrapes_handled: u64,
-//!
-//! // UDP tracker
-//! pub udp6_connections_handled: u64,
-//! pub udp6_announces_handled: u64,
-//! pub udp6_scrapes_handled: u64,
-//! }
-//! ```
-//!
-//! The metrics maintained by the `Tracker` are:
-//!
-//! - `connections_handled`: number of connections handled by the tracker
-//! - `announces_handled`: number of `announce` requests handled by the tracker
-//! - `scrapes_handled`: number of `scrape` handled requests by the tracker
-//!
-//! > **NOTICE**: as the HTTP tracker does not have an specific `connection` request like the UDP tracker, `connections_handled` are
-//! > increased on every `announce` and `scrape` requests.
-//!
-//! The tracker exposes an event sender API that allows the tracker users to send events. When a higher application service handles a
-//! `connection` , `announce` or `scrape` requests, it notifies the `Tracker` by sending statistics events.
-//!
-//! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4.
-//!
-//! ```text
-//! stats_event_sender.send_stats_event(statistics::event::Event::Tcp4Announce).await
-//! ```
-//!
-//! Refer to [`statistics`] module for more information about statistics.
-//!
-//! # Persistence
-//!
-//! Right now the `Tracker` is responsible for storing and load data into and
-//! from the database, when persistence is enabled.
-//!
-//! There are three types of persistent object:
-//!
-//! - Authentication keys (only expiring keys)
-//! - Torrent whitelist
-//! - Torrent metrics
-//!
-//! Refer to [`databases`] module for more information about persistence.
-pub mod announce_handler;
-pub mod authentication;
-pub mod databases;
-pub mod error;
-pub mod scrape_handler;
pub mod statistics;
-pub mod torrent;
-pub mod whitelist;
-
-pub mod core_tests;
-pub mod peer_tests;
-
-#[cfg(test)]
-mod tests {
- mod the_tracker {
- use std::net::{IpAddr, Ipv4Addr};
- use std::str::FromStr;
- use std::sync::Arc;
-
- use torrust_tracker_test_helpers::configuration;
-
- use crate::core::announce_handler::AnnounceHandler;
- use crate::core::core_tests::initialize_handlers;
- use crate::core::scrape_handler::ScrapeHandler;
-
- fn initialize_handlers_for_public_tracker() -> (Arc, Arc) {
- let config = configuration::ephemeral_public();
- initialize_handlers(&config)
- }
-
- fn initialize_handlers_for_listed_tracker() -> (Arc, Arc) {
- let config = configuration::ephemeral_listed();
- initialize_handlers(&config)
- }
-
- // The client peer IP
- fn peer_ip() -> IpAddr {
- IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap())
- }
-
- mod for_all_config_modes {
-
- mod handling_a_scrape_request {
-
- use std::net::{IpAddr, Ipv4Addr};
-
- use bittorrent_primitives::info_hash::InfoHash;
- use torrust_tracker_primitives::core::ScrapeData;
- use torrust_tracker_primitives::swarm_metadata::SwarmMetadata;
-
- use crate::core::announce_handler::PeersWanted;
- use crate::core::core_tests::{complete_peer, incomplete_peer};
- use crate::core::tests::the_tracker::initialize_handlers_for_public_tracker;
-
- #[tokio::test]
- async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() {
- let (announce_handler, scrape_handler) = initialize_handlers_for_public_tracker();
-
- let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237
-
- // Announce a "complete" peer for the torrent
- let mut complete_peer = complete_peer();
- announce_handler.announce(
- &info_hash,
- &mut complete_peer,
- &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)),
- &PeersWanted::All,
- );
-
- // Announce an "incomplete" peer for the torrent
- let mut incomplete_peer = incomplete_peer();
- announce_handler.announce(
- &info_hash,
- &mut incomplete_peer,
- &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)),
- &PeersWanted::All,
- );
-
- // Scrape
- let scrape_data = scrape_handler.scrape(&vec![info_hash]).await;
-
- // The expected swarm metadata for the file
- let mut expected_scrape_data = ScrapeData::empty();
- expected_scrape_data.add_file(
- &info_hash,
- SwarmMetadata {
- complete: 0, // the "complete" peer does not count because it was not previously known
- downloaded: 0,
- incomplete: 1, // the "incomplete" peer we have just announced
- },
- );
-
- assert_eq!(scrape_data, expected_scrape_data);
- }
- }
- }
-
- mod configured_as_whitelisted {
-
- mod handling_a_scrape_request {
-
- use bittorrent_primitives::info_hash::InfoHash;
- use torrust_tracker_primitives::core::ScrapeData;
- use torrust_tracker_primitives::swarm_metadata::SwarmMetadata;
-
- use crate::core::announce_handler::PeersWanted;
- use crate::core::core_tests::{complete_peer, incomplete_peer};
- use crate::core::tests::the_tracker::{initialize_handlers_for_listed_tracker, peer_ip};
-
- #[tokio::test]
- async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() {
- let (announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker();
-
- let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237
-
- let mut peer = incomplete_peer();
- announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All);
-
- // Announce twice to force non zeroed swarm metadata
- let mut peer = complete_peer();
- announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All);
-
- let scrape_data = scrape_handler.scrape(&vec![info_hash]).await;
-
- // The expected zeroed swarm metadata for the file
- let mut expected_scrape_data = ScrapeData::empty();
- expected_scrape_data.add_file(&info_hash, SwarmMetadata::zeroed());
-
- assert_eq!(scrape_data, expected_scrape_data);
- }
- }
- }
- }
-}
diff --git a/src/core/statistics/mod.rs b/src/core/statistics/mod.rs
index 2ffbc0c8f..4e379ae78 100644
--- a/src/core/statistics/mod.rs
+++ b/src/core/statistics/mod.rs
@@ -1,32 +1 @@
-//! Structs to collect and keep tracker metrics.
-//!
-//! The tracker collects metrics such as:
-//!
-//! - Number of connections handled
-//! - Number of `announce` requests handled
-//! - Number of `scrape` request handled
-//!
-//! These metrics are collected for each connection type: UDP and HTTP and
-//! also for each IP version used by the peers: IPv4 and IPv6.
-//!
-//! > Notice: that UDP tracker have an specific `connection` request. For the
-//! > `HTTP` metrics the counter counts one connection for each `announce` or
-//! > `scrape` request.
-//!
-//! The data is collected by using an `event-sender -> event listener` model.
-//!
-//! The tracker uses a [`Sender`](crate::core::statistics::event::sender::Sender)
-//! instance to send an event.
-//!
-//! The [`statistics::keeper::Keeper`](crate::core::statistics::keeper::Keeper) listens to new
-//! events and uses the [`statistics::repository::Repository`](crate::core::statistics::repository::Repository) to
-//! upgrade and store metrics.
-//!
-//! See the [`statistics::event::Event`](crate::core::statistics::event::Event) enum to check
-//! which events are available.
-pub mod event;
-pub mod keeper;
-pub mod metrics;
-pub mod repository;
pub mod services;
-pub mod setup;
diff --git a/src/core/statistics/services.rs b/src/core/statistics/services.rs
index 337731aea..a4bcc411e 100644
--- a/src/core/statistics/services.rs
+++ b/src/core/statistics/services.rs
@@ -2,14 +2,14 @@
//!
//! It includes:
//!
-//! - A [`factory`](crate::core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics.
-//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics).
+//! - A [`factory`](bittorrent_tracker_core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics.
+//! - A [`get_metrics`] service to get the tracker [`metrics`](bittorrent_tracker_core::statistics::metrics::Metrics).
//!
//! Tracker metrics are collected using a Publisher-Subscribe pattern.
//!
//! The factory function builds two structs:
//!
-//! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender)
+//! - An statistics event [`Sender`](bittorrent_tracker_core::statistics::event::sender::Sender)
//! - An statistics [`Repository`]
//!
//! ```text
@@ -21,7 +21,7 @@
//! There is an event listener that is receiving all the events and processing them with an event handler.
//! Then, the event handler updates the metrics depending on the received event.
//!
-//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::event::Event::Udp4Connect):
+//! For example, if you send the event [`Event::Udp4Connect`](bittorrent_tracker_core::statistics::event::Event::Udp4Connect):
//!
//! ```text
//! let result = event_sender.send_event(Event::Udp4Connect).await;
@@ -38,28 +38,14 @@
//! ```
use std::sync::Arc;
+use bittorrent_tracker_core::statistics::metrics::Metrics;
+use bittorrent_tracker_core::statistics::repository::Repository;
+use bittorrent_tracker_core::statistics::services::TrackerMetrics;
+use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
use tokio::sync::RwLock;
-use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics;
-use crate::core::statistics::metrics::Metrics;
-use crate::core::statistics::repository::Repository;
-use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
use crate::servers::udp::server::banning::BanService;
-/// All the metrics collected by the tracker.
-#[derive(Debug, PartialEq)]
-pub struct TrackerMetrics {
- /// Domain level metrics.
- ///
- /// General metrics for all torrents (number of seeders, leechers, etcetera)
- pub torrents_metrics: TorrentsMetrics,
-
- /// Application level metrics. Usage statistics/metrics.
- ///
- /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera)
- pub protocol_metrics: Metrics,
-}
-
/// It returns all the [`TrackerMetrics`]
pub async fn get_metrics(
in_memory_torrent_repository: Arc,
@@ -110,14 +96,15 @@ pub async fn get_metrics(
mod tests {
use std::sync::Arc;
+ use bittorrent_tracker_core::statistics::services::TrackerMetrics;
+ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
+ use bittorrent_tracker_core::{self, statistics};
use tokio::sync::RwLock;
use torrust_tracker_configuration::Configuration;
use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics;
use torrust_tracker_test_helpers::configuration;
- use crate::core::statistics::services::{get_metrics, TrackerMetrics};
- use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
- use crate::core::{self, statistics};
+ use crate::core::statistics::services::get_metrics;
use crate::servers::udp::server::banning::BanService;
use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP;
@@ -145,7 +132,7 @@ mod tests {
tracker_metrics,
TrackerMetrics {
torrents_metrics: TorrentsMetrics::default(),
- protocol_metrics: core::statistics::metrics::Metrics::default(),
+ protocol_metrics: statistics::metrics::Metrics::default(),
}
);
}
diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs
index 045a9d211..7024ffeba 100644
--- a/src/servers/apis/v1/context/auth_key/handlers.rs
+++ b/src/servers/apis/v1/context/auth_key/handlers.rs
@@ -5,6 +5,8 @@ use std::time::Duration;
use axum::extract::{self, Path, State};
use axum::response::Response;
+use bittorrent_tracker_core::authentication::handler::{AddKeyRequest, KeysHandler};
+use bittorrent_tracker_core::authentication::Key;
use serde::Deserialize;
use super::forms::AddKeyForm;
@@ -12,8 +14,6 @@ use super::responses::{
auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response,
invalid_auth_key_duration_response, invalid_auth_key_response,
};
-use crate::core::authentication::handler::{AddKeyRequest, KeysHandler};
-use crate::core::authentication::Key;
use crate::servers::apis::v1::context::auth_key::resources::AuthKey;
use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response};
@@ -43,11 +43,11 @@ pub async fn add_auth_key_handler(
{
Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)),
Err(err) => match err {
- crate::core::error::PeerKeyError::DurationOverflow { seconds_valid } => {
+ bittorrent_tracker_core::error::PeerKeyError::DurationOverflow { seconds_valid } => {
invalid_auth_key_duration_response(seconds_valid)
}
- crate::core::error::PeerKeyError::InvalidKey { key, source } => invalid_auth_key_response(&key, source),
- crate::core::error::PeerKeyError::DatabaseError { source } => failed_to_generate_key_response(source),
+ bittorrent_tracker_core::error::PeerKeyError::InvalidKey { key, source } => invalid_auth_key_response(&key, source),
+ bittorrent_tracker_core::error::PeerKeyError::DatabaseError { source } => failed_to_generate_key_response(source),
},
}
}
diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs
index a65eb2ab2..8f5b4d309 100644
--- a/src/servers/apis/v1/context/auth_key/resources.rs
+++ b/src/servers/apis/v1/context/auth_key/resources.rs
@@ -1,10 +1,9 @@
//! API resources for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context.
+use bittorrent_tracker_core::authentication::{self, Key};
use serde::{Deserialize, Serialize};
use torrust_tracker_clock::conv::convert_from_iso_8601_to_timestamp;
-use crate::core::authentication::{self, Key};
-
/// A resource that represents an authentication key.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct AuthKey {
@@ -50,11 +49,11 @@ impl From for AuthKey {
mod tests {
use std::time::Duration;
+ use bittorrent_tracker_core::authentication::{self, Key};
use torrust_tracker_clock::clock::stopped::Stopped as _;
use torrust_tracker_clock::clock::{self, Time};
use super::AuthKey;
- use crate::core::authentication::{self, Key};
use crate::CurrentClock;
struct TestTime {
diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs
index ee9f3252c..623fb3459 100644
--- a/src/servers/apis/v1/context/auth_key/routes.rs
+++ b/src/servers/apis/v1/context/auth_key/routes.rs
@@ -10,9 +10,9 @@ use std::sync::Arc;
use axum::routing::{get, post};
use axum::Router;
+use bittorrent_tracker_core::authentication::handler::KeysHandler;
use super::handlers::{add_auth_key_handler, delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler};
-use crate::core::authentication::handler::KeysHandler;
/// It adds the routes to the router for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context.
pub fn add(prefix: &str, router: Router, keys_handler: &Arc) -> Router {
diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs
index b8e7abd87..b4ead78ea 100644
--- a/src/servers/apis/v1/context/stats/handlers.rs
+++ b/src/servers/apis/v1/context/stats/handlers.rs
@@ -5,13 +5,13 @@ use std::sync::Arc;
use axum::extract::State;
use axum::response::Response;
use axum_extra::extract::Query;
+use bittorrent_tracker_core::statistics::repository::Repository;
+use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
use serde::Deserialize;
use tokio::sync::RwLock;
use super::responses::{metrics_response, stats_response};
-use crate::core::statistics::repository::Repository;
use crate::core::statistics::services::get_metrics;
-use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
use crate::servers::udp::server::banning::BanService;
#[derive(Deserialize, Debug, Default)]
diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs
index 97ece22fc..d4a0ec7ec 100644
--- a/src/servers/apis/v1/context/stats/resources.rs
+++ b/src/servers/apis/v1/context/stats/resources.rs
@@ -1,9 +1,8 @@
//! API resources for the [`stats`](crate::servers::apis::v1::context::stats)
//! API context.
+use bittorrent_tracker_core::statistics::services::TrackerMetrics;
use serde::{Deserialize, Serialize};
-use crate::core::statistics::services::TrackerMetrics;
-
/// It contains all the statistics generated by the tracker.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct Stats {
@@ -118,11 +117,11 @@ impl From for Stats {
#[cfg(test)]
mod tests {
+ use bittorrent_tracker_core::statistics::metrics::Metrics;
+ use bittorrent_tracker_core::statistics::services::TrackerMetrics;
use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics;
use super::Stats;
- use crate::core::statistics::metrics::Metrics;
- use crate::core::statistics::services::TrackerMetrics;
#[test]
fn stats_resource_should_be_converted_from_tracker_metrics() {
diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs
index 6fda43f8c..fc74b5f8d 100644
--- a/src/servers/apis/v1/context/stats/responses.rs
+++ b/src/servers/apis/v1/context/stats/responses.rs
@@ -1,9 +1,9 @@
//! API responses for the [`stats`](crate::servers::apis::v1::context::stats)
//! API context.
use axum::response::{IntoResponse, Json, Response};
+use bittorrent_tracker_core::statistics::services::TrackerMetrics;
use super::resources::Stats;
-use crate::core::statistics::services::TrackerMetrics;
/// `200` response that contains the [`Stats`] resource as json.
#[must_use]
diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs
index 0ec90441d..ce80d8fee 100644
--- a/src/servers/apis/v1/context/torrent/handlers.rs
+++ b/src/servers/apis/v1/context/torrent/handlers.rs
@@ -8,13 +8,13 @@ use axum::extract::{Path, State};
use axum::response::{IntoResponse, Response};
use axum_extra::extract::Query;
use bittorrent_primitives::info_hash::InfoHash;
+use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
+use bittorrent_tracker_core::torrent::services::{get_torrent_info, get_torrents, get_torrents_page};
use serde::{de, Deserialize, Deserializer};
use thiserror::Error;
use torrust_tracker_primitives::pagination::Pagination;
use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response};
-use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
-use crate::core::torrent::services::{get_torrent_info, get_torrents, get_torrents_page};
use crate::servers::apis::v1::responses::invalid_info_hash_param_response;
use crate::servers::apis::InfoHashParam;
@@ -33,7 +33,7 @@ pub async fn get_torrent_handler(
) -> Response {
match InfoHash::from_str(&info_hash.0) {
Err(_) => invalid_info_hash_param_response(&info_hash.0),
- Ok(info_hash) => match get_torrent_info(in_memory_torrent_repository.clone(), &info_hash).await {
+ Ok(info_hash) => match get_torrent_info(&in_memory_torrent_repository, &info_hash) {
Some(info) => torrent_info_response(info).into_response(),
None => torrent_not_known_response(),
},
@@ -85,19 +85,14 @@ pub async fn get_torrents_handler(
tracing::debug!("pagination: {:?}", pagination);
if pagination.0.info_hashes.is_empty() {
- torrent_list_response(
- &get_torrents_page(
- in_memory_torrent_repository.clone(),
- Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)),
- )
- .await,
- )
+ torrent_list_response(&get_torrents_page(
+ &in_memory_torrent_repository,
+ Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)),
+ ))
.into_response()
} else {
match parse_info_hashes(pagination.0.info_hashes) {
- Ok(info_hashes) => {
- torrent_list_response(&get_torrents(in_memory_torrent_repository.clone(), &info_hashes).await).into_response()
- }
+ Ok(info_hashes) => torrent_list_response(&get_torrents(&in_memory_torrent_repository, &info_hashes)).into_response(),
Err(err) => match err {
QueryParamError::InvalidInfoHash { info_hash } => invalid_info_hash_param_response(&info_hash),
},
diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs
index c90a2a05f..5e4da5c16 100644
--- a/src/servers/apis/v1/context/torrent/resources/torrent.rs
+++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs
@@ -4,10 +4,9 @@
//! - `ListItem` is a list item resource on a torrent list. `ListItem` does
//! include a `peers` field but it is always `None` in the struct and `null` in
//! the JSON response.
+use bittorrent_tracker_core::torrent::services::{BasicInfo, Info};
use serde::{Deserialize, Serialize};
-use crate::core::torrent::services::{BasicInfo, Info};
-
/// `Torrent` API resource.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct Torrent {
@@ -99,10 +98,10 @@ mod tests {
use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId};
use bittorrent_primitives::info_hash::InfoHash;
+ use bittorrent_tracker_core::torrent::services::{BasicInfo, Info};
use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch};
use super::Torrent;
- use crate::core::torrent::services::{BasicInfo, Info};
use crate::servers::apis::v1::context::torrent::resources::peer::Peer;
use crate::servers::apis::v1::context::torrent::resources::torrent::ListItem;
diff --git a/src/servers/apis/v1/context/torrent/responses.rs b/src/servers/apis/v1/context/torrent/responses.rs
index 5174c9abe..cd359247b 100644
--- a/src/servers/apis/v1/context/torrent/responses.rs
+++ b/src/servers/apis/v1/context/torrent/responses.rs
@@ -1,10 +1,10 @@
//! API responses for the [`torrent`](crate::servers::apis::v1::context::torrent)
//! API context.
use axum::response::{IntoResponse, Json, Response};
+use bittorrent_tracker_core::torrent::services::{BasicInfo, Info};
use serde_json::json;
use super::resources::torrent::{ListItem, Torrent};
-use crate::core::torrent::services::{BasicInfo, Info};
/// `200` response that contains an array of
/// [`ListItem`]
diff --git a/src/servers/apis/v1/context/torrent/routes.rs b/src/servers/apis/v1/context/torrent/routes.rs
index 3ea8c639c..615bd8d51 100644
--- a/src/servers/apis/v1/context/torrent/routes.rs
+++ b/src/servers/apis/v1/context/torrent/routes.rs
@@ -8,9 +8,9 @@ use std::sync::Arc;
use axum::routing::get;
use axum::Router;
+use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
use super::handlers::{get_torrent_handler, get_torrents_handler};
-use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
/// It adds the routes to the router for the [`torrent`](crate::servers::apis::v1::context::torrent) API context.
pub fn add(prefix: &str, router: Router, in_memory_torrent_repository: &Arc) -> Router {
diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs
index ebe0bb15c..e33a215f2 100644
--- a/src/servers/apis/v1/context/whitelist/handlers.rs
+++ b/src/servers/apis/v1/context/whitelist/handlers.rs
@@ -6,11 +6,11 @@ use std::sync::Arc;
use axum::extract::{Path, State};
use axum::response::Response;
use bittorrent_primitives::info_hash::InfoHash;
+use bittorrent_tracker_core::whitelist::manager::WhitelistManager;
use super::responses::{
failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response,
};
-use crate::core::whitelist::manager::WhitelistManager;
use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response};
use crate::servers::apis::InfoHashParam;
diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/src/servers/apis/v1/context/whitelist/routes.rs
index 5069332af..316193cd6 100644
--- a/src/servers/apis/v1/context/whitelist/routes.rs
+++ b/src/servers/apis/v1/context/whitelist/routes.rs
@@ -9,9 +9,9 @@ use std::sync::Arc;
use axum::routing::{delete, get, post};
use axum::Router;
+use bittorrent_tracker_core::whitelist::manager::WhitelistManager;
use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler};
-use crate::core::whitelist::manager::WhitelistManager;
/// It adds the routes to the router for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context.
pub fn add(prefix: &str, router: Router, whitelist_manager: &Arc) -> Router {
diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs
index d3b77c31a..0e46b75dd 100644
--- a/src/servers/http/v1/extractors/authentication_key.rs
+++ b/src/servers/http/v1/extractors/authentication_key.rs
@@ -50,10 +50,10 @@ use axum::extract::{FromRequestParts, Path};
use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};
use bittorrent_http_protocol::v1::responses;
+use bittorrent_tracker_core::authentication::Key;
use hyper::StatusCode;
use serde::Deserialize;
-use crate::core::authentication::Key;
use crate::servers::http::v1::handlers::common::auth;
/// Extractor for the [`Key`] struct.
diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs
index 544d706fa..40462c31d 100644
--- a/src/servers/http/v1/handlers/announce.rs
+++ b/src/servers/http/v1/handlers/announce.rs
@@ -16,17 +16,18 @@ use bittorrent_http_protocol::v1::requests::announce::{Announce, Compact, Event}
use bittorrent_http_protocol::v1::responses::{self};
use bittorrent_http_protocol::v1::services::peer_ip_resolver;
use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources;
+use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted};
+use bittorrent_tracker_core::authentication::service::AuthenticationService;
+use bittorrent_tracker_core::authentication::Key;
+use bittorrent_tracker_core::statistics::event::sender::Sender;
+use bittorrent_tracker_core::whitelist;
use hyper::StatusCode;
use torrust_tracker_clock::clock::Time;
use torrust_tracker_configuration::Core;
use torrust_tracker_primitives::core::AnnounceData;
use torrust_tracker_primitives::peer;
-use crate::core::announce_handler::{AnnounceHandler, PeersWanted};
-use crate::core::authentication::service::AuthenticationService;
-use crate::core::authentication::Key;
-use crate::core::statistics::event::sender::Sender;
-use crate::core::whitelist;
+use super::common::auth::map_auth_error_to_error_response;
use crate::servers::http::v1::extractors::announce_request::ExtractRequest;
use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey;
use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources;
@@ -150,7 +151,7 @@ async fn handle_announce(
match maybe_key {
Some(key) => match authentication_service.authenticate(&key).await {
Ok(()) => (),
- Err(error) => return Err(responses::error::Error::from(error)),
+ Err(error) => return Err(map_auth_error_to_error_response(&error)),
},
None => {
return Err(responses::error::Error::from(auth::Error::MissingAuthKey {
@@ -250,21 +251,20 @@ mod tests {
use bittorrent_http_protocol::v1::requests::announce::Announce;
use bittorrent_http_protocol::v1::responses;
use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources;
+ use bittorrent_tracker_core::announce_handler::AnnounceHandler;
+ use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository;
+ use bittorrent_tracker_core::authentication::service::AuthenticationService;
+ use bittorrent_tracker_core::core_tests::sample_info_hash;
+ use bittorrent_tracker_core::databases::setup::initialize_database;
+ use bittorrent_tracker_core::statistics;
+ use bittorrent_tracker_core::statistics::event::sender::Sender;
+ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
+ use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository;
+ use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization;
+ use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist;
use torrust_tracker_configuration::{Configuration, Core};
use torrust_tracker_test_helpers::configuration;
- use crate::core::announce_handler::AnnounceHandler;
- use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository;
- use crate::core::authentication::service::AuthenticationService;
- use crate::core::core_tests::sample_info_hash;
- use crate::core::databases::setup::initialize_database;
- use crate::core::statistics;
- use crate::core::statistics::event::sender::Sender;
- use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
- use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository;
- use crate::core::whitelist::authorization::WhitelistAuthorization;
- use crate::core::whitelist::repository::in_memory::InMemoryWhitelist;
-
struct CoreTrackerServices {
pub core_config: Arc,
pub announce_handler: Arc,
@@ -347,8 +347,9 @@ mod tests {
use std::str::FromStr;
+ use bittorrent_tracker_core::authentication;
+
use super::{initialize_private_tracker, sample_announce_request, sample_client_ip_sources};
- use crate::core::authentication;
use crate::servers::http::v1::handlers::announce::handle_announce;
use crate::servers::http::v1::handlers::announce::tests::assert_error_response;
diff --git a/src/servers/http/v1/handlers/common/auth.rs b/src/servers/http/v1/handlers/common/auth.rs
index 5497427d8..c8625d03a 100644
--- a/src/servers/http/v1/handlers/common/auth.rs
+++ b/src/servers/http/v1/handlers/common/auth.rs
@@ -4,10 +4,9 @@
use std::panic::Location;
use bittorrent_http_protocol::v1::responses;
+use bittorrent_tracker_core::authentication;
use thiserror::Error;
-use crate::core::authentication;
-
/// Authentication error.
///
/// When the tracker is private, the authentication key is required in the URL
@@ -31,10 +30,12 @@ impl From for responses::error::Error {
}
}
-impl From for responses::error::Error {
- fn from(err: authentication::Error) -> Self {
- responses::error::Error {
- failure_reason: format!("Authentication error: {err}"),
- }
+#[must_use]
+pub fn map_auth_error_to_error_response(err: &authentication::Error) -> responses::error::Error {
+ // code_review: this could not been implemented with the trait:
+ // impl From for responses::error::Error
+ // Consider moving the trait implementation to the http-protocol package.
+ responses::error::Error {
+ failure_reason: format!("Authentication error: {err}"),
}
}
diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs
index 35c5b1409..1b9196e25 100644
--- a/src/servers/http/v1/handlers/scrape.rs
+++ b/src/servers/http/v1/handlers/scrape.rs
@@ -12,14 +12,14 @@ use axum::response::{IntoResponse, Response};
use bittorrent_http_protocol::v1::requests::scrape::Scrape;
use bittorrent_http_protocol::v1::responses;
use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources};
+use bittorrent_tracker_core::authentication::service::AuthenticationService;
+use bittorrent_tracker_core::authentication::Key;
+use bittorrent_tracker_core::scrape_handler::ScrapeHandler;
+use bittorrent_tracker_core::statistics::event::sender::Sender;
use hyper::StatusCode;
use torrust_tracker_configuration::Core;
use torrust_tracker_primitives::core::ScrapeData;
-use crate::core::authentication::service::AuthenticationService;
-use crate::core::authentication::Key;
-use crate::core::scrape_handler::ScrapeHandler;
-use crate::core::statistics::event::sender::Sender;
use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey;
use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources;
use crate::servers::http::v1::extractors::scrape_request::ExtractRequest;
@@ -171,21 +171,20 @@ mod tests {
use bittorrent_http_protocol::v1::responses;
use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources;
use bittorrent_primitives::info_hash::InfoHash;
+ use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository;
+ use bittorrent_tracker_core::authentication::service::AuthenticationService;
+ use bittorrent_tracker_core::scrape_handler::ScrapeHandler;
+ use bittorrent_tracker_core::statistics;
+ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
+ use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization;
+ use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist;
use torrust_tracker_configuration::{Configuration, Core};
use torrust_tracker_test_helpers::configuration;
- use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository;
- use crate::core::authentication::service::AuthenticationService;
- use crate::core::scrape_handler::ScrapeHandler;
- use crate::core::statistics;
- use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository;
- use crate::core::whitelist::authorization::WhitelistAuthorization;
- use crate::core::whitelist::repository::in_memory::InMemoryWhitelist;
-
struct CoreTrackerServices {
pub core_config: Arc,
pub scrape_handler: Arc,
- pub stats_event_sender: Arc