1
Fork 0

Compare commits

...

73 commits

Author SHA1 Message Date
79e604eb96
rdserver: Use mediatype to process Accept header 2024-11-19 06:41:19 +01:00
f223ce64fe
Checkpoint non-atomic commit 2024-11-19 06:06:48 +01:00
8b01cc14c0
Checkpoint non-atomic commit 2024-11-19 03:31:07 +01:00
aec5a01f2c
rd: Fix typo 2024-11-19 00:37:50 +01:00
f36ecbfc6d
rd: Improve crate metadata 2024-11-19 00:16:19 +01:00
86cdf48106
database: Add debug logging 2024-11-19 00:13:24 +01:00
0c86515def
rd: Bump version to 0.3.0 2024-11-19 00:08:47 +01:00
8aa0d31041
Rename acrate-hostmeta to acrate_rd 2024-11-19 00:08:11 +01:00
7d1e1d2dd7
inbox: Temporarily delete 2024-11-18 19:57:07 +01:00
ef7d23490e
database: Bump version to 0.3.0 2024-11-18 19:56:04 +01:00
7ad60b68f6
database: Heavy refactoring and cleanup 2024-11-18 19:55:21 +01:00
1322023e23
database: Allow meta_subjects.subject to be null 2024-11-18 18:24:15 +01:00
17a0dfd21d
database: Add some documentation 2024-11-18 09:48:43 +01:00
ccae871d8e
database: Create acrate_database_migrate bin that runs migrations 2024-11-18 09:45:03 +01:00
09295b2ce8
database: Add crate metadata 2024-11-18 06:24:08 +01:00
e758e670e6
Rename acrate-core to acrate_database 2024-11-18 06:13:49 +01:00
cc6dfd0dfc
webfinger: Use the subject field to determine the canonical name of the subject 2024-11-16 07:49:28 +01:00
219880f3d3
core: Fix type mismatch 2024-11-16 07:49:12 +01:00
5078b41499
core: Add subject column 2024-11-16 07:43:54 +01:00
0e7aacdd0e
Create webfinger crate' (#5)
Reviewed-on: #5
2024-11-16 06:33:05 +00:00
ee1eb9f470
Add README listing crates 2024-11-16 07:30:35 +01:00
8ca9d01688
webfinger: Don't link self 2024-11-16 07:29:09 +01:00
7319a3fe71
webfinger: Add basic CSS to the page 2024-11-16 07:24:14 +01:00
0498e45b59
webfinger: Handle not found and redirects 2024-11-16 06:46:25 +01:00
7f392bef36
core: Fix schema 2024-11-16 06:45:58 +01:00
c83fdc43e6
webfinger: text/html version of the document 2024-11-16 06:16:52 +01:00
dfee4e510e
core: Add meta_subjects to handle redirects 2024-11-16 06:16:34 +01:00
d80888c9db
webfinger: Add link properties and titles 2024-11-16 02:58:45 +01:00
5b8b166323
Obliterate .idea/misc.xml from existence 2024-11-16 02:56:24 +01:00
86f9aa27f2
hostmeta: Schema improvements 2024-11-16 02:55:08 +01:00
a5b6485d11
core: Allow querying meta objects grouped by parent 2024-11-16 02:54:55 +01:00
a5b9918c43
webfinger: Property.r#type to Property.rel 2024-11-16 01:42:04 +01:00
8b5408f21e
hostmeta: Property.r#type to Property.rel 2024-11-16 01:41:57 +01:00
72f3669ef1
webfinger: yield to type_ 2024-11-16 01:35:30 +01:00
8a49903eca
core: Support meta titles 2024-11-15 20:53:59 +01:00
f2d73c1798
core: Further schema improvements 2024-11-15 20:48:51 +01:00
d1dcbc1fc6
core: Give up on renaming type_ 2024-11-15 20:44:06 +01:00
e5412d85ba
core: Update schema with more details 2024-11-15 20:43:41 +01:00
c36b6edbfb
webfinger: Serve XRD and JRD responses 2024-11-15 18:12:13 +01:00
49b1b8ba65
hostmeta: Fix value being wrapped in a tag 2024-11-15 18:10:39 +01:00
32f756f800
hostmeta: Fix type not being an attribute 2024-11-15 18:10:02 +01:00
a020861e33
hostmeta: Make the root element use the XRD tag 2024-11-15 17:57:31 +01:00
065fa9c80e
Eyes are closing, git fire 2024-11-15 06:50:51 +01:00
f5449cd397
core: Fix r#type again 2024-11-15 06:31:49 +01:00
6315c22ad6
core: Add missing rel attribute to meta_properties 2024-11-15 06:30:42 +01:00
affb063508
webfinger: Add acrate-core dependency 2024-11-15 05:23:21 +01:00
94203cdc7b
core: Filter meta queries on document 2024-11-15 05:23:06 +01:00
d0aa551ef4
core: Add document to the meta types 2024-11-15 05:21:05 +01:00
b7924c8776
core: Fix r#type in schema 2024-11-15 05:20:46 +01:00
3906d03653
core: Add document field to meta tables 2024-11-15 05:19:50 +01:00
69392bf7e5
core: DROP tables only IF EXISTS 2024-11-15 05:19:25 +01:00
153dc7d50f
core: Cascade table DROPs 2024-11-15 05:18:52 +01:00
3e2a7fd110
core: Expose diesel and diesel_async 2024-11-15 04:59:13 +01:00
c235467b06
core: Add queryable meta structs 2024-11-15 03:16:06 +01:00
18b3619785
core: Apparently you still need the postgres feature on diesel 2024-11-15 02:57:39 +01:00
6ebf2ddd6d
core: Use diesel_async dep 2024-11-15 02:40:58 +01:00
b5d907bd07
core: Use r#type instead of type_ 2024-11-15 02:35:17 +01:00
5a3d913933
core: Don't define database functions, implement them in Rust 2024-11-15 02:34:53 +01:00
21842d9f80
core: Add base core::meta structs 2024-11-15 02:16:16 +01:00
2ca4bb3662
core: Rename link to meta_link_id 2024-11-15 02:15:29 +01:00
84f7002338
core: Make link not null 2024-11-15 02:12:26 +01:00
c27af2cf53
core: Use plural in table names 2024-11-15 02:05:49 +01:00
e65c85616d
core: Use plural in table names 2024-11-15 02:04:15 +01:00
956bd17ad0
core: Make core::meta public 2024-11-15 01:57:32 +01:00
c9afa95fd6
core: Remove dependency on workspace
(This will be the database crate)
2024-11-15 01:57:13 +01:00
34e1eff855
core: Add uuid feature to diesel 2024-11-15 01:51:30 +01:00
c09edc9b08
core: Attach core::schema 2024-11-15 01:49:26 +01:00
ad2383c56b
core: Add postgres feature to diesel 2024-11-15 01:48:01 +01:00
03aab44ba4
core: Rename migration 2024-11-15 01:37:26 +01:00
2d3421e2c3
core: Create migration for metadata tables 2024-11-14 06:23:38 +01:00
025311e100
webfinger: Properly handle requests 2024-11-14 04:16:12 +01:00
8145ce57cc
webfinger: Parse query string with serde and axum_extra 2024-11-14 04:02:40 +01:00
646696a49e
webfinger: Create crate by cloning inbox 2024-11-14 03:51:11 +01:00
43 changed files with 1867 additions and 161 deletions

3
.gitignore vendored
View file

@ -15,3 +15,6 @@ Cargo.lock
# Environment
.env.local
# IntelliJ IDEA thing, mostly broken versioning
.idea/misc.xml

View file

@ -3,12 +3,14 @@
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/acrate-core/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/acrate-hostmeta/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/acrate-hostmeta/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/acrate-inbox/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/acrate-nodeinfo/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/acrate-nodeinfo/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/acrate_database/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/acrate_nodeinfo/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/acrate_nodeinfo/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/acrate_rd/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/acrate_rd/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/acrate_mime/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/acrate_rdserver/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />

12
.idea/dataSources.xml Normal file
View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="acrate" uuid="8258414e-095d-430b-a0a5-b48e72af23a9">
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql:///acrate</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

View file

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DiscordProjectSettings">
<option name="show" value="ASK" />
<option name="description" value="" />
</component>
</project>

6
.idea/sqldialects.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/acrate_database/migrations/2024-11-14-031744_meta/up.sql" dialect="GenericSQL" />
</component>
</project>

View file

@ -1,3 +1,3 @@
[workspace]
resolver = "2"
members = ["acrate-core", "acrate-hostmeta", "acrate-inbox", "acrate-nodeinfo"]
members = ["acrate_database", "acrate_rd", "acrate_nodeinfo", "acrate_rdserver"]

287
LICENSE.txt Normal file
View file

@ -0,0 +1,287 @@
EUROPEAN UNION PUBLIC LICENCE v. 1.2
EUPL © the European Union 2007, 2016
This European Union Public Licence (the EUPL) applies to the Work (as defined
below) which is provided under the terms of this Licence. Any use of the Work,
other than as authorised under this Licence is prohibited (to the extent such
use is covered by a right of the copyright holder of the Work).
The Work is provided under the terms of this Licence when the Licensor (as
defined below) has placed the following notice immediately following the
copyright notice for the Work:
Licensed under the EUPL
or has expressed by any other means his willingness to license under the EUPL.
1. Definitions
In this Licence, the following terms have the following meaning:
- The Licence: this Licence.
- The Original Work: the work or software distributed or communicated by the
Licensor under this Licence, available as Source Code and also as Executable
Code as the case may be.
- Derivative Works: the works or software that could be created by the
Licensee, based upon the Original Work or modifications thereof. This Licence
does not define the extent of modification or dependence on the Original Work
required in order to classify a work as a Derivative Work; this extent is
determined by copyright law applicable in the country mentioned in Article 15.
- The Work: the Original Work or its Derivative Works.
- The Source Code: the human-readable form of the Work which is the most
convenient for people to study and modify.
- The Executable Code: any code which has generally been compiled and which is
meant to be interpreted by a computer as a program.
- The Licensor: the natural or legal person that distributes or communicates
the Work under the Licence.
- Contributor(s): any natural or legal person who modifies the Work under the
Licence, or otherwise contributes to the creation of a Derivative Work.
- The Licensee or You: any natural or legal person who makes any usage of
the Work under the terms of the Licence.
- Distribution or Communication: any act of selling, giving, lending,
renting, distributing, communicating, transmitting, or otherwise making
available, online or offline, copies of the Work or providing access to its
essential functionalities at the disposal of any other natural or legal
person.
2. Scope of the rights granted by the Licence
The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
sublicensable licence to do the following, for the duration of copyright vested
in the Original Work:
- use the Work in any circumstance and for all usage,
- reproduce the Work,
- modify the Work, and make Derivative Works based upon the Work,
- communicate to the public, including the right to make available or display
the Work or copies thereof to the public and perform publicly, as the case may
be, the Work,
- distribute the Work or copies thereof,
- lend and rent the Work or copies thereof,
- sublicense rights in the Work or copies thereof.
Those rights can be exercised on any media, supports and formats, whether now
known or later invented, as far as the applicable law permits so.
In the countries where moral rights apply, the Licensor waives his right to
exercise his moral right to the extent allowed by law in order to make effective
the licence of the economic rights here above listed.
The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to
any patents held by the Licensor, to the extent necessary to make use of the
rights granted on the Work under this Licence.
3. Communication of the Source Code
The Licensor may provide the Work either in its Source Code form, or as
Executable Code. If the Work is provided as Executable Code, the Licensor
provides in addition a machine-readable copy of the Source Code of the Work
along with each copy of the Work that the Licensor distributes or indicates, in
a notice following the copyright notice attached to the Work, a repository where
the Source Code is easily and freely accessible for as long as the Licensor
continues to distribute or communicate the Work.
4. Limitations on copyright
Nothing in this Licence is intended to deprive the Licensee of the benefits from
any exception or limitation to the exclusive rights of the rights owners in the
Work, of the exhaustion of those rights or of other applicable limitations
thereto.
5. Obligations of the Licensee
The grant of the rights mentioned above is subject to some restrictions and
obligations imposed on the Licensee. Those obligations are the following:
Attribution right: The Licensee shall keep intact all copyright, patent or
trademarks notices and all notices that refer to the Licence and to the
disclaimer of warranties. The Licensee must include a copy of such notices and a
copy of the Licence with every copy of the Work he/she distributes or
communicates. The Licensee must cause any Derivative Work to carry prominent
notices stating that the Work has been modified and the date of modification.
Copyleft clause: If the Licensee distributes or communicates copies of the
Original Works or Derivative Works, this Distribution or Communication will be
done under the terms of this Licence or of a later version of this Licence
unless the Original Work is expressly distributed only under this version of the
Licence — for example by communicating EUPL v. 1.2 only. The Licensee
(becoming Licensor) cannot offer or impose any additional terms or conditions on
the Work or Derivative Work that alter or restrict the terms of the Licence.
Compatibility clause: If the Licensee Distributes or Communicates Derivative
Works or copies thereof based upon both the Work and another work licensed under
a Compatible Licence, this Distribution or Communication can be done under the
terms of this Compatible Licence. For the sake of this clause, Compatible
Licence refers to the licences listed in the appendix attached to this Licence.
Should the Licensee's obligations under the Compatible Licence conflict with
his/her obligations under this Licence, the obligations of the Compatible
Licence shall prevail.
Provision of Source Code: When distributing or communicating copies of the Work,
the Licensee will provide a machine-readable copy of the Source Code or indicate
a repository where this Source will be easily and freely available for as long
as the Licensee continues to distribute or communicate the Work.
Legal Protection: This Licence does not grant permission to use the trade names,
trademarks, service marks, or names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the copyright notice.
6. Chain of Authorship
The original Licensor warrants that the copyright in the Original Work granted
hereunder is owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each Contributor warrants that the copyright in the modifications he/she brings
to the Work are owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each time You accept the Licence, the original Licensor and subsequent
Contributors grant You a licence to their contributions to the Work, under the
terms of this Licence.
7. Disclaimer of Warranty
The Work is a work in progress, which is continuously improved by numerous
Contributors. It is not a finished work and may therefore contain defects or
bugs inherent to this type of development.
For the above reason, the Work is provided under the Licence on an as is basis
and without warranties of any kind concerning the Work, including without
limitation merchantability, fitness for a particular purpose, absence of defects
or errors, accuracy, non-infringement of intellectual property rights other than
copyright as stated in Article 6 of this Licence.
This disclaimer of warranty is an essential part of the Licence and a condition
for the grant of any rights to the Work.
8. Disclaimer of Liability
Except in the cases of wilful misconduct or damages directly caused to natural
persons, the Licensor will in no event be liable for any direct or indirect,
material or moral, damages of any kind, arising out of the Licence or of the use
of the Work, including without limitation, damages for loss of goodwill, work
stoppage, computer failure or malfunction, loss of data or any commercial
damage, even if the Licensor has been advised of the possibility of such damage.
However, the Licensor will be liable under statutory product liability laws as
far such laws apply to the Work.
9. Additional agreements
While distributing the Work, You may choose to conclude an additional agreement,
defining obligations or services consistent with this Licence. However, if
accepting obligations, You may act only on your own behalf and on your sole
responsibility, not on behalf of the original Licensor or any other Contributor,
and only if You agree to indemnify, defend, and hold each Contributor harmless
for any liability incurred by, or claims asserted against such Contributor by
the fact You have accepted any warranty or additional liability.
10. Acceptance of the Licence
The provisions of this Licence can be accepted by clicking on an icon I agree
placed under the bottom of a window displaying the text of this Licence or by
affirming consent in any other similar way, in accordance with the rules of
applicable law. Clicking on that icon indicates your clear and irrevocable
acceptance of this Licence and all of its terms and conditions.
Similarly, you irrevocably accept this Licence and all of its terms and
conditions by exercising any rights granted to You by Article 2 of this Licence,
such as the use of the Work, the creation by You of a Derivative Work or the
Distribution or Communication by You of the Work or copies thereof.
11. Information to the public
In case of any Distribution or Communication of the Work by means of electronic
communication by You (for example, by offering to download the Work from a
remote location) the distribution channel or media (for example, a website) must
at least provide to the public the information requested by the applicable law
regarding the Licensor, the Licence and the way it may be accessible, concluded,
stored and reproduced by the Licensee.
12. Termination of the Licence
The Licence and the rights granted hereunder will terminate automatically upon
any breach by the Licensee of the terms of the Licence.
Such a termination will not terminate the licences of any person who has
received the Work from the Licensee under the Licence, provided such persons
remain in full compliance with the Licence.
13. Miscellaneous
Without prejudice of Article 9 above, the Licence represents the complete
agreement between the Parties as to the Work.
If any provision of the Licence is invalid or unenforceable under applicable
law, this will not affect the validity or enforceability of the Licence as a
whole. Such provision will be construed or reformed so as necessary to make it
valid and enforceable.
The European Commission may publish other linguistic versions or new versions of
this Licence or updated versions of the Appendix, so far this is required and
reasonable, without reducing the scope of the rights granted by the Licence. New
versions of the Licence will be published with a unique version number.
All linguistic versions of this Licence, approved by the European Commission,
have identical value. Parties can take advantage of the linguistic version of
their choice.
14. Jurisdiction
Without prejudice to specific agreement between parties,
- any litigation resulting from the interpretation of this License, arising
between the European Union institutions, bodies, offices or agencies, as a
Licensor, and any Licensee, will be subject to the jurisdiction of the Court
of Justice of the European Union, as laid down in article 272 of the Treaty on
the Functioning of the European Union,
- any litigation arising between other parties and resulting from the
interpretation of this License, will be subject to the exclusive jurisdiction
of the competent court where the Licensor resides or conducts its primary
business.
15. Applicable Law
Without prejudice to specific agreement between parties,
- this Licence shall be governed by the law of the European Union Member State
where the Licensor has his seat, resides or has his registered office,
- this licence shall be governed by Belgian law if the Licensor has no seat,
residence or registered office inside a European Union Member State.
Appendix
Compatible Licences according to Article 5 EUPL are:
- GNU General Public License (GPL) v. 2, v. 3
- GNU Affero General Public License (AGPL) v. 3
- Open Software License (OSL) v. 2.1, v. 3.0
- Eclipse Public License (EPL) v. 1.0
- CeCILL v. 2.0, v. 2.1
- Mozilla Public Licence (MPL) v. 2
- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
works other than software
- European Union Public Licence (EUPL) v. 1.1, v. 1.2
- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong
Reciprocity (LiLiQ-R+).
The European Commission may update this Appendix to later versions of the above
licences without producing a new version of the EUPL, as long as they provide
the rights granted in Article 2 of this Licence and protect the covered Source
Code from exclusive appropriation.
All other changes or additions to this Appendix require the production of a new
EUPL version.

View file

@ -11,3 +11,19 @@ Federation database
> [!Caution]
>
> This software suite is in active development!
> [!Warning]
>
> **Monorepo!** Make sure to open the root directory in your IDE, or weird things might happen until the packages are published!
## Crates
### Libraries
- `acrate_database`: Database schema, migrations, and high level database-reliant structures
- `acrate_nodeinfo`: Rust typing and utilities for the NodeInfo format
- `acrate_rd`: Rust typing and utilities for the JSON and XML resource descriptior formats
### Binaries
- `acrate_rdserver`: Resource descriptor web server

View file

@ -1,13 +0,0 @@
[package]
name = "acrate-core"
version = "0.1.0"
edition = "2021"
[dependencies]
diesel = "2.2.4"
diesel_migrations = "2.2.0"
acrate-hostmeta = { path = "../acrate-hostmeta" }
acrate-nodeinfo = { path = "../acrate-nodeinfo" }
[lints.clippy]
tabs-in-doc-comments = "allow"

View file

@ -1,4 +0,0 @@
//! Core crate of the `acrate` project.
pub use acrate_nodeinfo as nodeinfo;
pub use acrate_hostmeta as hostmeta;

View file

@ -1,8 +0,0 @@
/// Extract the MIME type from the value of the `Content-Type` header.
pub fn extract_mime_from_content_type(value: &reqwest::header::HeaderValue) -> Option<String> {
let value = value.to_str().ok()?;
match value.split_once("; ") {
None => Some(value.to_string()),
Some((mime, _)) => Some(mime.to_string()),
}
}

View file

@ -1,12 +0,0 @@
[package]
name = "acrate-inbox"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0.93"
axum = "0.7.7"
log = "0.4.22"
micronfig = "0.3.0"
pretty_env_logger = "0.5.0"
tokio = { version = "1.41.1", features = ["macros", "net", "rt-multi-thread"] }

View file

@ -1,3 +0,0 @@
micronfig::config!(
ACRATE_INBOX_BIND_ADDRESS: String,
);

View file

@ -1,8 +0,0 @@
#[allow(unreachable_code)]
pub async fn inbox_handler() {
todo!("pre-validation hook");
todo!("validate signature");
todo!("post-validation hook");
todo!("database storage");
todo!("post-storage hook");
}

View file

@ -1,20 +0,0 @@
[package]
name = "acrate-nodeinfo"
version = "0.1.0"
edition = "2021"
[dependencies]
acrate-hostmeta = { path = "../acrate-hostmeta" }
log = "0.4.22"
reqwest = { version = "0.12.9", features = ["json", "stream"] }
serde = { version = "1.0.214", features = ["derive"] }
serde_json = "1.0.132"
thiserror = "2.0.3"
[dev-dependencies]
pretty_env_logger = "0.5.0"
tokio = { version = "1.41.1", features = ["macros", "rt-multi-thread"] }
tokio-test = "0.4.4"
[lints.clippy]
tabs-in-doc-comments = "allow"

View file

@ -0,0 +1,34 @@
[package]
name = "acrate_database"
version = "0.3.0"
authors = ["Stefano Pigozzi <me@steffo.eu>"]
edition = "2021"
description = "Database schema and migrations for the acrate project"
repository = "https://forge.steffo.eu/unimore/tirocinio-canali-steffo-acrate"
license = "EUPL-1.2"
keywords = ["fediverse", "diesel", "database", "postgresql", "database-migrations"]
categories = ["database"]
[dependencies]
diesel = { version = "2.2.4", features = ["postgres", "uuid"] }
diesel-async = { version = "0.5.1", features = ["postgres"] }
diesel_migrations = { version = "2.2.0", optional = true }
log = "0.4.22"
mediatype = "0.19.18"
micronfig = { version = "0.3.0", optional = true }
mime = "0.3.17"
pretty_env_logger = { version = "0.5.0", optional = true }
uuid = "1.11.0"
[features]
bin = ["diesel_migrations", "micronfig", "pretty_env_logger"]
[lib]
name = "acrate_database"
[[bin]]
name = "acrate_database_migrate"
required-features = ["bin"]
[lints.clippy]
tabs-in-doc-comments = "allow"

View file

@ -0,0 +1,6 @@
DROP TABLE IF EXISTS meta_properties CASCADE;
DROP TABLE IF EXISTS meta_link_properties CASCADE;
DROP TABLE IF EXISTS meta_link_titles CASCADE;
DROP TABLE IF EXISTS meta_links CASCADE;
DROP TABLE IF EXISTS meta_aliases CASCADE;
DROP TABLE IF EXISTS meta_subjects CASCADE;

View file

@ -0,0 +1,69 @@
CREATE TABLE IF NOT EXISTS meta_subjects (
id UUID DEFAULT gen_random_uuid(),
document BPCHAR NOT NULL,
pattern BPCHAR NOT NULL,
subject BPCHAR,
redirect BPCHAR,
CONSTRAINT either_subject_or_redirect_not_null CHECK (
(subject IS NOT NULL AND redirect IS NULL)
OR
(subject IS NULL AND redirect IS NOT NULL)
),
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_aliases (
id UUID DEFAULT gen_random_uuid(),
document BPCHAR NOT NULL,
pattern BPCHAR NOT NULL,
alias BPCHAR NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_links (
id UUID DEFAULT gen_random_uuid(),
document BPCHAR NOT NULL,
pattern BPCHAR NOT NULL,
rel BPCHAR NOT NULL,
type BPCHAR,
href BPCHAR,
template BPCHAR,
CONSTRAINT either_href_or_template_not_null CHECK (
(href IS NOT NULL AND template IS NULL)
OR
(href IS NULL AND template IS NOT NULL)
),
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_link_properties (
id UUID DEFAULT gen_random_uuid(),
meta_link_id UUID REFERENCES meta_links (id) NOT NULL,
rel BPCHAR NOT NULL,
value BPCHAR,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_properties (
id UUID DEFAULT gen_random_uuid(),
document BPCHAR NOT NULL,
pattern BPCHAR NOT NULL,
rel BPCHAR NOT NULL,
value BPCHAR,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS meta_link_titles (
id UUID DEFAULT gen_random_uuid(),
meta_link_id UUID REFERENCES meta_links (id) NOT NULL,
language BPCHAR NOT NULL DEFAULT 'und',
value BPCHAR NOT NULL,
CONSTRAINT unique_languages UNIQUE (meta_link_id, language),
PRIMARY KEY(id)
);

View file

@ -0,0 +1,10 @@
UPDATE meta_subjects SET subject = 'invalid:subject.null' WHERE subject IS NULL;
ALTER TABLE meta_subjects ALTER subject SET NOT NULL;
ALTER TABLE meta_subjects ADD CONSTRAINT either_subject_or_redirect_not_null
CHECK (
(subject IS NOT NULL AND redirect IS NULL)
OR
(subject IS NULL AND redirect IS NOT NULL)
);

View file

@ -0,0 +1,5 @@
ALTER TABLE meta_subjects DROP CONSTRAINT either_subject_or_redirect_not_null;
ALTER TABLE meta_subjects ALTER subject DROP NOT NULL;
UPDATE meta_subjects SET subject = NULL WHERE subject = 'invalid:subject.null';

View file

@ -0,0 +1,50 @@
//! Run all migrations defined by [`acrate_database`].
//!
//! This uses the configuration defined in [`acrate_database::config`].
//!
//! ## Exit codes
//!
//! | Code | Meaning |
//! |-----:|---------|
//! | `0` | Migrations applied successfully |
//! | `1` | Couldn't connect to the database |
//! | `2` | Couldn't apply migrations |
//! | `101` | Configuration is invalid |
//!
use std::process::exit;
use diesel::{Connection, PgConnection};
use diesel_migrations::{EmbeddedMigrations, MigrationHarness};
mod config {
micronfig::config! {
ACRATE_DATABASE_DATABASE_URL: String,
}
}
pub const MIGRATIONS: EmbeddedMigrations = diesel_migrations::embed_migrations!();
fn main() {
pretty_env_logger::init();
log::info!("Logging initialized successfully!");
log::trace!("Determining database URL...");
let db = config::ACRATE_DATABASE_DATABASE_URL();
log::debug!("Connecting to: {db:?}");
let mut db = match PgConnection::establish(db) {
Err(e) => {
log::error!("Failed to connect to the PostgreSQL database: {e:#?}");
exit(1);
}
Ok(db) => db,
};
log::debug!("Running migrations...");
if let Err(e) = db.run_pending_migrations(MIGRATIONS) {
log::error!("Failed to perform migration: {e:#?}");
exit(2);
};
log::info!("Migrations applied successfully!")
}

View file

@ -0,0 +1,11 @@
//! Database schema, migrations, and high level database-reliant structures for the [`acrate`] project.
/// Database schema information automatically generated by [`diesel`].
///
/// Configured by `diesel.toml`.
mod schema;
pub mod meta;
pub use diesel;
pub use diesel_async;

560
acrate_database/src/meta.rs Normal file
View file

@ -0,0 +1,560 @@
//! Tables related to web page metadata, XRD and JRD, `host-meta`, `WebFinger`, and so on.
//!
//! # Intended usage
//!
//! 1. An user agent requests an application for the descriptor for a given resource;
//! 2. **The application queries the database using these structures to:**
//! 1. [Determine if a descriptor should be returned, or if it should be handled by another application](MetaSubject);
//! 2. [Determine which aliases the resource has](MetaAlias);
//! 3. [Determine which properties the resource has](MetaProperty);
//! 4. [Determine which links the resource has](MetaLink);
//! 5. [Determine the titles of each link](MetaLinkTitle);
//! 6. [Determine the properties of each link](MetaLinkProperty);
//! 3. The application compiles the data in a single structure that the user agent supports
//! 4. The application returns the data to the user agent
//!
//! # Matching
//!
//! Matching is performed for each single record separately, allowing for example a system administrator to define many separate subjects while globally defining a property for all the resources served.
//!
//! # Reference
//!
//! See [`acrate_rd`] for more information on the specification these structures are based on.
//!
//! # Used by
//!
//! - [`acrate_rdserver`]
//!
use diesel::deserialize::FromSql;
use diesel::{AsExpression, Associations, FromSqlRow, Identifiable, Insertable, IntoSql, PgTextExpressionMethods, QueryResult, Queryable, QueryableByName, Selectable, SelectableHelper, ExpressionMethods, BelongingToDsl};
use diesel::pg::{Pg, PgConnection};
use diesel::serialize::{Output, ToSql};
use diesel_async::AsyncPgConnection;
use mediatype::MediaTypeBuf;
use uuid::Uuid;
use super::schema;
/// Wrapper to use [`mime::Mime`] with [`diesel`].
#[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct MediaTypeDatabase(pub MediaTypeBuf);
/// A matchable record denoting the existence of a resource descriptor.
///
/// # See also
///
/// - [`MetaSubjectInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable)]
#[diesel(table_name = schema::meta_subjects)]
#[diesel(check_for_backend(Pg))]
pub struct MetaSubject {
/// The identity column of the record.
pub id: Uuid,
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The value the `subject` property should take when this record is matched.
///
/// If [`None`], its value is up for specification by the querying application.
pub subject: Option<String>,
/// Where the querying application should redirect the user agent to when this record is matched.
///
/// If [`Some`], should always override everything else.
pub redirect: Option<String>,
}
/// An [`Insertable`] version of [`MetaSubject`].
#[derive(Debug, Insertable)]
#[diesel(table_name = schema::meta_subjects)]
#[diesel(check_for_backend(Pg))]
pub struct MetaSubjectInsert {
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The value the `subject` property should take when this record is matched.
///
/// If [`None`], its value is up for specification by the querying application.
pub subject: Option<String>,
/// Where the querying application should redirect the user agent to when this record is matched.
///
/// If [`Some`], should always override everything else.
pub redirect: Option<String>,
}
/// A matchable record denoting an alias belonging to a subject.
///
/// # See also
///
/// - [`MetaAliasInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable)]
#[diesel(table_name = schema::meta_aliases)]
#[diesel(check_for_backend(Pg))]
pub struct MetaAlias {
/// The identity column of the record.
pub id: Uuid,
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The alias to **add** to the list of aliases of the resource.
pub alias: String,
}
/// An [`Insertable`] version of [`MetaAlias`].
#[derive(Debug, Insertable)]
#[diesel(table_name = schema::meta_aliases)]
#[diesel(check_for_backend(Pg))]
pub struct MetaAliasInsert {
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The alias to **add** to the list of aliases of the resource.
pub alias: String,
}
/// A matchable record denoting a link towards another resource someway related with the subject.
///
/// # See also
///
/// - [`MetaLinkInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable)]
#[diesel(table_name = schema::meta_links)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLink {
/// The identity column of the record.
pub id: Uuid,
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The relationship the link establishes between itself and the value of the link.
pub rel: String,
/// The media type of the value of the link.
///
/// Can be [`None`] if it shouldn't be specified.
pub type_: Option<MediaTypeDatabase>,
/// The URI to the document this property is linking the subject to.
///
/// Can be [`None`] if it shouldn't be specified, for example if [`Self::template`] is [`Some`].
pub href: Option<String>,
/// The template to the document this property is linking the subject to.
///
/// Can be [`None`] if it shouldn't be specified, for example if [`Self::href`] is [`Some`].
pub template: Option<String>,
}
/// An [`Insertable`] version of [`MetaLink`].
#[derive(Debug, Insertable)]
#[diesel(table_name = schema::meta_links)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkInsert {
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The relationship the link establishes between itself and the value of the link.
pub rel: String,
/// The media type of the value of the link.
///
/// Can be [`None`] if it shouldn't be specified.
pub type_: Option<MediaTypeDatabase>,
/// The URI to the document this property is linking the subject to.
///
/// Can be [`None`] if it shouldn't be specified, for example if [`Self::template`] is [`Some`].
pub href: Option<String>,
/// The template to the document this property is linking the subject to.
///
/// Can be [`None`] if it shouldn't be specified, for example if [`Self::href`] is [`Some`].
pub template: Option<String>,
}
/// A property that a [`MetaLink`] has.
///
/// # See also
///
/// - [`MetaLinkPropertyInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable, Associations)]
#[diesel(belongs_to(MetaLink))]
#[diesel(table_name = schema::meta_link_properties)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkProperty {
/// The identity column of the record.
pub id: Uuid,
/// The [`MetaLink::id`] this record refers to.
pub meta_link_id: Uuid,
/// The relationship the property establishes between the [`MetaLink`] and the [`MetaLinkProperty::value`].
pub rel: String,
/// The value that the property has.
pub value: Option<String>,
}
/// An [`Insertable`] version of [`MetaLinkProperty`].
#[derive(Debug, Insertable)]
#[diesel(belongs_to(MetaLink))]
#[diesel(table_name = schema::meta_link_properties)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkPropertyInsert {
/// The [`MetaLink::id`] this record refers to.
pub meta_link_id: Uuid,
/// The relationship the property establishes between the [`MetaLink`] and the [`MetaLinkProperty::value`].
pub rel: String,
/// The value that the property has.
pub value: Option<String>,
}
/// A title that a [`MetaLink`] has in a certain language.
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable, Associations)]
#[diesel(belongs_to(MetaLink))]
#[diesel(table_name = schema::meta_link_titles)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkTitle {
/// The identity column of the record.
pub id: Uuid,
/// The [`MetaLink::id`] this record refers to.
pub meta_link_id: Uuid,
/// The language of the title.
pub language: String,
/// The actual contents of the title.
pub value: String,
}
/// An [`Insertable`] version of [`MetaLinkTitle`].
#[derive(Debug, Insertable)]
#[diesel(belongs_to(MetaLink))]
#[diesel(table_name = schema::meta_link_titles)]
#[diesel(check_for_backend(Pg))]
pub struct MetaLinkTitleInsert {
/// The [`MetaLink::id`] this record refers to.
pub meta_link_id: Uuid,
/// The language of the title.
pub language: String,
/// The actual contents of the title.
pub value: String,
}
/// A matchable record denoting a property that a subject has.
///
/// # See also
///
/// - [`MetaPropertyInsert`]
///
#[derive(Debug, Queryable, QueryableByName, Identifiable, Selectable)]
#[diesel(table_name = schema::meta_properties)]
#[diesel(check_for_backend(Pg))]
pub struct MetaProperty {
/// The identity column of the record.
pub id: Uuid,
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The relationship the property establishes between the [`MetaSubject`] and the [`MetaProperty::value`].
pub rel: String,
/// The value that the property has.
pub value: Option<String>,
}
/// An [`Insertable`] version of [`MetaLinkTitle`].
#[derive(Debug, Insertable)]
#[diesel(table_name = schema::meta_properties)]
#[diesel(check_for_backend(Pg))]
pub struct MetaPropertyInsert {
/// The document the record is valid for.
pub document: String,
/// The [PostgreSQL ILIKE pattern] to match the search term against for the record to be valid.
///
/// [PostgreSQL ILIKE pattern]: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE
pub pattern: String,
/// The relationship the property establishes between the [`MetaSubject`] and the [`MetaProperty::value`].
pub rel: String,
/// The value that the property has.
pub value: Option<String>,
}
/// Allow [`diesel::sql_types::Text`] values to be parsed as [`MediaTypeDatabase`].
impl<DB> FromSql<diesel::sql_types::Text, DB> for MediaTypeDatabase
where
DB: diesel::backend::Backend,
String: FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(bytes: <DB as diesel::backend::Backend>::RawValue<'_>) -> diesel::deserialize::Result<Self> {
log::trace!("Reading TEXT from the database...");
let s = <String as FromSql<diesel::sql_types::Text, DB>>::from_sql(bytes)?;
log::trace!("Attempting to parse as a media type: {s:?}");
let mt: MediaTypeBuf = s.parse()?;
log::trace!("Successfully parsed media type: {mt:?}");
Ok(Self(mt))
}
}
/// Allow [`diesel::sql_types::Text`] values to be written to with [`MediaTypeDatabase`].
impl<DB> ToSql<diesel::sql_types::Text, DB> for MediaTypeDatabase
where
DB: diesel::backend::Backend,
str: ToSql<diesel::sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
log::trace!("Getting the essence of a media type to prepare for serialization...");
let mt = self.0.as_str();
log::trace!("Serializing media type as TEXT: {mt:?}");
<str as ToSql<diesel::sql_types::Text, DB>>::to_sql(mt, out)
}
}
impl MetaSubject {
/// Synchronously query the records matching the given document and resource.
pub fn query_matching(conn: &mut PgConnection, doc: &str, resource: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use schema::meta_subjects::dsl::*;
let document_is_equal = document.eq(doc);
let resource_matches_pattern = resource.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_subjects
.filter(document_is_equal)
.filter(resource_matches_pattern)
.select(Self::as_select())
.load(conn)
}
/// Asynchronously query the records matching the given document and resource.
pub async fn aquery_matching(conn: &mut AsyncPgConnection, doc: &str, resource: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use schema::meta_subjects::dsl::*;
let document_is_equal = document.eq(doc);
let resource_matches_pattern = resource.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_subjects
.filter(document_is_equal)
.filter(resource_matches_pattern)
.select(Self::as_select())
.load(conn)
.await
}
}
impl MetaAlias {
/// Synchronously query the records matching the given document and resource.
pub fn query_matching(conn: &mut PgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use schema::meta_aliases::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_aliases
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
}
/// Asynchronously query the records matching the given document and resource.
pub async fn aquery_matching(conn: &mut AsyncPgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use schema::meta_aliases::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_aliases
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
.await
}
}
impl MetaLink {
/// Synchronously query the records matching the given document and resource.
pub async fn query_matching(conn: &mut PgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use schema::meta_links::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_links
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
}
/// Asynchronously query the records matching the given document and resource.
pub async fn aquery_matching(conn: &mut AsyncPgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use schema::meta_links::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_links
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
.await
}
}
impl MetaLinkProperty {
/// Synchronously query the records belonging to the given [`MetaLink`]s.
pub fn query_by_link(conn: &mut PgConnection, links: &[MetaLink]) -> QueryResult<Vec<Self>> {
use diesel::RunQueryDsl;
Self::belonging_to(links)
.load(conn)
}
/// Asynchronously query the records belonging to the given [`MetaLink`]s.
pub async fn aquery_by_link(conn: &mut AsyncPgConnection, links: &[MetaLink]) -> QueryResult<Vec<Self>> {
use diesel_async::RunQueryDsl;
Self::belonging_to(links)
.load(conn)
.await
}
}
impl MetaLinkTitle {
/// Synchronously query the records belonging to the given [`MetaLink`]s.
pub fn query_by_link(conn: &mut PgConnection, links: &[MetaLink]) -> QueryResult<Vec<Self>> {
use diesel::RunQueryDsl;
Self::belonging_to(links)
.load(conn)
}
/// Asynchronously query the records belonging to the given [`MetaLink`]s.
pub async fn aquery_by_link(conn: &mut AsyncPgConnection, links: &[MetaLink]) -> QueryResult<Vec<Self>> {
use diesel_async::RunQueryDsl;
Self::belonging_to(links)
.load(conn)
.await
}
}
impl MetaProperty {
/// Synchronously query the records matching the given document and resource.
pub fn query_matching(conn: &mut PgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use schema::meta_properties::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_properties
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
}
/// Asynchronously query the records matching the given document and resource.
pub async fn aquery_matching(conn: &mut AsyncPgConnection, doc: &str, subject: &str) -> QueryResult<Vec<Self>> {
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use schema::meta_properties::dsl::*;
let document_is_equal = document.eq(doc);
let subject_matches_pattern = subject.into_sql::<diesel::sql_types::Text>().ilike(pattern);
meta_properties
.filter(document_is_equal)
.filter(subject_matches_pattern)
.select(Self::as_select())
.load(conn)
.await
}
}

View file

@ -0,0 +1,73 @@
// @generated automatically by Diesel CLI.
diesel::table! {
meta_aliases (id) {
id -> Uuid,
document -> Bpchar,
pattern -> Bpchar,
alias -> Bpchar,
}
}
diesel::table! {
meta_link_properties (id) {
id -> Uuid,
meta_link_id -> Uuid,
rel -> Bpchar,
value -> Nullable<Bpchar>,
}
}
diesel::table! {
meta_link_titles (id) {
id -> Uuid,
meta_link_id -> Uuid,
language -> Bpchar,
value -> Bpchar,
}
}
diesel::table! {
meta_links (id) {
id -> Uuid,
document -> Bpchar,
pattern -> Bpchar,
rel -> Bpchar,
#[sql_name = "type"]
type_ -> Nullable<Bpchar>,
href -> Nullable<Bpchar>,
template -> Nullable<Bpchar>,
}
}
diesel::table! {
meta_properties (id) {
id -> Uuid,
document -> Bpchar,
pattern -> Bpchar,
rel -> Bpchar,
value -> Nullable<Bpchar>,
}
}
diesel::table! {
meta_subjects (id) {
id -> Uuid,
document -> Bpchar,
pattern -> Bpchar,
subject -> Nullable<Bpchar>,
redirect -> Nullable<Bpchar>,
}
}
diesel::joinable!(meta_link_properties -> meta_links (meta_link_id));
diesel::joinable!(meta_link_titles -> meta_links (meta_link_id));
diesel::allow_tables_to_appear_in_same_query!(
meta_aliases,
meta_link_properties,
meta_link_titles,
meta_links,
meta_properties,
meta_subjects,
);

View file

@ -0,0 +1,27 @@
[package]
name = "acrate_nodeinfo"
version = "0.3.0"
authors = ["Stefano Pigozzi <me@steffo.eu>"]
edition = "2021"
description = "Rust typing and utilities for the NodeInfo format"
repository = "https://forge.steffo.eu/unimore/tirocinio-canali-steffo-acrate"
license = "EUPL-1.2"
keywords = ["nodeinfo", "fediverse"]
categories = ["web-programming"]
[dependencies]
acrate_rd = { path = "../acrate_rd" }
log = "0.4.22"
mediatype = { version = "0.19.18", features = ["serde"] }
reqwest = { version = "0.12.9", features = ["json", "stream"] }
serde = { version = "1.0.214", features = ["derive"] }
serde_json = "1.0.132"
thiserror = "2.0.3"
[dev-dependencies]
pretty_env_logger = "0.5.0"
tokio = { version = "1.41.1", features = ["macros", "rt-multi-thread"] }
tokio-test = "0.4.4"
[lints.clippy]
tabs-in-doc-comments = "allow"

View file

@ -1,4 +1,4 @@
//! Serde-based NodeInfo fetcher and loose parser.
//! Rust typing and utilities for the NodeInfo format.
//!
//! > NodeInfo is an effort to create a standardized way of exposing metadata about a server running one of the distributed social networks.
//!
@ -6,7 +6,9 @@
//!
//! - <https://github.com/jhass/nodeinfo/blob/main/PROTOCOL.md>
//! - <https://codeberg.org/fediverse/fep/src/branch/main/fep/f1d5/fep-f1d5.md>
//!
use mediatype::MediaTypeBuf;
use serde::Deserialize;
use thiserror::Error;
@ -15,6 +17,7 @@ use thiserror::Error;
/// # Specification
///
/// - <https://github.com/jhass/nodeinfo/blob/main/PROTOCOL.md>
///
#[derive(Debug, Clone)]
pub enum NodeInfo {
V1(NodeInfo1),
@ -206,7 +209,7 @@ impl NodeInfo {
base.set_path(Self::WELLKNOWN_NODEINFO_PATH);
log::trace!("Discovering NodeInfo document locations...");
let discovery = acrate_hostmeta::any::ResourceDescriptor::get(client, base)
let discovery = acrate_rd::any::ResourceDescriptor::get(client, base)
.await
.map_err(Get)?
.jrd();
@ -315,7 +318,7 @@ impl NodeInfo {
pub enum NodeInfoGetWellknownError {
/// The discovery of possible locations for NodeInfo documents failed.
#[error("the discovery of possible locations for NodeInfo documents failed")]
Get(acrate_hostmeta::any::GetError),
Get(acrate_rd::any::GetError),
/// No compatible NodeInfo documents were detected at the given URL.
#[error("no compatible NodeInfo documents were detected at the given URL")]
Unsupported,
@ -346,21 +349,28 @@ impl NodeInfo1 {
let response = client.execute(request)
.await
.map_err(Request)?;
log::trace!("Checking `Content-Type` of the response...");
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.ok_or(ContentTypeMissing)?;
log::trace!("Extracting MIME type from the `Content-Type` header...");
let mime_type = extract_mime_from_content_type(content_type)
.ok_or(ContentTypeInvalid)?;
log::trace!("Ensuring MIME type is acceptable for NodeInfo documents...");
if mime_type != "application/json" {
log::error!("MIME type `{mime_type}` is not acceptable for NodeInfo documents.");
return Err(ContentTypeInvalid)
log::trace!("Extracting media type from the `Content-Type` header: {content_type:?}");
let media_type: MediaTypeBuf = content_type
.to_str()
.map_err(ContentTypeUnprintable)?
.parse()
.map_err(ContentTypeInvalid)?;
log::trace!("Checking if media type is supported: {media_type:?}");
let mime_is_json = media_type.essence().eq(&"application/json".parse::<MediaTypeBuf>().unwrap());
log::trace!("Is media type `application/json`? {mime_is_json:?}");
if !mime_is_json {
log::error!("Media type `{media_type}` is not acceptable for NodeInfo parsing.");
return Err(ContentTypeUnsupported);
}
log::trace!("Attempting to parse response as JSON...");
@ -418,21 +428,28 @@ impl NodeInfo2 {
let response = client.execute(request)
.await
.map_err(Request)?;
log::trace!("Checking `Content-Type` of the response...");
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.ok_or(ContentTypeMissing)?;
log::trace!("Extracting MIME type from the `Content-Type` header...");
let mime_type = extract_mime_from_content_type(content_type)
.ok_or(ContentTypeInvalid)?;
log::trace!("Ensuring MIME type is acceptable for NodeInfo documents...");
if mime_type != "application/json" {
log::error!("MIME type `{mime_type}` is not acceptable for NodeInfo documents.");
return Err(ContentTypeInvalid)
log::trace!("Extracting media type from the `Content-Type` header: {content_type:?}");
let media_type: MediaTypeBuf = content_type
.to_str()
.map_err(ContentTypeUnprintable)?
.parse()
.map_err(ContentTypeInvalid)?;
log::trace!("Checking if media type is supported: {media_type:?}");
let mime_is_json = media_type.essence().eq(&"application/json".parse::<MediaTypeBuf>().unwrap());
log::trace!("Is media type `application/json`? {mime_is_json:?}");
if !mime_is_json {
log::error!("Media type `{media_type}` is not acceptable for NodeInfo parsing.");
return Err(ContentTypeUnsupported);
}
log::trace!("Attempting to parse response as JSON...");
@ -455,14 +472,22 @@ pub enum NodeInfoGetError {
/// The HTTP request failed.
#[error("the HTTP request failed")]
Request(reqwest::Error),
/// The `Content-Type` header of the response is missing.
#[error("the Content-Type header of the response is missing")]
ContentTypeMissing,
/// The `Content-Type` header of the response is invalid.
#[error("the Content-Type header of the response is invalid")]
ContentTypeInvalid,
/// The `Content-Type` header of the response can't be converted to a [`str`].
#[error("the Content-Type header of the response cannot be converted to a &str")]
ContentTypeUnprintable(reqwest::header::ToStrError),
/// The `Content-Type` header of the response is not a valid [`mime::Mime`] type.
#[error("the Content-Type header of the response is not a valid media type")]
ContentTypeInvalid(mediatype::MediaTypeError),
/// The `Content-Type` header of the response is not a supported [`mime::Mime`] type.
#[error("the Content-Type header of the response is not a supported media type")]
ContentTypeUnsupported,
/// The document failed to be parsed as JSON by [`reqwest`].
#[error("the document failed to be parsed as JSON")]
@ -472,12 +497,3 @@ pub enum NodeInfoGetError {
#[error("the returned NodeInfo version would not match the version of the called method")]
Version,
}
/// Extract the MIME type from the value of the `Content-Type` header.
fn extract_mime_from_content_type(value: &reqwest::header::HeaderValue) -> Option<String> {
let value = value.to_str().ok()?;
match value.split_once("; ") {
None => Some(value.to_string()),
Some((mime, _)) => Some(mime.to_string()),
}
}

View file

@ -1,10 +1,17 @@
[package]
name = "acrate-hostmeta"
version = "0.2.0"
name = "acrate_rd"
version = "0.3.0"
authors = ["Stefano Pigozzi <me@steffo.eu>"]
edition = "2021"
description = "Rust typing and utilities for the JSON and XML resource descriptior formats"
repository = "https://forge.steffo.eu/unimore/tirocinio-canali-steffo-acrate"
license = "EUPL-1.2"
keywords = ["jrd", "xrd", "host-meta", "webfinger", "resource-descriptor"]
categories = ["web-programming"]
[dependencies]
log = "0.4.22"
mediatype = { version = "0.19.18", features = ["serde"] }
quick-xml = { version = "0.37.0", features = ["overlapped-lists", "serialize"] }
reqwest = { version = "0.12.9", features = ["json", "stream"] }
serde = { version = "1.0.214", features = ["derive"] }

View file

@ -30,7 +30,7 @@ impl ResourceDescriptor {
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::any::ResourceDescriptor;
/// use acrate_rd::any::ResourceDescriptor;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/host-meta".parse()
@ -185,7 +185,7 @@ impl ResourceDescriptor {
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::any::ResourceDescriptor;
/// use acrate_rd::any::ResourceDescriptor;
///
/// let client = reqwest::Client::new();
/// let base: reqwest::Url = "https://junimo.party".parse()

View file

@ -1,14 +1,18 @@
//! Definition and implementation of [`ResourceDescriptorJRD`].
use std::collections::HashMap;
use mediatype::MediaTypeBuf;
use serde::{Serialize, Deserialize};
use thiserror::Error;
use crate::xrd::{ResourceDescriptorLinkXRD, ResourceDescriptorPropertyXRD, ResourceDescriptorTitleXRD, ResourceDescriptorXRD};
/// A resource descriptor object in JRD format.
/// A resource descriptor in JRD format.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4>
///
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceDescriptorJRD {
/// The resource this document refers to.
@ -17,6 +21,7 @@ pub struct ResourceDescriptorJRD {
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.1>
///
#[serde(skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
/// Other names the resource described by this document can be referred to.
@ -70,7 +75,8 @@ pub struct ResourceDescriptorLinkJRD {
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.2>
///
pub r#type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub r#type: Option<MediaTypeBuf>,
/// URI to the resource put in relation.
///
@ -78,6 +84,7 @@ pub struct ResourceDescriptorLinkJRD {
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.3>
///
#[serde(skip_serializing_if = "Option::is_none")]
pub href: Option<String>,
/// Titles of the resource put in relation in various languages.
@ -104,6 +111,7 @@ pub struct ResourceDescriptorLinkJRD {
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-4.2>
///
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
}
@ -119,7 +127,7 @@ impl ResourceDescriptorJRD {
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::jrd::ResourceDescriptorJRD;
/// use acrate_rd::jrd::ResourceDescriptorJRD;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/nodeinfo".parse()
@ -164,14 +172,24 @@ impl ResourceDescriptorJRD {
.get(reqwest::header::CONTENT_TYPE)
.ok_or(ContentTypeMissing)?;
log::trace!("Extracting MIME type from the `Content-Type` header...");
let mime_type = crate::utils::extract_mime_from_content_type(content_type)
.ok_or(ContentTypeInvalid)?;
log::trace!("Extracting media type from the `Content-Type` header: {content_type:?}");
let media_type: MediaTypeBuf = content_type
.to_str()
.map_err(ContentTypeUnprintable)?
.parse()
.map_err(ContentTypeInvalid)?;
log::trace!("Ensuring MIME type is acceptable for JRD parsing...");
if !(mime_type == "application/json" || mime_type == "application/jrd+json") {
log::error!("MIME type `{mime_type}` is not acceptable for JRD parsing.");
return Err(ContentTypeInvalid);
log::trace!("Checking if media type is supported: {media_type:?}");
let mime_is_json = media_type.essence().eq(&"application/json".parse::<MediaTypeBuf>().unwrap());
log::trace!("Is media type `application/json`? {mime_is_json:?}");
let mime_is_jrd = media_type.essence().eq(&"application/jrd+json".parse::<MediaTypeBuf>().unwrap());
log::trace!("Is media type `application/jrd+json`? {mime_is_jrd:?}");
if !(mime_is_json || mime_is_jrd) {
log::error!("Media type `{media_type}` is not acceptable for JRD parsing.");
return Err(ContentTypeUnsupported);
}
log::trace!("Attempting to parse response as JSON...");
@ -219,7 +237,7 @@ impl From<ResourceDescriptorLinkXRD> for ResourceDescriptorLinkJRD {
impl From<ResourceDescriptorPropertyXRD> for (String, Option<String>) {
fn from(value: ResourceDescriptorPropertyXRD) -> Self {
(value.r#type, value.value)
(value.rel, value.value)
}
}
@ -241,9 +259,17 @@ pub enum GetJRDError {
#[error("the Content-Type header of the response is missing")]
ContentTypeMissing,
/// The `Content-Type` header of the response is invalid.
#[error("the Content-Type header of the response is invalid")]
ContentTypeInvalid,
/// The `Content-Type` header of the response can't be converted to a [`str`].
#[error("the Content-Type header of the response cannot be converted to a &str")]
ContentTypeUnprintable(reqwest::header::ToStrError),
/// The `Content-Type` header of the response is not a valid [`mime::Mime`] type.
#[error("the Content-Type header of the response is not a valid media type")]
ContentTypeInvalid(mediatype::MediaTypeError),
/// The `Content-Type` header of the response is not a supported [`mime::Mime`] type.
#[error("the Content-Type header of the response is not a supported media type")]
ContentTypeUnsupported,
/// The document failed to be parsed as JSON by [`reqwest`].
#[error("the document failed to be parsed as JSON")]

View file

@ -1,4 +1,4 @@
//! Resource descriptior handler.
//! Rust typing and utilities for the JSON and XML resource descriptior formats.
//!
//! # Specification
//!
@ -8,5 +8,3 @@
pub mod jrd;
pub mod xrd;
pub mod any;
mod utils;

View file

@ -1,3 +1,6 @@
//! Definition and implementation of [`ResourceDescriptorXRD`].
use mediatype::MediaTypeBuf;
use serde::{Serialize, Deserialize};
use thiserror::Error;
use crate::jrd::{ResourceDescriptorJRD, ResourceDescriptorLinkJRD};
@ -9,6 +12,7 @@ use crate::jrd::{ResourceDescriptorJRD, ResourceDescriptorLinkJRD};
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4>
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "XRD")]
pub struct ResourceDescriptorXRD {
/// The resource this document refers to.
///
@ -17,6 +21,7 @@ pub struct ResourceDescriptorXRD {
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.1>
///
#[serde(rename = "Subject")]
#[serde(skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
/// Other names the resource described by this document can be referred to.
@ -58,6 +63,7 @@ pub struct ResourceDescriptorXRD {
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
///
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Link")]
pub struct ResourceDescriptorLinkXRD {
/// The kind of relation established by the subject with the attached resource.
///
@ -75,7 +81,8 @@ pub struct ResourceDescriptorLinkXRD {
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.2>
///
#[serde(rename = "@type")]
pub r#type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub r#type: Option<MediaTypeBuf>,
/// URI to the resource put in relation.
///
@ -84,6 +91,7 @@ pub struct ResourceDescriptorLinkXRD {
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.3>
///
#[serde(rename = "@href")]
#[serde(skip_serializing_if = "Option::is_none")]
pub href: Option<String>,
/// Titles of the resource put in relation in various languages.
@ -93,6 +101,7 @@ pub struct ResourceDescriptorLinkXRD {
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.4>
///
#[serde(default)]
#[serde(rename = "Title")]
pub titles: Vec<ResourceDescriptorTitleXRD>,
/// Additional information about the resource put in relation.
@ -102,6 +111,7 @@ pub struct ResourceDescriptorLinkXRD {
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.5>
///
#[serde(default)]
#[serde(rename = "Property")]
pub properties: Vec<ResourceDescriptorPropertyXRD>,
/// Template to fill to get the URL to resource-specific information.
@ -111,6 +121,7 @@ pub struct ResourceDescriptorLinkXRD {
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-4.2>
///
#[serde(rename = "@template")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
}
@ -120,22 +131,26 @@ pub struct ResourceDescriptorLinkXRD {
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.4>
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Title")]
pub struct ResourceDescriptorTitleXRD {
/// The language of the title.
#[serde(rename = "@lang")]
pub language: String,
/// The title itself.
#[serde(rename = "$text")]
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename = "Property")]
pub struct ResourceDescriptorPropertyXRD {
/// The property identifier, or type.
#[serde(alias = "@type")]
pub r#type: String,
#[serde(rename = "@rel")]
pub rel: String,
/// The property value.
#[serde(rename = "$text")]
pub value: Option<String>,
}
@ -151,7 +166,7 @@ impl ResourceDescriptorXRD {
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::xrd::ResourceDescriptorXRD;
/// use acrate_rd::xrd::ResourceDescriptorXRD;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/host-meta".parse()
@ -193,14 +208,21 @@ impl ResourceDescriptorXRD {
.get(reqwest::header::CONTENT_TYPE)
.ok_or(ContentTypeMissing)?;
log::trace!("Extracting MIME type from the `Content-Type` header...");
let mime_type = crate::utils::extract_mime_from_content_type(content_type)
.ok_or(ContentTypeInvalid)?;
log::trace!("Extracting media type from the `Content-Type` header: {content_type:?}");
let media_type: MediaTypeBuf = content_type
.to_str()
.map_err(ContentTypeUnprintable)?
.parse()
.map_err(ContentTypeInvalid)?;
log::trace!("Ensuring MIME type is acceptable for XRD parsing...");
if mime_type != "application/xrd+xml" {
log::error!("MIME type `{mime_type}` is not acceptable for XRD parsing.");
return Err(ContentTypeInvalid)
log::trace!("Checking if media type is supported: {media_type:?}");
let mime_is_xrd = media_type.essence().eq(&"application/xrd+xml".parse::<MediaTypeBuf>().unwrap());
log::trace!("Is media type `application/xrd+xml`? {mime_is_xrd:?}");
if !mime_is_xrd {
log::error!("MIME type `{media_type}` is not acceptable for XRD parsing.");
return Err(ContentTypeUnsupported);
}
log::trace!("Attempting to parse response as text...");
@ -234,7 +256,7 @@ impl From<ResourceDescriptorJRD> for ResourceDescriptorXRD {
impl From<(String, Option<String>)> for ResourceDescriptorPropertyXRD {
fn from(value: (String, Option<String>)) -> Self {
Self {
r#type: value.0,
rel: value.0,
value: value.1,
}
}
@ -278,9 +300,17 @@ pub enum GetXRDError {
#[error("the Content-Type header of the response is missing")]
ContentTypeMissing,
/// The `Content-Type` header of the response is invalid.
#[error("the Content-Type header of the response is invalid")]
ContentTypeInvalid,
/// The `Content-Type` header of the response can't be converted to a [`str`].
#[error("the Content-Type header of the response cannot be converted to a &str")]
ContentTypeUnprintable(reqwest::header::ToStrError),
/// The `Content-Type` header of the response is not a valid [`mime::Mime`] type.
#[error("the Content-Type header of the response is not a valid media type")]
ContentTypeInvalid(mediatype::MediaTypeError),
/// The `Content-Type` header of the response is not a supported [`mime::Mime`] type.
#[error("the Content-Type header of the response is not a supported media type")]
ContentTypeUnsupported,
/// The document failed to be decoded as text.
#[error("the document failed to be decoded as text")]

View file

@ -38,7 +38,7 @@ macro_rules! test_discover_hostmeta {
let base: reqwest::Url = $url.parse()
.expect("a valid URL");
let doc = acrate_hostmeta::any::ResourceDescriptor::discover_hostmeta(&client, base)
let doc = acrate_rd::any::ResourceDescriptor::discover_hostmeta(&client, base)
.await
.expect("host-meta discovery to succeed");
@ -61,7 +61,7 @@ macro_rules! test_de_ser_jrd {
log::info!("Starting document: {:#?}", JRD_DOCUMENT);
let de: acrate_hostmeta::jrd::ResourceDescriptorJRD = serde_json::from_str(JRD_DOCUMENT)
let de: acrate_rd::jrd::ResourceDescriptorJRD = serde_json::from_str(JRD_DOCUMENT)
.expect("document to be deserialized successfully");
log::info!("Serialized document: {de:#?}");
@ -85,11 +85,10 @@ macro_rules! test_de_ser_xrd {
$(#[$tag])*
fn $id() {
init_log();
let client = make_client();
log::info!("Starting document: {:#?}", XRD_DOCUMENT);
let de: acrate_hostmeta::xrd::ResourceDescriptorXRD = quick_xml::de::from_str(XRD_DOCUMENT)
let de: acrate_rd::xrd::ResourceDescriptorXRD = quick_xml::de::from_str(XRD_DOCUMENT)
.expect("document to be deserialized successfully");
log::info!("Serialized document: {de:#?}");
@ -113,4 +112,5 @@ test_discover_hostmeta!(test_discover_hostmeta_threads_net, "https://threads.net
test_discover_hostmeta!(test_discover_hostmeta_ngoa_giao_loan, "https://ngoa.giao.loan", ignore = "does not support host-meta");
test_discover_hostmeta!(test_discover_hostmeta_hollo_social, "https://hollo.social", ignore = "does not support host-meta");
test_de_ser_jrd!(test_de_ser_sample_junimo_party, "samples/junimo_party.nodeinfo.jrd.json");
test_de_ser_jrd!(test_de_ser_jrd_sample_junimo_party, "samples/junimo_party.nodeinfo.jrd.json");
test_de_ser_xrd!(test_de_ser_xrd_sample_junimo_party, "samples/junimo_party.host-meta.xrd.xml");

View file

@ -0,0 +1,29 @@
[package]
name = "acrate_rdserver"
version = "0.3.0"
authors = ["Stefano Pigozzi <me@steffo.eu>"]
edition = "2021"
description = "Resource descriptor web server for the acrate project"
repository = "https://forge.steffo.eu/unimore/tirocinio-canali-steffo-acrate"
license = "EUPL-1.2"
keywords = ["jrd", "xrd", "hostmeta", "webfinger", "resource-descriptor"]
categories = ["web-programming"]
[dependencies]
acrate_database = { path = "../acrate_database" }
acrate_rd = { path = "../acrate_rd" }
anyhow = "1.0.93"
axum = { version = "0.7.7", features = ["macros"] }
axum-extra = { version = "0.9.4", features = ["query"] }
log = "0.4.22"
micronfig = "0.3.0"
minijinja = "2.5.0"
pretty_env_logger = "0.5.0"
quick-xml = { version = "0.37.0", features = ["serialize"] }
serde = { version = "1.0.215", features = ["derive"] }
serde_json = "1.0.132"
tokio = { version = "1.41.1", features = ["macros", "net", "rt-multi-thread"] }
mediatype = { version = "0.19.18", features = ["serde"] }
[lints.clippy]
tabs-in-doc-comments = "allow"

View file

@ -0,0 +1,4 @@
micronfig::config!(
ACRATE_WEBFINGER_DATABASE_URL: String,
ACRATE_WEBFINGER_BIND_ADDRESS: String,
);

View file

@ -1,4 +1,6 @@
use std::sync::Arc;
use anyhow::Context;
use axum::Extension;
mod config;
mod route;
@ -8,14 +10,22 @@ mod route;
async fn main() -> anyhow::Result<std::convert::Infallible> {
pretty_env_logger::init();
log::debug!("Logging initialized!");
log::trace!("Creating Minijinja environment...");
let mut mj = minijinja::Environment::<'static>::new();
log::trace!("Adding webfinger page to the Minijinja environment...");
mj.add_template("rd.html.j2", include_str!("rd.html.j2"))
.expect("rd.html.j2 to be a valid Minijinja template");
log::trace!("Creating Axum router...");
let app = axum::Router::new()
.route("/inbox", axum::routing::post(route::inbox_handler));
.route("/*path", axum::routing::get(route::webfinger_handler))
.layer(Extension(Arc::new(mj)));
log::trace!("Axum router created successfully!");
log::trace!("Creating Tokio listener...");
let bind_address = config::ACRATE_INBOX_BIND_ADDRESS();
let bind_address = config::ACRATE_WEBFINGER_BIND_ADDRESS();
let listener = tokio::net::TcpListener::bind(bind_address)
.await
.context("failed to bind listener to address")?;

View file

@ -0,0 +1,192 @@
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>{{ subject }} · Acrate RDServer</title>
<style>
:root {
--wf-yellow: #e2bb03;
--wf-brown: #3b351d;
--link-color: #0094b9;
}
body {
font-family: sans-serif;
}
h1, h2 {
text-align: center;
}
main {
max-width: 800px;
padding: 8px;
margin: 0 auto;
border: 2px solid currentColor;
border-radius: 8px;
}
a {
color: var(--link-color);
}
hr {
margin: 8px -8px;
border: 1px solid currentColor;
opacity: 1;
}
small span {
font-family: monospace;
}
@media screen {
main {
box-shadow: 4px 4px 10px currentColor;
}
}
@media screen and (prefers-color-scheme: dark) {
body {
background-color: black;
color: var(--wf-yellow);
}
main {
background-color: var(--wf-brown);
}
main, hr {
border-color: var(--wf-yellow);
}
}
@media screen and (prefers-color-scheme: light) {
body {
background-color: var(--wf-yellow);
color: var(--wf-brown);
}
main {
background-color: white;
}
main, hr {
border-color: var(--wf-brown);
}
}
</style>
</head>
<body>
<header>
<h1>
<span id="path">{{ path }}</span>
</h1>
</header>
<main>
<h2 id="section-subject">
<span id="subject">{{ subject }}</span>
</h2>
{% if aliases %}
<hr>
<section id="section-aliases">
<h3>
Aliases
</h3>
<ul>
{% for alias in aliases %}
<li><a href="{{ alias }}">{{ alias }}</a></li>
{% endfor %}
</ul>
</section>
{% endif %}
{% if properties %}
<hr>
<section id="section-properties">
<h3>
Properties
</h3>
<dl>
{% for property in properties %}
<dt>
<a href="{{ property[0] }}">{{ property[0] }}</a>
</dt>
<dd>
<span>{{ property[1] }}</span>
</dd>
{% endfor %}
</dl>
</section>
{% endif %}
{% if links %}
<hr>
<section id="section-links">
<h3>
Links
</h3>
<dl>
{% for link in links %}
<dt>
<h4>
{% if link[0] != "self" %}
<a href="{{ link[0] }}">{{ link[0] }}</a>
{% else %}
<span>{{ link[0] }}</span>
{% endif %}
{% if link[1] is not none %}
<small>
(<span>{{ link[1] }}</span>)
</small>
{% endif %}
</h4>
</dt>
<dd>
{% if link[2] is not none %}
<h5>
Link destination
</h5>
<a href="{{ link[2] }}">{{ link[2] }}</a>
{% endif %}
{% if link[3] is not none %}
<h5>
Link template
</h5>
<span>{{ link[3] }}</span>
{% endif %}
{% if link[4] %}
<h5>
Link properties
</h5>
<dl>
{% for property in link[4] %}
<dt>
<a href="{{ property[0] }}">{{ property[0] }}</a>
</dt>
<dd>
<span>{{ property[1] }}</span>
</dd>
{% endfor %}
</dl>
{% endif %}
{% if link[5] %}
<h5>
Link titles
</h5>
<dl>
{% for title in link[5] %}
<dt>
<span>{{ title[0] }}</span>
</dt>
<dd>
<span>{{ title[1] }}</span>
</dd>
{% endfor %}
</dl>
{% endif %}
</dd>
{% endfor %}
</dl>
</section>
{% endif %}
</main>
</body>

View file

@ -0,0 +1,298 @@
use std::iter::IntoIterator;
use std::sync::Arc;
use axum::Extension;
use axum::extract::Path;
use axum::http::{HeaderMap, Response, StatusCode};
use axum_extra::extract::Query;
use mediatype::{MediaTypeBuf, MediaTypeList};
use serde::Deserialize;
use acrate_database::diesel::GroupedBy;
use acrate_database::diesel_async::{AsyncConnection, AsyncPgConnection};
use acrate_database::meta::{MetaAlias, MetaLink, MetaLinkProperty, MetaLinkTitle, MetaProperty, MetaSubject};
use acrate_rd::jrd::ResourceDescriptorLinkJRD;
use acrate_rd::xrd::{ResourceDescriptorLinkXRD, ResourceDescriptorPropertyXRD, ResourceDescriptorTitleXRD};
use crate::config;
#[derive(Debug, Clone, Deserialize)]
pub struct WebfingerQuery {
pub resource: Option<String>,
#[serde(default)]
pub rel: Vec<String>,
}
pub async fn webfinger_handler(
Path(path): Path<String>,
Query(WebfingerQuery {resource, rel}): Query<WebfingerQuery>,
headers: HeaderMap,
Extension(mj): Extension<Arc<minijinja::Environment<'static>>>,
) -> Result<Response<String>, StatusCode> {
log::info!("Handling a WebFinger request!");
let resource = resource.unwrap_or_else(|| "".to_string());
log::debug!("Resource is: {resource:#?}");
let path = format!("/{path}");
log::debug!("Path is: {path:#?}");
log::debug!("Rel is: {rel:#?}");
let accept = headers.get("Accept");
log::debug!("Accept is: {accept:#?}");
let accept = accept
.map(|h| h.to_str())
.unwrap_or(Ok("*/*"))
.map(|h| MediaTypeList::new(h))
.map_err(|_| StatusCode::BAD_REQUEST)?;
let mut response = Response::new("".to_string());
let mut conn = AsyncPgConnection::establish(config::ACRATE_WEBFINGER_DATABASE_URL())
.await
.map_err(|_| StatusCode::BAD_GATEWAY)?;
let subjects = MetaSubject::aquery_matching(&mut conn, &path, &resource)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let subject = subjects.first()
.ok_or(StatusCode::NOT_FOUND)?;
if subject.redirect.is_some() {
{
let headers = response.headers_mut();
headers.insert(
"Location",
subject.redirect
.as_ref()
.expect("redirect not to have become suddenly None")
.parse()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
);
}
{
let status = response.status_mut();
*status = StatusCode::FOUND;
}
return Ok(response);
}
let subject = subject.subject.clone();
let aliases = MetaAlias::aquery_matching(&mut conn, &path, &resource)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let properties = MetaProperty::aquery_matching(&mut conn, &path, &resource)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let links = MetaLink::aquery_matching(&mut conn, &path, &resource)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let link_properties = MetaLinkProperty::aquery_by_link(&mut conn, &links)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.grouped_by(&links);
let link_titles = MetaLinkTitle::aquery_by_link(&mut conn, &links)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.grouped_by(&links);
let links_full: Vec<(MetaLink, Vec<MetaLinkProperty>, Vec<MetaLinkTitle>)> = links
.into_iter()
.zip(link_properties)
.zip(link_titles)
.map(|((link, properties), titles)| (link, properties, titles))
.collect();
{
let headers = response.headers_mut();
headers.insert(
"Access-Control-Allow-Origin",
"*".parse().unwrap()
);
}
for media_type in accept.into_iter() {
let media_type = match media_type {
Err(e) => {
log::debug!("Skipping error while parsing media type: {e:?}");
continue;
},
Ok(media_type) => media_type
};
{
let headers = response.headers_mut();
headers.insert(
"Content-Type",
media_type.to_string()
.parse()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
);
}
match media_type.essence().to_string().to_ascii_lowercase().as_str() {
"*/*" | "application/json" | "application/jrd+json" => {
let aliases = aliases
.into_iter()
.map(|alias| alias.alias)
.collect();
let properties = properties
.into_iter()
.map(|prop| (prop.rel, prop.value))
.collect();
let links = links_full
.into_iter()
.map(|(link, properties, titles)| ResourceDescriptorLinkJRD {
rel: link.rel,
r#type: link.type_.map(|m| m.0),
href: link.href,
template: link.template,
properties: properties
.into_iter()
.map(|property| (property.rel, property.value))
.collect(),
titles: titles
.into_iter()
.map(|title| (title.language, title.value))
.collect(),
})
.collect::<Vec<ResourceDescriptorLinkJRD>>();
let rd = acrate_rd::jrd::ResourceDescriptorJRD {
subject,
aliases,
properties,
links,
};
let json = serde_json::to_string_pretty(&rd)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
{
let body = response.body_mut();
body.push_str(&json);
}
return Ok(response);
},
"application/xml" | "application/xrd+xml" => {
let aliases = aliases
.into_iter()
.map(|alias| alias.alias)
.collect();
let properties: Vec<ResourceDescriptorPropertyXRD> = properties
.into_iter()
.map(|prop| ResourceDescriptorPropertyXRD {
rel: prop.rel,
value: prop.value,
})
.collect();
let links = links_full
.into_iter()
.map(|(link, properties, titles)| ResourceDescriptorLinkXRD {
rel: link.rel,
r#type: link.type_.map(|m| m.0),
href: link.href,
template: link.template,
properties: properties
.into_iter()
.map(|property| ResourceDescriptorPropertyXRD {
rel: property.rel,
value: property.value,
})
.collect(),
titles: titles
.into_iter()
.map(|title| ResourceDescriptorTitleXRD {
language: title.language,
value: title.value,
})
.collect(),
})
.collect::<Vec<ResourceDescriptorLinkXRD>>();
let rd = acrate_rd::xrd::ResourceDescriptorXRD {
subject,
aliases,
properties,
links,
};
let xml = quick_xml::se::to_string(&rd)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
{
let body = response.body_mut();
body.push_str(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
body.push_str(&xml);
}
return Ok(response);
},
"text/html" => {
let aliases: Vec<String> = aliases.into_iter()
.map(|alias| alias.alias)
.collect();
let properties: Vec<(String, Option<String>)> = properties.into_iter()
.map(|prop| {
(prop.rel, prop.value)
})
.collect();
let links: Vec<(String, Option<MediaTypeBuf>, Option<String>, Option<String>, Vec<(String, Option<String>)>, Vec<(String, String)>)> = links_full
.into_iter()
.map(|(link, properties, titles)| {
(
link.rel,
link.type_.map(|m| m.0),
link.href,
link.template,
properties.into_iter()
.map(|prop| (prop.rel, prop.value))
.collect::<Vec<(String, Option<String>)>>(),
titles.into_iter()
.map(|title| (title.language, title.value))
.collect::<Vec<(String, String)>>()
)
})
.collect();
let html = mj.get_template("rd.html.j2")
.expect("rd.html.j2 to exist")
.render(
minijinja::context!(
path => path,
subject => subject,
aliases => aliases,
properties => properties,
links => links,
)
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
{
let body = response.body_mut();
body.push_str(&html);
}
return Ok(response);
},
_ => {
continue;
},
}
}
Err(StatusCode::NOT_ACCEPTABLE)
}