mirror of
https://github.com/stalwartlabs/stalwart.git
synced 2026-11-26 23:29:52 +00:00
v1.0.1
This commit is contained in:
parent
47df4c0bae
commit
23b69755cb
130 changed files with 6643 additions and 1359 deletions
|
|
@ -1,7 +1,9 @@
|
|||
[env]
|
||||
RUST_MIN_STACK = "8388608"
|
||||
CXXFLAGS_aarch64_unknown_linux_gnu = "-march=armv8-a+crc+crypto -DROCKSDB_AUXV_GETAUXVAL_PRESENT"
|
||||
CXXFLAGS_aarch64_unknown_linux_musl = "-march=armv8-a+crc+crypto -DROCKSDB_AUXV_GETAUXVAL_PRESENT"
|
||||
CFLAGS_aarch64_unknown_linux_gnu = "-moutline-atomics"
|
||||
CFLAGS_aarch64_unknown_linux_musl = "-moutline-atomics"
|
||||
CXXFLAGS_aarch64_unknown_linux_gnu = "-march=armv8-a+crc+crypto -moutline-atomics -DROCKSDB_AUXV_GETAUXVAL_PRESENT"
|
||||
CXXFLAGS_aarch64_unknown_linux_musl = "-march=armv8-a+crc+crypto -moutline-atomics -DROCKSDB_AUXV_GETAUXVAL_PRESENT"
|
||||
|
||||
[target.'cfg(all(target_arch = "x86_64", not(target_env = "musl")))']
|
||||
rustflags = ["-C", "target-cpu=x86-64-v2"]
|
||||
|
|
|
|||
35
CHANGELOG.md
35
CHANGELOG.md
|
|
@ -2,6 +2,41 @@
|
|||
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [1.0.1] - 2026-10-28
|
||||
|
||||
## Added
|
||||
- Telemetry
|
||||
- New OpenTelemetry (OTLP over HTTP and gRPC) and Prometheus exporters replace the `opentelemetry` and `prometheus` crates, with 4x to 14x faster encoding.
|
||||
- Metric names follow the OpenTelemetry and Prometheus conventions (`stalwart.*` in OTLP, `stalwart_*` with unit and `_total` suffixes in Prometheus); dashboards and alerts must be updated.
|
||||
- OpenMetrics output, plus `serviceName`, `serviceNamespace` and `resourceAttributes` settings replacing the `OTEL_*` environment variables.
|
||||
- gRPC exporters support TLS options, authentication and custom headers; histogram buckets and counters are fixed (cumulative, inclusive, 64-bit).
|
||||
|
||||
## Changed
|
||||
- Encryption at rest: JMAP messages stored with the `$draft` keyword are no longer encrypted on append, so they are submitted as written by the client. The Sent copy of messages submitted over JMAP is stored unencrypted.
|
||||
- OAuth: The consent screen is shown after sign-in and is skipped while the client is listed under the account's connected applications with the requested scopes. `prompt=consent` always shows it. All cluster nodes must be upgraded before relying on the new sign-in flow.
|
||||
- Registry: Listing connected applications, public keys, masked addresses and archived items returns only the requested account's objects, also for administrators. Administrators reach other accounts through the account id or an explicit `accountId` filter.
|
||||
|
||||
## Fixed
|
||||
- ACME: DNS-01 challenges for a subdomain are written to the registrable domain's zone instead of the domain's own zone when no zone origin is configured.
|
||||
- iTIP
|
||||
- Invitation emails for all-day events show the start as `00:00` with a time zone instead of the date only.
|
||||
- Attendee replies are rejected when the client drops or changes the organizer's `PRIORITY`, for example when accepting an invitation from BusyCal.
|
||||
- JMAP
|
||||
- `Mailbox/set` returns only the id of created mailboxes instead of also the server-set and defaulted properties (RFC 8620, section 5.3).
|
||||
- `AddressBook/set`, `ContactCard/set` and `Identity/set` return only the id of created objects, and `Calendar/set` and `CalendarEvent/set` omit some defaulted properties (RFC 8620, section 5.3).
|
||||
- Registry
|
||||
- `config.json` is created with the process umask (usually `0644`), so the data store credentials are readable by other local users.
|
||||
- Listing archived items with an `accountId` filter fails with `unsupportedFilter` for users without the `impersonate` permission instead of ignoring the filter like the other account-owned objects.
|
||||
- RocksDB:
|
||||
- Updated to 11.8.1 with the upstream fix for spurious compare-and-swap failures in the write group leader ([facebook/rocksdb#15415](https://github.com/facebook/rocksdb/pull/15415)).
|
||||
- `aarch64` release builds crash with `SIGSEGV` under concurrent writes (C and C++ dependencies are now compiled with outline atomics).
|
||||
- Spam filter: `FORGED_RCVD_TRAIL` is added for every `Received` header whose reverse DNS name ends with a dot, such as those written by Gmail.
|
||||
- WebUI
|
||||
- Saving objects that use schema defaults fails with "Invalid value for object property", for example when enabling the AI classifier.
|
||||
- Object pickers on tenant-scoped objects (for example the ACME provider of a tenant domain) list objects from other tenants, and saving one fails with a generic "references another item that does not exist" error instead of saying the object belongs to another tenant.
|
||||
- Multi-tenancy: Tenant administrators given the `impersonate` permission can reach accounts of other tenants. The permission is now never granted to tenant members and cannot be added to a tenant's permissions.
|
||||
- Installer: The systemd unit written by `install.sh` uses `Type=simple` instead of `Type=notify`.
|
||||
|
||||
## [1.0.0] - 2026-10-26
|
||||
|
||||
This version includes **multiple breaking changes** and a new database layout, so existing v0.16.x deployments cannot be upgraded in place. Please read the [migration documentation](https://stalw.art/docs/migration/upgrade-0-16/) for more information on how to migrate from v0.16.x.
|
||||
|
|
|
|||
341
Cargo.lock
generated
341
Cargo.lock
generated
|
|
@ -827,7 +827,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "calcard"
|
||||
version = "0.4.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"encodify",
|
||||
|
|
@ -1077,7 +1077,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "common"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"aes-gcm-siv",
|
||||
"ahash",
|
||||
|
|
@ -1114,10 +1114,6 @@ dependencies = [
|
|||
"memchr",
|
||||
"nlp",
|
||||
"nohash-hasher",
|
||||
"opentelemetry",
|
||||
"opentelemetry-otlp",
|
||||
"opentelemetry-semantic-conventions",
|
||||
"opentelemetry_sdk",
|
||||
"p256 0.14.0",
|
||||
"p384 0.14.0",
|
||||
"parking_lot 0.13.0",
|
||||
|
|
@ -1125,7 +1121,6 @@ dependencies = [
|
|||
"percent-encoding",
|
||||
"pkcs8 0.11.0",
|
||||
"privdrop",
|
||||
"prometheus",
|
||||
"proxy-header",
|
||||
"psl",
|
||||
"quick-xml 0.42.0",
|
||||
|
|
@ -1154,6 +1149,7 @@ dependencies = [
|
|||
"smtp-report",
|
||||
"socket2 0.6.5",
|
||||
"store",
|
||||
"telemetry",
|
||||
"tinyvec",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
|
|
@ -1262,7 +1258,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "coordinator"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"async-nats",
|
||||
"deadpool",
|
||||
|
|
@ -1672,7 +1668,7 @@ checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
|
|||
|
||||
[[package]]
|
||||
name = "dav"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"calcard",
|
||||
"common",
|
||||
|
|
@ -1696,7 +1692,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "dav-proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"calcard",
|
||||
"compact_str",
|
||||
|
|
@ -1920,7 +1916,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "directory"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"argon2 0.6.0",
|
||||
|
|
@ -2162,7 +2158,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "email"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"aes 0.9.3",
|
||||
"aes-gcm 0.11.1",
|
||||
|
|
@ -2281,7 +2277,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "event_macro"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
|
|
@ -2787,7 +2783,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "groupware"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"calcard",
|
||||
|
|
@ -3074,7 +3070,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"common",
|
||||
|
|
@ -3092,6 +3088,7 @@ dependencies = [
|
|||
"hyper",
|
||||
"hyper-util",
|
||||
"jmap",
|
||||
"jmap-tools",
|
||||
"jmap_proto",
|
||||
"mail-auth",
|
||||
"mail-builder",
|
||||
|
|
@ -3107,6 +3104,7 @@ dependencies = [
|
|||
"sha2 0.11.1",
|
||||
"smtp",
|
||||
"store",
|
||||
"telemetry",
|
||||
"tokio",
|
||||
"trc",
|
||||
"types",
|
||||
|
|
@ -3148,7 +3146,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "http_proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"common",
|
||||
"compact_str",
|
||||
|
|
@ -3238,19 +3236,6 @@ dependencies = [
|
|||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-timeout"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"
|
||||
dependencies = [
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.21"
|
||||
|
|
@ -3605,7 +3590,7 @@ checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a"
|
|||
|
||||
[[package]]
|
||||
name = "imap"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"common",
|
||||
|
|
@ -3629,7 +3614,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "imap_proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"compact_str",
|
||||
|
|
@ -3888,7 +3873,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "jmap"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"calcard",
|
||||
|
|
@ -3937,7 +3922,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "jmap-tools"
|
||||
version = "0.1.9"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"rkyv",
|
||||
"serde",
|
||||
|
|
@ -3946,7 +3931,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "jmap_proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"calcard",
|
||||
|
|
@ -4264,9 +4249,8 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "librocksdb-sys"
|
||||
version = "0.17.3+10.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cef2a00ee60fe526157c9023edab23943fae1ce2ab6f4abb2a807c1746835de9"
|
||||
version = "0.19.0+11.8.1"
|
||||
source = "git+https://github.com/stalwartlabs/rust-rocksdb?branch=stalwart%2F0.25#f6169ca36d74c15637f8c6396c34e82aa73d0d47"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"bzip2-sys",
|
||||
|
|
@ -4274,6 +4258,7 @@ dependencies = [
|
|||
"libc",
|
||||
"libz-sys",
|
||||
"lz4-sys",
|
||||
"rustflags",
|
||||
"zstd-sys",
|
||||
]
|
||||
|
||||
|
|
@ -4454,7 +4439,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "managesieve"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"common",
|
||||
"compact_str",
|
||||
|
|
@ -4805,7 +4790,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "nlp"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"hashify",
|
||||
|
|
@ -5045,82 +5030,6 @@ dependencies = [
|
|||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "opentelemetry"
|
||||
version = "0.33.0"
|
||||
source = "git+https://github.com/stalwartlabs/opentelemetry-rust#ae66e97b140f70e477ab710686aafce665cc2f8b"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"js-sys",
|
||||
"pin-project-lite",
|
||||
"thiserror",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "opentelemetry-http"
|
||||
version = "0.33.0"
|
||||
source = "git+https://github.com/stalwartlabs/opentelemetry-rust#ae66e97b140f70e477ab710686aafce665cc2f8b"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"http 1.5.0",
|
||||
"opentelemetry",
|
||||
"reqwest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "opentelemetry-otlp"
|
||||
version = "0.33.0"
|
||||
source = "git+https://github.com/stalwartlabs/opentelemetry-rust#ae66e97b140f70e477ab710686aafce665cc2f8b"
|
||||
dependencies = [
|
||||
"http 1.5.0",
|
||||
"httpdate",
|
||||
"opentelemetry",
|
||||
"opentelemetry-http",
|
||||
"opentelemetry-proto",
|
||||
"opentelemetry_sdk",
|
||||
"prost",
|
||||
"reqwest",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tonic",
|
||||
"tonic-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "opentelemetry-proto"
|
||||
version = "0.33.0"
|
||||
source = "git+https://github.com/stalwartlabs/opentelemetry-rust#ae66e97b140f70e477ab710686aafce665cc2f8b"
|
||||
dependencies = [
|
||||
"opentelemetry",
|
||||
"opentelemetry_sdk",
|
||||
"prost",
|
||||
"tonic",
|
||||
"tonic-prost",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "opentelemetry-semantic-conventions"
|
||||
version = "0.33.0"
|
||||
source = "git+https://github.com/stalwartlabs/opentelemetry-rust#ae66e97b140f70e477ab710686aafce665cc2f8b"
|
||||
|
||||
[[package]]
|
||||
name = "opentelemetry_sdk"
|
||||
version = "0.33.0"
|
||||
source = "git+https://github.com/stalwartlabs/opentelemetry-rust#ae66e97b140f70e477ab710686aafce665cc2f8b"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"futures-executor",
|
||||
"futures-util",
|
||||
"opentelemetry",
|
||||
"percent-encoding",
|
||||
"portable-atomic",
|
||||
"rand 0.9.5",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "option-ext"
|
||||
version = "0.2.0"
|
||||
|
|
@ -5585,7 +5494,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "pop3"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"common",
|
||||
"compact_str",
|
||||
|
|
@ -5808,52 +5717,6 @@ dependencies = [
|
|||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prometheus"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ca5326d8d0b950a9acd87e6a3f94745394f62e4dae1b1ee22b2bc0c394af43a"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"fnv",
|
||||
"lazy_static",
|
||||
"memchr",
|
||||
"parking_lot 0.12.5",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost"
|
||||
version = "0.14.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-derive"
|
||||
version = "0.14.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-types"
|
||||
version = "0.14.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
|
||||
dependencies = [
|
||||
"prost",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proxy-header"
|
||||
version = "0.1.3"
|
||||
|
|
@ -6074,20 +5937,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha 0.3.1",
|
||||
"rand_chacha",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha 0.9.0",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.3"
|
||||
|
|
@ -6109,16 +5962,6 @@ dependencies = [
|
|||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
|
|
@ -6128,15 +5971,6 @@ dependencies = [
|
|||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.10.1"
|
||||
|
|
@ -6396,7 +6230,7 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
|||
|
||||
[[package]]
|
||||
name = "registry"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"compact_str",
|
||||
|
|
@ -6570,9 +6404,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "rocksdb"
|
||||
version = "0.24.0"
|
||||
version = "0.25.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddb7af00d2b17dbd07d82c0063e25411959748ff03e8d4f96134c2ff41fce34f"
|
||||
checksum = "d8d90add70d1d420ee487bce4a1449880a8d147451c6051b2ee5f8354553dcbf"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"librocksdb-sys",
|
||||
|
|
@ -6668,6 +6502,12 @@ dependencies = [
|
|||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustflags"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a39e0e9135d7a7208ee80aa4e3e4b88f0f5ad7be92153ed70686c38a03db2e63"
|
||||
|
||||
[[package]]
|
||||
name = "rusticata-macros"
|
||||
version = "4.1.0"
|
||||
|
|
@ -6790,7 +6630,7 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
|||
|
||||
[[package]]
|
||||
name = "s3"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"bytes",
|
||||
|
|
@ -6889,7 +6729,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "scim"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"common",
|
||||
"compact_str",
|
||||
|
|
@ -6913,7 +6753,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "scim-proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"hashify",
|
||||
"serde",
|
||||
|
|
@ -7244,7 +7084,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "services"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"aes-gcm 0.11.1",
|
||||
"aho-corasick",
|
||||
|
|
@ -7436,7 +7276,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
|||
|
||||
[[package]]
|
||||
name = "sieve-rs"
|
||||
version = "2.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bumpalo",
|
||||
|
|
@ -7574,7 +7414,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "smtp"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"blake3",
|
||||
|
|
@ -7614,7 +7454,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "smtp-proto"
|
||||
version = "0.2.5"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"rkyv",
|
||||
|
|
@ -7623,7 +7463,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "smtp-report"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hashify",
|
||||
|
|
@ -7720,7 +7560,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "spam-filter"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"common",
|
||||
"compact_str",
|
||||
|
|
@ -7857,7 +7697,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "stalwart"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"common",
|
||||
"coordinator",
|
||||
|
|
@ -7865,7 +7705,7 @@ dependencies = [
|
|||
"directory",
|
||||
"email",
|
||||
"groupware",
|
||||
"http 1.0.0",
|
||||
"http 1.0.1",
|
||||
"http_proto",
|
||||
"imap",
|
||||
"jmap",
|
||||
|
|
@ -7895,7 +7735,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
|||
|
||||
[[package]]
|
||||
name = "store"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"arc-swap",
|
||||
|
|
@ -8074,6 +7914,29 @@ version = "1.0.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
|
||||
|
||||
[[package]]
|
||||
name = "telemetry"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytes",
|
||||
"encodify",
|
||||
"hashify",
|
||||
"http 1.5.0",
|
||||
"http-body-util",
|
||||
"httpdate",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"itoa",
|
||||
"memchr",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"trc",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
|
|
@ -8107,7 +7970,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "text-extract"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"encoding_rs",
|
||||
|
|
@ -8393,56 +8256,6 @@ dependencies = [
|
|||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"http 1.5.0",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-timeout",
|
||||
"hyper-util",
|
||||
"percent-encoding",
|
||||
"pin-project",
|
||||
"rustls-native-certs",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-stream",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-prost"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
"tonic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-types"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8"
|
||||
dependencies = [
|
||||
"prost",
|
||||
"prost-types",
|
||||
"tonic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "totp-rs"
|
||||
version = "6.0.0"
|
||||
|
|
@ -8469,15 +8282,11 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
|||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"indexmap 2.14.2",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -8592,7 +8401,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "trc"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"compact_str",
|
||||
|
|
@ -8684,7 +8493,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
|||
|
||||
[[package]]
|
||||
name = "types"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"compact_str",
|
||||
|
|
@ -8901,7 +8710,7 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
|||
|
||||
[[package]]
|
||||
name = "utils"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"arcstr",
|
||||
|
|
@ -9644,7 +9453,7 @@ dependencies = [
|
|||
"aes 0.8.4",
|
||||
"hmac 0.12.1",
|
||||
"rand 0.8.8",
|
||||
"rand_chacha 0.3.1",
|
||||
"rand_chacha",
|
||||
"sha3 0.10.9",
|
||||
"zenoh-result",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ members = [
|
|||
"crates/utils",
|
||||
"crates/common",
|
||||
"crates/trc",
|
||||
"crates/telemetry",
|
||||
"crates/text-extract",
|
||||
"crates/smtp-proto",
|
||||
"crates/smtp-report",
|
||||
|
|
@ -64,6 +65,7 @@ default-members = [
|
|||
"crates/utils",
|
||||
"crates/common",
|
||||
"crates/trc",
|
||||
"crates/telemetry",
|
||||
"crates/text-extract",
|
||||
"crates/smtp-proto",
|
||||
"crates/smtp-report",
|
||||
|
|
@ -134,3 +136,4 @@ rpath = false
|
|||
hickory-proto = { git = "https://github.com/stalwartlabs/hickory-dns", branch = "stalwart/0.26" }
|
||||
hickory-net = { git = "https://github.com/stalwartlabs/hickory-dns", branch = "stalwart/0.26" }
|
||||
hickory-resolver = { git = "https://github.com/stalwartlabs/hickory-dns", branch = "stalwart/0.26" }
|
||||
librocksdb-sys = { git = "https://github.com/stalwartlabs/rust-rocksdb", branch = "stalwart/0.25" }
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "calcard"
|
||||
description = "iCalendar/JSCalendar and vCard/JSContact parsing, building and conversion library"
|
||||
version = "0.4.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@ use crate::{
|
|||
},
|
||||
},
|
||||
jscontact::{
|
||||
JSContact, JSContactId, JSContactKind, JSContactProperty, JSContactType, JSContactValue,
|
||||
JSCONTACT_VERSION, JSContact, JSContactId, JSContactKind, JSContactProperty, JSContactType,
|
||||
JSContactValue,
|
||||
import::{
|
||||
CardProperties, EntryState, ExtractedParams, Localization, Member, PropIdKey, PropIds,
|
||||
State, VCardConvertedProperty, VCardParams,
|
||||
|
|
@ -51,7 +52,10 @@ where
|
|||
JSContactProperty::Type,
|
||||
Value::Element(JSContactValue::Type(JSContactType::Card)),
|
||||
);
|
||||
entries.insert(JSContactProperty::Version, Value::Str("1.0".into()));
|
||||
entries.insert(
|
||||
JSContactProperty::Version,
|
||||
Value::Str(JSCONTACT_VERSION.into()),
|
||||
);
|
||||
|
||||
let mut default_language = None;
|
||||
let mut language_counts: OrderedMap<LanguageTag<'_>, usize> = OrderedMap::default();
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ use std::{
|
|||
str::FromStr,
|
||||
};
|
||||
|
||||
pub const JSCONTACT_VERSION: &str = "1.0";
|
||||
|
||||
pub mod export;
|
||||
pub mod import;
|
||||
pub mod parser;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "common"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
build = "build.rs"
|
||||
|
||||
|
|
@ -9,6 +9,7 @@ utils = { path = "../utils" }
|
|||
nlp = { path = "../nlp" }
|
||||
store = { path = "../store" }
|
||||
trc = { path = "../trc" }
|
||||
telemetry = { path = "../telemetry" }
|
||||
directory = { path = "../directory" }
|
||||
coordinator = { path = "../coordinator" }
|
||||
types = { path = "../types" }
|
||||
|
|
@ -43,11 +44,6 @@ x509-parser = "0.18"
|
|||
pem = "4.0"
|
||||
jiff = "0.2.38"
|
||||
hyper = { version = "1.12.0", features = ["server", "http1", "http2"] }
|
||||
opentelemetry = { git = "https://github.com/stalwartlabs/opentelemetry-rust" }
|
||||
opentelemetry_sdk = { git = "https://github.com/stalwartlabs/opentelemetry-rust" }
|
||||
opentelemetry-otlp = { git = "https://github.com/stalwartlabs/opentelemetry-rust", default-features = false, features = ["reqwest-client", "http-proto", "trace", "metrics", "logs", "internal-logs", "grpc-tonic", "tls-aws-lc", "tls-roots", "reqwest-rustls"] }
|
||||
opentelemetry-semantic-conventions = { git = "https://github.com/stalwartlabs/opentelemetry-rust" }
|
||||
prometheus = { version = "0.14", default-features = false }
|
||||
imagesize = "0.15"
|
||||
sha1 = "0.11"
|
||||
sha2 = "0.11"
|
||||
|
|
@ -102,7 +98,7 @@ dns-update = { version = "0.6", features = ["test_provider"] }
|
|||
|
||||
[features]
|
||||
dev_mode = []
|
||||
enterprise = ["store/enterprise", "utils/enterprise", "trc/enterprise", "directory/enterprise", "coordinator/enterprise", "registry/enterprise", "jmap_proto/enterprise"]
|
||||
enterprise = ["store/enterprise", "utils/enterprise", "trc/enterprise", "telemetry/enterprise", "directory/enterprise", "coordinator/enterprise", "registry/enterprise", "jmap_proto/enterprise"]
|
||||
foundation = []
|
||||
redis = ["store/redis"]
|
||||
|
||||
|
|
|
|||
|
|
@ -14,13 +14,14 @@ use crate::{
|
|||
use registry::{
|
||||
schema::{
|
||||
enums::OAuthClientKind,
|
||||
prelude::{Object, ObjectInner, ObjectType},
|
||||
prelude::{Object, ObjectInner, ObjectType, Property},
|
||||
structs::OAuthGrant,
|
||||
},
|
||||
types::{datetime::UTCDateTime, id::ObjectId, ipaddr::IpAddr},
|
||||
};
|
||||
use std::net::IpAddr as StdIpAddr;
|
||||
use store::{
|
||||
blake3,
|
||||
registry::{
|
||||
RegistryQuery,
|
||||
write::{RegistryWrite, RegistryWriteResult},
|
||||
|
|
@ -116,6 +117,10 @@ impl TokenScope {
|
|||
}
|
||||
}
|
||||
|
||||
fn client_id_hash(client_id: &str) -> String {
|
||||
blake3::hash(client_id.as_bytes()).to_hex().to_string()
|
||||
}
|
||||
|
||||
fn prune_selection(last_used: &[i64], now: i64, idle_timeout: i64) -> Vec<bool> {
|
||||
let mut prune = last_used
|
||||
.iter()
|
||||
|
|
@ -231,6 +236,7 @@ impl Server {
|
|||
let grant = OAuthGrant {
|
||||
account_id: Id::from(new.account_id),
|
||||
client_id: new.client_id.to_string(),
|
||||
client_hash: client_id_hash(new.client_id),
|
||||
client_name: new
|
||||
.client_name
|
||||
.filter(|name| !name.is_empty())
|
||||
|
|
@ -303,6 +309,38 @@ impl Server {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn has_oauth_grant(
|
||||
&self,
|
||||
account_id: u32,
|
||||
client_id: &str,
|
||||
client_kind: OAuthClientKind,
|
||||
scopes: OAuthScopes,
|
||||
) -> trc::Result<bool> {
|
||||
let idle_since =
|
||||
(now() as i64).saturating_sub(self.core.oauth.oauth_expiry_refresh_token as i64);
|
||||
for id in self
|
||||
.registry()
|
||||
.query::<Vec<Id>>(
|
||||
RegistryQuery::new(ObjectType::OAuthGrant)
|
||||
.with_account(account_id)
|
||||
.equal(Property::ClientHash, client_id_hash(client_id)),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
if self.oauth_grant(id.id()).await?.is_some_and(|stored| {
|
||||
let grant = &stored.grant;
|
||||
grant.client_id == client_id
|
||||
&& grant.client_kind == client_kind
|
||||
&& grant.last_used_at.timestamp() > idle_since
|
||||
&& OAuthScopes::from_registry(grant.scopes.iter()).contains(scopes)
|
||||
}) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub async fn revoke_oauth_grants(
|
||||
&self,
|
||||
account_id: u32,
|
||||
|
|
@ -412,6 +450,9 @@ impl Server {
|
|||
updated.generation = stored_generation;
|
||||
updated.pending = true;
|
||||
updated.last_used_at = now;
|
||||
if updated.client_hash.is_empty() {
|
||||
updated.client_hash = client_id_hash(&updated.client_id);
|
||||
}
|
||||
let old_object =
|
||||
Object::with_revision(ObjectInner::OAuthGrant(stored.grant), stored.revision);
|
||||
let new_object = Object::new(ObjectInner::OAuthGrant(updated));
|
||||
|
|
|
|||
|
|
@ -96,6 +96,7 @@ impl Server {
|
|||
}
|
||||
|
||||
permissions.restrict(&tenant_permissions);
|
||||
permissions.disabled.set(Permission::Impersonate as usize);
|
||||
} else {
|
||||
// Enterprise edition downgrade, remove any tenant administrator permissions
|
||||
permissions.restrict(&PermissionsGroup::user());
|
||||
|
|
|
|||
|
|
@ -10,17 +10,10 @@ use ahash::{AHashMap, AHashSet};
|
|||
use aws_lc_rs::constant_time::verify_slices_are_equal;
|
||||
use encodify::base64::STANDARD;
|
||||
use hyper::HeaderMap;
|
||||
use opentelemetry::{InstrumentationScope, KeyValue};
|
||||
use opentelemetry_otlp::{
|
||||
LogExporter, MetricExporter, SpanExporter, WithExportConfig, WithHttpConfig, WithTonicConfig,
|
||||
tonic_types::metadata::MetadataMap,
|
||||
};
|
||||
use opentelemetry_sdk::{Resource, metrics::Temporality};
|
||||
use opentelemetry_semantic_conventions::resource::SERVICE_VERSION;
|
||||
use registry::schema::{
|
||||
enums::{EventPolicy, LogRotateFrequency},
|
||||
prelude::ObjectType,
|
||||
structs::{self, EventTracingLevel, MetricsPrometheus, Tracer, WebHook},
|
||||
structs::{self, EventTracingLevel, HttpAuth, MetricsPrometheus, Tracer, WebHook},
|
||||
};
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
|
|
@ -30,15 +23,27 @@ use registry::schema::structs::Search;
|
|||
// SPDX-SnippetEnd
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
hash::{DefaultHasher, Hash, Hasher},
|
||||
str::FromStr,
|
||||
sync::Arc,
|
||||
sync::{Arc, atomic::AtomicUsize},
|
||||
time::Duration,
|
||||
};
|
||||
use store::registry::bootstrap::Bootstrap;
|
||||
use telemetry::{
|
||||
exporter::{
|
||||
DEFAULT_MAX_PENDING_BYTES, DEFAULT_MAX_REQUEST_BYTES, OtlpConfig, OtlpTracer,
|
||||
metrics::OtlpMetricsExporter,
|
||||
},
|
||||
otlp::resource::{ProcessIdentity, Resource},
|
||||
transport::{
|
||||
endpoint::{Endpoint, Transport},
|
||||
sender::is_reserved_header,
|
||||
},
|
||||
};
|
||||
use trc::{EventType, Level, MetricType, TelemetryEvent, ipc::subscriber::Interests};
|
||||
use utils::http::http_client_builder;
|
||||
use utils::{http::shared_tls_config, map::vec_map::VecMap};
|
||||
|
||||
const DEFAULT_GRPC_URL: &str = "http://localhost:4317";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TelemetrySubscriber {
|
||||
|
|
@ -65,19 +70,10 @@ pub enum TelemetrySubscriberType {
|
|||
// SPDX-SnippetEnd
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct OtelTracer {
|
||||
pub span_exporter: SpanExporter,
|
||||
pub span_exporter_enable: bool,
|
||||
pub log_exporter: LogExporter,
|
||||
pub log_exporter_enable: bool,
|
||||
pub throttle: Duration,
|
||||
}
|
||||
pub type OtelTracer = OtlpTracer;
|
||||
|
||||
pub struct OtelMetrics {
|
||||
pub resource: Resource,
|
||||
pub instrumentation: InstrumentationScope,
|
||||
pub exporter: MetricExporter,
|
||||
pub exporter: tokio::sync::Mutex<OtlpMetricsExporter>,
|
||||
pub interval: Duration,
|
||||
}
|
||||
|
||||
|
|
@ -153,6 +149,7 @@ pub struct Metrics {
|
|||
#[derive(Debug, Clone)]
|
||||
pub struct PrometheusMetrics {
|
||||
pub auth: PrometheusAuth,
|
||||
pub size_hint: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
|
@ -190,13 +187,14 @@ impl PrometheusAuth {
|
|||
|
||||
impl Telemetry {
|
||||
pub async fn parse(bp: &mut Bootstrap, storage: &Storage, index_tx: IndexQueueNotify) -> Self {
|
||||
let metrics = bp.setting_infallible::<structs::Metrics>().await;
|
||||
let resource = OtlpResource::new(bp, &metrics);
|
||||
let mut telemetry = Telemetry {
|
||||
tracers: Tracers::parse(bp, storage, index_tx).await,
|
||||
tracers: Tracers::parse(bp, storage, index_tx, &resource).await,
|
||||
metrics: Interests::default(),
|
||||
};
|
||||
|
||||
// Parse metrics
|
||||
let metrics = bp.setting_infallible::<structs::Metrics>().await;
|
||||
apply_metrics(metrics.metrics, metrics.metrics_policy, |metric_type| {
|
||||
let event_id = metric_type.event_id();
|
||||
if event_id != usize::MAX {
|
||||
|
|
@ -229,21 +227,107 @@ fn sink_fingerprint<T: Serialize>(value: &T) -> u64 {
|
|||
hasher.finish()
|
||||
}
|
||||
|
||||
fn tracer_sink_fingerprint(tracer: &Tracer) -> u64 {
|
||||
fn tracer_sink_fingerprint(tracer: &Tracer, resource: &OtlpResource) -> u64 {
|
||||
let mut tracer = tracer.clone();
|
||||
match &mut tracer {
|
||||
Tracer::Log(t) => strip_interests!(t, level),
|
||||
Tracer::Stdout(t) => strip_interests!(t, level),
|
||||
Tracer::Journal(t) => strip_interests!(t, level),
|
||||
Tracer::OtelHttp(t) => strip_interests!(t, level),
|
||||
Tracer::OtelGrpc(t) => strip_interests!(t, level),
|
||||
let resource_fingerprint = match &mut tracer {
|
||||
Tracer::Log(t) => {
|
||||
strip_interests!(t, level);
|
||||
0
|
||||
}
|
||||
Tracer::Stdout(t) => {
|
||||
strip_interests!(t, level);
|
||||
0
|
||||
}
|
||||
Tracer::Journal(t) => {
|
||||
strip_interests!(t, level);
|
||||
0
|
||||
}
|
||||
Tracer::OtelHttp(t) => {
|
||||
strip_interests!(t, level);
|
||||
resource.fingerprint
|
||||
}
|
||||
Tracer::OtelGrpc(t) => {
|
||||
strip_interests!(t, level);
|
||||
resource.fingerprint
|
||||
}
|
||||
};
|
||||
sink_fingerprint(&tracer) ^ resource_fingerprint
|
||||
}
|
||||
|
||||
pub struct OtlpResource {
|
||||
resource: Resource,
|
||||
fingerprint: u64,
|
||||
}
|
||||
|
||||
impl OtlpResource {
|
||||
fn new(bp: &Bootstrap, metrics: &structs::Metrics) -> Self {
|
||||
Self {
|
||||
resource: Resource::new(
|
||||
&ProcessIdentity::new(bp.registry.process_nonce()),
|
||||
&metrics.service_name,
|
||||
metrics.service_namespace.as_deref(),
|
||||
metrics
|
||||
.resource_attributes
|
||||
.iter()
|
||||
.map(|(key, value)| (key.as_str(), value.as_str())),
|
||||
),
|
||||
fingerprint: sink_fingerprint(&(
|
||||
&metrics.service_name,
|
||||
&metrics.service_namespace,
|
||||
&metrics.resource_attributes,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct OtlpSettings {
|
||||
transport: Transport,
|
||||
url: Option<String>,
|
||||
http_auth: HttpAuth,
|
||||
http_headers: VecMap<String, String>,
|
||||
allow_invalid_certs: bool,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl OtlpSettings {
|
||||
async fn build(self) -> Result<OtlpConfig, String> {
|
||||
let url = self.url.as_deref().unwrap_or(DEFAULT_GRPC_URL);
|
||||
let endpoint = Endpoint::parse(url).map_err(|err| err.to_string())?;
|
||||
let header_map = self
|
||||
.http_auth
|
||||
.build_headers(self.http_headers, None)
|
||||
.await
|
||||
.map_err(|err| format!("Failed to build OpenTelemetry headers: {err}"))?;
|
||||
let mut headers = Vec::with_capacity(header_map.len());
|
||||
let mut name = None;
|
||||
for (next_name, value) in header_map {
|
||||
if next_name.is_some() {
|
||||
name = next_name;
|
||||
}
|
||||
if let Some(name) = name.as_ref().filter(|name| !is_reserved_header(name)) {
|
||||
headers.push((name.clone(), value));
|
||||
}
|
||||
}
|
||||
Ok(OtlpConfig {
|
||||
endpoint,
|
||||
transport: self.transport,
|
||||
headers: headers.into(),
|
||||
tls: Arc::new(shared_tls_config(self.allow_invalid_certs)),
|
||||
timeout: self.timeout,
|
||||
max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
|
||||
max_pending_bytes: DEFAULT_MAX_PENDING_BYTES,
|
||||
})
|
||||
}
|
||||
sink_fingerprint(&tracer)
|
||||
}
|
||||
|
||||
impl Tracers {
|
||||
#[cfg_attr(not(feature = "enterprise"), allow(unused_variables))]
|
||||
pub async fn parse(bp: &mut Bootstrap, storage: &Storage, index_tx: IndexQueueNotify) -> Self {
|
||||
pub async fn parse(
|
||||
bp: &mut Bootstrap,
|
||||
storage: &Storage,
|
||||
index_tx: IndexQueueNotify,
|
||||
resource: &OtlpResource,
|
||||
) -> Self {
|
||||
let mut custom_levels = AHashMap::new();
|
||||
let mut tracers: Vec<TelemetrySubscriber> = Vec::new();
|
||||
let mut global_interests = Interests::default();
|
||||
|
|
@ -258,7 +342,7 @@ impl Tracers {
|
|||
for tracer in bp.list_infallible::<Tracer>().await {
|
||||
let id = tracer.id;
|
||||
let tracer = tracer.object;
|
||||
let sink = tracer_sink_fingerprint(&tracer);
|
||||
let sink = tracer_sink_fingerprint(&tracer, resource);
|
||||
let level;
|
||||
let lossy;
|
||||
let events;
|
||||
|
|
@ -351,81 +435,26 @@ impl Tracers {
|
|||
events_policy = tracer.events_policy;
|
||||
enable = tracer.enable;
|
||||
|
||||
let headers = match tracer
|
||||
.http_auth
|
||||
.build_headers(tracer.http_headers, None)
|
||||
.await
|
||||
match (OtlpSettings {
|
||||
transport: Transport::Http,
|
||||
url: Some(tracer.url),
|
||||
http_auth: tracer.http_auth,
|
||||
http_headers: tracer.http_headers,
|
||||
allow_invalid_certs: tracer.allow_invalid_certs,
|
||||
timeout: tracer.timeout.into_inner(),
|
||||
})
|
||||
.build()
|
||||
.await
|
||||
{
|
||||
Ok(headers) => headers
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| {
|
||||
k.and_then(|k| {
|
||||
Some((k.to_string(), v.to_str().ok()?.to_string()))
|
||||
})
|
||||
})
|
||||
.collect::<HashMap<String, String>>(),
|
||||
Ok(otlp) => TelemetrySubscriberType::OtelTracer(OtlpTracer {
|
||||
otlp,
|
||||
resource: resource.resource.clone(),
|
||||
throttle: tracer.throttle.into_inner(),
|
||||
export_logs: tracer.enable_log_exporter,
|
||||
export_spans: tracer.enable_span_exporter,
|
||||
}),
|
||||
Err(err) => {
|
||||
bp.build_error(
|
||||
id,
|
||||
format!("Failed to build OpenTelemetry HTTP headers: {err}"),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let mut span_exporter = SpanExporter::builder()
|
||||
.with_http()
|
||||
.with_endpoint(tracer.url.clone())
|
||||
.with_timeout(tracer.timeout.into_inner());
|
||||
let mut log_exporter = LogExporter::builder()
|
||||
.with_http()
|
||||
.with_endpoint(tracer.url)
|
||||
.with_timeout(tracer.timeout.into_inner());
|
||||
if !headers.is_empty() {
|
||||
span_exporter = span_exporter.with_headers(headers.clone());
|
||||
log_exporter = log_exporter.with_headers(headers);
|
||||
}
|
||||
if tracer.allow_invalid_certs {
|
||||
match http_client_builder(true)
|
||||
.timeout(tracer.timeout.into_inner())
|
||||
.build()
|
||||
{
|
||||
Ok(client) => {
|
||||
span_exporter = span_exporter.with_http_client(client.clone());
|
||||
log_exporter = log_exporter.with_http_client(client);
|
||||
}
|
||||
Err(err) => {
|
||||
bp.build_error(
|
||||
id,
|
||||
format!("Failed to build OpenTelemetry HTTP client: {err}"),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match (span_exporter.build(), log_exporter.build()) {
|
||||
(Ok(span_exporter), Ok(log_exporter)) => {
|
||||
TelemetrySubscriberType::OtelTracer(OtelTracer {
|
||||
span_exporter,
|
||||
log_exporter,
|
||||
throttle: tracer.throttle.into_inner(),
|
||||
span_exporter_enable: tracer.enable_span_exporter,
|
||||
log_exporter_enable: tracer.enable_log_exporter,
|
||||
})
|
||||
}
|
||||
(Err(err), _) => {
|
||||
bp.build_error(
|
||||
id,
|
||||
format!("Failed to build OpenTelemetry span exporter: {err}"),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
(_, Err(err)) => {
|
||||
bp.build_error(
|
||||
id,
|
||||
format!("Failed to build OpenTelemetry log exporter: {err}"),
|
||||
);
|
||||
bp.build_error(id, err);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
|
@ -437,58 +466,26 @@ impl Tracers {
|
|||
events_policy = tracer.events_policy;
|
||||
enable = tracer.enable;
|
||||
|
||||
let metadata = match tracer
|
||||
.http_auth
|
||||
.build_headers(tracer.http_headers, None)
|
||||
.await
|
||||
match (OtlpSettings {
|
||||
transport: Transport::Grpc,
|
||||
url: tracer.url,
|
||||
http_auth: tracer.http_auth,
|
||||
http_headers: tracer.http_headers,
|
||||
allow_invalid_certs: tracer.allow_invalid_certs,
|
||||
timeout: tracer.timeout.into_inner(),
|
||||
})
|
||||
.build()
|
||||
.await
|
||||
{
|
||||
Ok(headers) => MetadataMap::from_headers(headers),
|
||||
Ok(otlp) => TelemetrySubscriberType::OtelTracer(OtlpTracer {
|
||||
otlp,
|
||||
resource: resource.resource.clone(),
|
||||
throttle: tracer.throttle.into_inner(),
|
||||
export_logs: tracer.enable_log_exporter,
|
||||
export_spans: tracer.enable_span_exporter,
|
||||
}),
|
||||
Err(err) => {
|
||||
bp.build_error(
|
||||
id,
|
||||
format!("Failed to build OpenTelemetry gRPC metadata: {err}"),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let mut span_exporter = SpanExporter::builder()
|
||||
.with_tonic()
|
||||
.with_protocol(opentelemetry_otlp::Protocol::Grpc)
|
||||
.with_timeout(tracer.timeout.into_inner())
|
||||
.with_metadata(metadata.clone());
|
||||
let mut log_exporter = LogExporter::builder()
|
||||
.with_tonic()
|
||||
.with_protocol(opentelemetry_otlp::Protocol::Grpc)
|
||||
.with_timeout(tracer.timeout.into_inner())
|
||||
.with_metadata(metadata);
|
||||
if let Some(endpoint) = tracer.url {
|
||||
span_exporter = span_exporter.with_endpoint(endpoint.clone());
|
||||
log_exporter = log_exporter.with_endpoint(endpoint);
|
||||
}
|
||||
|
||||
match (span_exporter.build(), log_exporter.build()) {
|
||||
(Ok(span_exporter), Ok(log_exporter)) => {
|
||||
TelemetrySubscriberType::OtelTracer(OtelTracer {
|
||||
span_exporter,
|
||||
log_exporter,
|
||||
throttle: tracer.throttle.into_inner(),
|
||||
span_exporter_enable: tracer.enable_span_exporter,
|
||||
log_exporter_enable: tracer.enable_log_exporter,
|
||||
})
|
||||
}
|
||||
(Err(err), _) => {
|
||||
bp.build_error(
|
||||
id,
|
||||
format!("Failed to build OpenTelemetry span exporter: {err}"),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
(_, Err(err)) => {
|
||||
bp.build_error(
|
||||
id,
|
||||
format!("Failed to build OpenTelemetry log exporter: {err}"),
|
||||
);
|
||||
bp.build_error(id, err);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
|
@ -726,13 +723,7 @@ impl Tracers {
|
|||
impl Metrics {
|
||||
pub async fn parse(bp: &mut Bootstrap) -> Self {
|
||||
let metrics = bp.setting_infallible::<structs::Metrics>().await;
|
||||
let resource = Resource::builder()
|
||||
.with_service_name("stalwart")
|
||||
.with_attribute(KeyValue::new(SERVICE_VERSION, env!("CARGO_PKG_VERSION")))
|
||||
.build();
|
||||
let instrumentation = InstrumentationScope::builder("stalwart")
|
||||
.with_version(env!("CARGO_PKG_VERSION"))
|
||||
.build();
|
||||
let resource = OtlpResource::new(bp, &metrics).resource;
|
||||
|
||||
Metrics {
|
||||
prometheus: match metrics.prometheus {
|
||||
|
|
@ -747,7 +738,10 @@ impl Metrics {
|
|||
}
|
||||
};
|
||||
match auth {
|
||||
Ok(auth) => Some(PrometheusMetrics { auth }),
|
||||
Ok(auth) => Some(PrometheusMetrics {
|
||||
auth,
|
||||
size_hint: Arc::new(AtomicUsize::new(0)),
|
||||
}),
|
||||
Err(err) => {
|
||||
bp.build_error(
|
||||
ObjectType::Metrics.singleton(),
|
||||
|
|
@ -759,94 +753,55 @@ impl Metrics {
|
|||
}
|
||||
MetricsPrometheus::Disabled => None,
|
||||
},
|
||||
otel: match metrics.open_telemetry {
|
||||
structs::MetricsOtel::Http(otel) => 'otel: {
|
||||
let headers = match otel.http_auth.build_headers(otel.http_headers, None).await
|
||||
{
|
||||
Ok(headers) => headers
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| {
|
||||
k.and_then(|k| Some((k.to_string(), v.to_str().ok()?.to_string())))
|
||||
})
|
||||
.collect::<HashMap<String, String>>(),
|
||||
Err(err) => {
|
||||
bp.build_error(
|
||||
ObjectType::Metrics.singleton(),
|
||||
format!("Failed to build OpenTelemetry HTTP headers: {err}"),
|
||||
);
|
||||
Default::default()
|
||||
}
|
||||
};
|
||||
|
||||
let mut exporter = MetricExporter::builder()
|
||||
.with_temporality(Temporality::Delta)
|
||||
.with_http()
|
||||
.with_endpoint(otel.url)
|
||||
.with_timeout(otel.timeout.into_inner());
|
||||
if !headers.is_empty() {
|
||||
exporter = exporter.with_headers(headers);
|
||||
}
|
||||
if otel.allow_invalid_certs {
|
||||
match http_client_builder(true)
|
||||
.timeout(otel.timeout.into_inner())
|
||||
.build()
|
||||
{
|
||||
Ok(client) => {
|
||||
exporter = exporter.with_http_client(client);
|
||||
}
|
||||
otel: {
|
||||
let settings = match metrics.open_telemetry {
|
||||
structs::MetricsOtel::Http(otel) => Some((
|
||||
OtlpSettings {
|
||||
transport: Transport::Http,
|
||||
url: Some(otel.url),
|
||||
http_auth: otel.http_auth,
|
||||
http_headers: otel.http_headers,
|
||||
allow_invalid_certs: otel.allow_invalid_certs,
|
||||
timeout: otel.timeout.into_inner(),
|
||||
},
|
||||
otel.interval.into_inner(),
|
||||
)),
|
||||
structs::MetricsOtel::Grpc(otel) => Some((
|
||||
OtlpSettings {
|
||||
transport: Transport::Grpc,
|
||||
url: otel.url,
|
||||
http_auth: otel.http_auth,
|
||||
http_headers: otel.http_headers,
|
||||
allow_invalid_certs: otel.allow_invalid_certs,
|
||||
timeout: otel.timeout.into_inner(),
|
||||
},
|
||||
otel.interval.into_inner(),
|
||||
)),
|
||||
structs::MetricsOtel::Disabled => None,
|
||||
};
|
||||
match settings {
|
||||
Some((settings, interval)) => {
|
||||
match settings.build().await.and_then(|config| {
|
||||
OtlpMetricsExporter::new(config, resource)
|
||||
.map_err(|err| err.to_string())
|
||||
}) {
|
||||
Ok(exporter) => Some(Arc::new(OtelMetrics {
|
||||
exporter: tokio::sync::Mutex::new(exporter),
|
||||
interval,
|
||||
})),
|
||||
Err(err) => {
|
||||
bp.build_error(
|
||||
ObjectType::Metrics.singleton(),
|
||||
format!("Failed to build OpenTelemetry HTTP client: {err}"),
|
||||
format!(
|
||||
"Failed to build OpenTelemetry metrics exporter: {err}"
|
||||
),
|
||||
);
|
||||
break 'otel None;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match exporter.build() {
|
||||
Ok(exporter) => Some(Arc::new(OtelMetrics {
|
||||
exporter,
|
||||
interval: otel.interval.into_inner(),
|
||||
resource,
|
||||
instrumentation,
|
||||
})),
|
||||
Err(err) => {
|
||||
bp.build_error(
|
||||
ObjectType::Metrics.singleton(),
|
||||
format!("Failed to build OpenTelemetry metrics exporter: {err}"),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
structs::MetricsOtel::Grpc(otel) => {
|
||||
let mut exporter = MetricExporter::builder()
|
||||
.with_temporality(Temporality::Delta)
|
||||
.with_tonic()
|
||||
.with_protocol(opentelemetry_otlp::Protocol::Grpc)
|
||||
.with_timeout(otel.timeout.into_inner());
|
||||
if let Some(endpoint) = otel.url {
|
||||
exporter = exporter.with_endpoint(endpoint);
|
||||
}
|
||||
|
||||
match exporter.build() {
|
||||
Ok(exporter) => Some(Arc::new(OtelMetrics {
|
||||
exporter,
|
||||
interval: otel.interval.into_inner(),
|
||||
resource,
|
||||
instrumentation,
|
||||
})),
|
||||
Err(err) => {
|
||||
bp.build_error(
|
||||
ObjectType::Metrics.singleton(),
|
||||
format!("Failed to build OpenTelemetry metrics exporter: {err}"),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
structs::MetricsOtel::Disabled => None,
|
||||
},
|
||||
log_path: bp
|
||||
.list_infallible::<Tracer>()
|
||||
|
|
|
|||
|
|
@ -153,7 +153,7 @@ pub enum AuthStatus {
|
|||
|
||||
pub struct AcmeDnsParameters {
|
||||
pub updater: DnsUpdater,
|
||||
pub origin: Option<String>,
|
||||
pub zone: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, Deserialize)]
|
||||
|
|
|
|||
|
|
@ -321,11 +321,7 @@ impl AcmeRequestBuilder {
|
|||
};
|
||||
let domain = domain.strip_prefix("*.").unwrap_or(&domain);
|
||||
|
||||
let zone = dns_parameters
|
||||
.origin
|
||||
.as_deref()
|
||||
.or_else(|| psl::domain_str(domain))
|
||||
.unwrap_or(domain);
|
||||
let zone = challenge_zone(&dns_parameters.zone, domain);
|
||||
|
||||
let proof = self.dns_proof(challenge)?;
|
||||
let challenge_name = format!("_acme-challenge.{}", domain);
|
||||
|
|
@ -548,6 +544,21 @@ impl ParsedCert {
|
|||
}
|
||||
}
|
||||
|
||||
fn challenge_zone<'x>(zone: &'x str, domain: &'x str) -> &'x str {
|
||||
let in_zone = domain
|
||||
.len()
|
||||
.checked_sub(zone.len())
|
||||
.and_then(|split| domain.split_at_checked(split))
|
||||
.is_some_and(|(prefix, suffix)| {
|
||||
suffix.eq_ignore_ascii_case(zone) && (prefix.is_empty() || prefix.ends_with('.'))
|
||||
});
|
||||
if in_zone {
|
||||
zone
|
||||
} else {
|
||||
psl::domain_str(domain).unwrap_or(domain)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../../stalwart-tests/unit/common/src/network/acme/order/tests.rs"]
|
||||
|
|
|
|||
|
|
@ -126,7 +126,7 @@ impl Server {
|
|||
match self.build_dns_updater(props.dns_server_id).await? {
|
||||
Ok(updater) => Some(AcmeDnsParameters {
|
||||
updater,
|
||||
origin: props.origin.clone(),
|
||||
zone: props.origin.clone().unwrap_or_else(|| domain.name.clone()),
|
||||
}),
|
||||
Err(err) => {
|
||||
return Err(AcmeError::Invalid(format!(
|
||||
|
|
|
|||
|
|
@ -5,97 +5,21 @@
|
|||
*/
|
||||
|
||||
use crate::config::telemetry::OtelMetrics;
|
||||
use compact_str::ToCompactString;
|
||||
use opentelemetry_sdk::metrics::{
|
||||
Temporality,
|
||||
data::{
|
||||
AggregatedMetrics, Gauge, GaugeDataPoint, Histogram, HistogramDataPoint, Metric,
|
||||
MetricData, ResourceMetrics, ScopeMetrics, Sum, SumDataPoint,
|
||||
},
|
||||
exporter::PushMetricExporter,
|
||||
};
|
||||
use std::time::SystemTime;
|
||||
use trc::{Collector, TelemetryEvent};
|
||||
use trc::TelemetryEvent;
|
||||
|
||||
impl OtelMetrics {
|
||||
pub async fn push_metrics(&self, is_enterprise: bool, start_time: SystemTime) {
|
||||
let mut metrics = Vec::with_capacity(256);
|
||||
let time = SystemTime::now();
|
||||
|
||||
// Add counters
|
||||
for counter in Collector::collect_counters(is_enterprise) {
|
||||
metrics.push(Metric::new(
|
||||
counter.id().as_str(),
|
||||
counter.id().description(),
|
||||
"events",
|
||||
AggregatedMetrics::U64(MetricData::Sum(Sum::new(
|
||||
vec![SumDataPoint::new(vec![], counter.value(), vec![])],
|
||||
start_time,
|
||||
time,
|
||||
Temporality::Cumulative,
|
||||
true,
|
||||
))),
|
||||
));
|
||||
}
|
||||
|
||||
// Add gauges
|
||||
for gauge in Collector::collect_gauges(is_enterprise) {
|
||||
metrics.push(Metric::new(
|
||||
gauge.id().as_str(),
|
||||
gauge.id().description(),
|
||||
gauge.id().unit(),
|
||||
AggregatedMetrics::U64(MetricData::Gauge(Gauge::new(
|
||||
vec![GaugeDataPoint::new(vec![], gauge.get(), vec![])],
|
||||
Some(start_time),
|
||||
time,
|
||||
))),
|
||||
));
|
||||
}
|
||||
|
||||
// Add histograms
|
||||
for histogram in Collector::collect_histograms(is_enterprise) {
|
||||
metrics.push(Metric::new(
|
||||
histogram.id().as_str(),
|
||||
histogram.id().description(),
|
||||
histogram.id().unit(),
|
||||
AggregatedMetrics::U64(MetricData::Histogram(Histogram::new(
|
||||
vec![HistogramDataPoint::new(
|
||||
vec![],
|
||||
histogram.count(),
|
||||
histogram.upper_bounds_vec(),
|
||||
histogram.buckets_vec(),
|
||||
histogram.min(),
|
||||
histogram.max(),
|
||||
histogram.sum(),
|
||||
vec![],
|
||||
)],
|
||||
start_time,
|
||||
time,
|
||||
Temporality::Cumulative,
|
||||
))),
|
||||
));
|
||||
}
|
||||
|
||||
// Export metrics
|
||||
let rm = ResourceMetrics::new(
|
||||
self.resource.clone(),
|
||||
vec![ScopeMetrics::new(self.instrumentation.clone(), metrics)],
|
||||
);
|
||||
if let Err(err) = self.exporter.export(&rm).await {
|
||||
trc::event!(
|
||||
match self.exporter.try_lock() {
|
||||
Ok(mut exporter) => {
|
||||
exporter
|
||||
.push(is_enterprise, start_time, self.interval)
|
||||
.await
|
||||
}
|
||||
Err(_) => trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelMetricsExporterError),
|
||||
Reason = err.to_compact_string(),
|
||||
);
|
||||
Details = "Previous metrics export still in progress, skipping this interval",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enable_errors() {
|
||||
// TODO: Remove this when the OpenTelemetry SDK supports error handling
|
||||
/*let _ = set_error_handler(|error| {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelMetricsExporterError),
|
||||
Reason = error.to_compact_string(),
|
||||
);
|
||||
});*/
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,18 +4,18 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use prometheus::{
|
||||
TextEncoder,
|
||||
proto::{Bucket, Counter, Gauge, Histogram, Metric, MetricFamily, MetricType},
|
||||
};
|
||||
use trc::{Collector, atomics::histogram::AtomicHistogram};
|
||||
use crate::{Server, config::telemetry::PrometheusMetrics};
|
||||
use std::sync::atomic::Ordering;
|
||||
use telemetry::prometheus::{PromFormat, text::write_prometheus};
|
||||
|
||||
use crate::Server;
|
||||
const SIZE_HINT_MARGIN: usize = 1024;
|
||||
|
||||
impl Server {
|
||||
pub async fn export_prometheus_metrics(&self) -> trc::Result<String> {
|
||||
let mut metrics = Vec::new();
|
||||
|
||||
pub fn export_prometheus_metrics(
|
||||
&self,
|
||||
prometheus: &PrometheusMetrics,
|
||||
format: PromFormat,
|
||||
) -> Vec<u8> {
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
|
|
@ -30,93 +30,10 @@ impl Server {
|
|||
self.inner.refresh_live_gauges();
|
||||
}
|
||||
|
||||
// Add counters
|
||||
for counter in Collector::collect_counters(is_enterprise) {
|
||||
let mut metric = MetricFamily::default();
|
||||
metric.set_name(metric_name(counter.id().as_str()));
|
||||
metric.set_help(counter.id().description().into());
|
||||
metric.set_field_type(MetricType::COUNTER);
|
||||
metric.set_metric(vec![new_counter(counter.value())]);
|
||||
metrics.push(metric);
|
||||
}
|
||||
|
||||
// Add gauges
|
||||
for gauge in Collector::collect_gauges(is_enterprise) {
|
||||
let mut metric = MetricFamily::default();
|
||||
metric.set_name(metric_name(gauge.id().as_str()));
|
||||
metric.set_help(gauge.id().description().into());
|
||||
metric.set_field_type(MetricType::GAUGE);
|
||||
metric.set_metric(vec![new_gauge(gauge.get())]);
|
||||
metrics.push(metric);
|
||||
}
|
||||
|
||||
// Add histograms
|
||||
for histogram in Collector::collect_histograms(is_enterprise) {
|
||||
let mut metric = MetricFamily::default();
|
||||
metric.set_name(metric_name(histogram.id().as_str()));
|
||||
metric.set_help(histogram.id().description().into());
|
||||
metric.set_field_type(MetricType::HISTOGRAM);
|
||||
metric.set_metric(vec![new_histogram(histogram)]);
|
||||
metrics.push(metric);
|
||||
}
|
||||
|
||||
TextEncoder::new().encode_to_string(&metrics).map_err(|e| {
|
||||
trc::EventType::Telemetry(trc::TelemetryEvent::OtelExporterError).reason(e)
|
||||
})
|
||||
let mut out =
|
||||
Vec::with_capacity(prometheus.size_hint.load(Ordering::Relaxed) + SIZE_HINT_MARGIN);
|
||||
write_prometheus(&mut out, format, is_enterprise);
|
||||
prometheus.size_hint.store(out.len(), Ordering::Relaxed);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn metric_name(id: impl AsRef<str>) -> String {
|
||||
let id = id.as_ref();
|
||||
let mut name = String::with_capacity(id.len());
|
||||
for c in id.chars() {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
name.push(c);
|
||||
} else {
|
||||
name.push('_');
|
||||
}
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
fn new_counter(value: u64) -> Metric {
|
||||
let mut m = Metric::default();
|
||||
let mut counter = Counter::default();
|
||||
counter.set_value(value as f64);
|
||||
m.set_counter(counter);
|
||||
m
|
||||
}
|
||||
|
||||
fn new_gauge(value: u64) -> Metric {
|
||||
let mut m = Metric::default();
|
||||
let mut gauge = Gauge::default();
|
||||
gauge.set_value(value as f64);
|
||||
m.set_gauge(gauge);
|
||||
m
|
||||
}
|
||||
|
||||
fn new_histogram(histogram: &AtomicHistogram<12>) -> Metric {
|
||||
let mut m = Metric::default();
|
||||
let mut h = Histogram::default();
|
||||
h.set_sample_count(histogram.count());
|
||||
h.set_sample_sum(histogram.sum() as f64);
|
||||
h.set_bucket(
|
||||
histogram
|
||||
.buckets_iter()
|
||||
.into_iter()
|
||||
.zip(histogram.upper_bounds_iter())
|
||||
.map(|(count, upper_bound)| {
|
||||
let mut b = Bucket::default();
|
||||
b.set_cumulative_count(count);
|
||||
b.set_upper_bound(if upper_bound != u64::MAX {
|
||||
upper_bound as f64
|
||||
} else {
|
||||
f64::INFINITY
|
||||
});
|
||||
b
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
m.set_histogram(h);
|
||||
m
|
||||
}
|
||||
|
|
|
|||
|
|
@ -134,7 +134,7 @@ pub trait MetricsStore: Sync + Send {
|
|||
|
||||
#[derive(Default)]
|
||||
pub struct MetricsHistory {
|
||||
events: AHashMap<MetricType, u32>,
|
||||
events: AHashMap<MetricType, u64>,
|
||||
histograms: AHashMap<MetricType, HistogramHistory>,
|
||||
id_generator: SnowflakeIdGenerator,
|
||||
}
|
||||
|
|
@ -178,7 +178,7 @@ impl MetricsStore for Store {
|
|||
batch.set(
|
||||
ValueClass::Telemetry(TelemetryClass::Metric(metric_id)),
|
||||
Metric::Counter(MetricCount {
|
||||
count: diff as u64,
|
||||
count: diff,
|
||||
metric: event,
|
||||
node_id,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@
|
|||
pub mod journald;
|
||||
pub mod log;
|
||||
pub mod otel;
|
||||
pub mod spans;
|
||||
pub mod stdout;
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
|
|
|
|||
|
|
@ -4,339 +4,15 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{LONG_1Y_SLUMBER, config::telemetry::OtelTracer};
|
||||
use compact_str::ToCompactString;
|
||||
use mail_parser::DateTime;
|
||||
use opentelemetry::{
|
||||
InstrumentationScope, Key, KeyValue, Value,
|
||||
logs::{AnyValue, Severity},
|
||||
trace::{SpanContext, SpanKind, Status, TraceFlags, TraceState},
|
||||
};
|
||||
use opentelemetry_sdk::{
|
||||
Resource,
|
||||
logs::{LogBatch, LogExporter, SdkLogRecord},
|
||||
trace::{SpanData, SpanEvents, SpanExporter, SpanLinks},
|
||||
};
|
||||
use opentelemetry_semantic_conventions::resource::SERVICE_VERSION;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use trc::{
|
||||
Event, EventDetails, Level, TelemetryEvent, event::KeySet, ipc::subscriber::SubscriberBuilder,
|
||||
};
|
||||
use crate::config::telemetry::OtelTracer;
|
||||
use trc::{TelemetryEvent, ipc::subscriber::SubscriberBuilder};
|
||||
|
||||
use super::spans::{SpanTracker, report_discarded_spans, tracks_span};
|
||||
|
||||
const MAX_PENDING_LOGS: usize = 1 << 16;
|
||||
const MAX_PENDING_SPANS: usize = 1 << 14;
|
||||
|
||||
pub(crate) fn spawn_otel_tracer(builder: SubscriberBuilder, mut otel: OtelTracer) {
|
||||
let (_, mut rx, interests) = builder.register();
|
||||
tokio::spawn(async move {
|
||||
let resource = Resource::builder()
|
||||
.with_service_name("stalwart")
|
||||
.with_attribute(KeyValue::new(SERVICE_VERSION, env!("CARGO_PKG_VERSION")))
|
||||
.build();
|
||||
|
||||
let instrumentation = InstrumentationScope::builder("stalwart")
|
||||
.with_version(env!("CARGO_PKG_VERSION"))
|
||||
.build();
|
||||
|
||||
otel.log_exporter.set_resource(&resource);
|
||||
otel.span_exporter.set_resource(&resource);
|
||||
|
||||
let mut wakeup_time = LONG_1Y_SLUMBER;
|
||||
let mut next_delivery = Instant::now();
|
||||
|
||||
let mut pending_logs = Vec::new();
|
||||
let mut pending_spans = Vec::new();
|
||||
|
||||
let mut active_spans = SpanTracker::default();
|
||||
let mut discarded_logs = 0usize;
|
||||
let mut discarded_spans = 0usize;
|
||||
|
||||
loop {
|
||||
// Wait for the next event or timeout
|
||||
let event_or_timeout = tokio::time::timeout(wakeup_time, rx.recv()).await;
|
||||
|
||||
match event_or_timeout {
|
||||
Ok(Some(events)) => {
|
||||
let observed = SystemTime::now();
|
||||
if otel.span_exporter_enable
|
||||
&& let Some(event) = events.last()
|
||||
{
|
||||
active_spans.sweep(event.inner.timestamp);
|
||||
}
|
||||
|
||||
for event in events {
|
||||
if otel.log_exporter_enable {
|
||||
if pending_logs.len() < MAX_PENDING_LOGS {
|
||||
pending_logs.push(otel.build_log_record(&event, observed));
|
||||
} else {
|
||||
discarded_logs += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if otel.span_exporter_enable
|
||||
&& let Some(span) = event.inner.span.as_ref()
|
||||
{
|
||||
let span_id = span.span_id().unwrap();
|
||||
if !event.inner.typ.is_span_end() {
|
||||
if !tracks_span(&interests, span) {
|
||||
continue;
|
||||
}
|
||||
active_spans.track(span_id, event);
|
||||
} else if let Some(events) = active_spans.finish(span_id) {
|
||||
if pending_spans.len() < MAX_PENDING_SPANS {
|
||||
pending_spans.push(build_span_data(
|
||||
span,
|
||||
&event,
|
||||
events.iter().chain(std::iter::once(&event)),
|
||||
&instrumentation,
|
||||
));
|
||||
} else {
|
||||
discarded_spans += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((events, spans)) = active_spans.take_discarded() {
|
||||
report_discarded_spans(events, spans);
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
break;
|
||||
}
|
||||
Err(_) => (),
|
||||
}
|
||||
|
||||
// Process events
|
||||
let mut next_retry = None;
|
||||
let now = Instant::now();
|
||||
if next_delivery <= now {
|
||||
if !pending_spans.is_empty() || !pending_logs.is_empty() {
|
||||
next_delivery = now + otel.throttle;
|
||||
|
||||
if discarded_logs > 0 {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = "Log export queue full, discarded logs",
|
||||
Total = std::mem::take(&mut discarded_logs),
|
||||
);
|
||||
}
|
||||
if discarded_spans > 0 {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = "Span export queue full, discarded spans",
|
||||
Total = std::mem::take(&mut discarded_spans),
|
||||
);
|
||||
}
|
||||
|
||||
if !pending_spans.is_empty() {
|
||||
match otel.span_exporter.export(pending_spans.clone()).await {
|
||||
Ok(_) => {
|
||||
pending_spans.clear();
|
||||
}
|
||||
Err(err) => {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = "Failed to export spans, will retry",
|
||||
Reason = err.to_compact_string()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !pending_logs.is_empty() {
|
||||
let logs = pending_logs
|
||||
.iter()
|
||||
.map(|log| (log, &instrumentation))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let result = otel.log_exporter.export(LogBatch::new(&logs)).await;
|
||||
drop(logs);
|
||||
|
||||
match result {
|
||||
Ok(_) => {
|
||||
pending_logs.clear();
|
||||
}
|
||||
Err(err) => {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = "Failed to export logs, will retry",
|
||||
Reason = err.to_compact_string()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !pending_spans.is_empty() || !pending_logs.is_empty() {
|
||||
next_retry = Some(next_delivery.saturating_duration_since(Instant::now()));
|
||||
}
|
||||
}
|
||||
} else if !pending_logs.is_empty() || !pending_spans.is_empty() {
|
||||
// Retry later
|
||||
let this_retry = next_delivery - now;
|
||||
match next_retry {
|
||||
Some(next_retry) if this_retry >= next_retry => {}
|
||||
_ => {
|
||||
next_retry = Some(this_retry);
|
||||
}
|
||||
}
|
||||
}
|
||||
wakeup_time = next_retry.unwrap_or(LONG_1Y_SLUMBER);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn build_span_data<I, T>(
|
||||
start_span: &Event<EventDetails>,
|
||||
end_span: &Event<EventDetails>,
|
||||
span_events: I,
|
||||
instrumentation: &InstrumentationScope,
|
||||
) -> SpanData
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: AsRef<Event<EventDetails>>,
|
||||
{
|
||||
let span_id = start_span.span_id().unwrap();
|
||||
|
||||
let mut events = SpanEvents::default();
|
||||
events.events = span_events
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
let event = event.as_ref();
|
||||
|
||||
opentelemetry::trace::Event::new(
|
||||
event.inner.typ.as_str(),
|
||||
UNIX_EPOCH + Duration::from_secs(event.inner.timestamp),
|
||||
event.keys.iter().filter_map(build_key_value).collect(),
|
||||
0,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
SpanData {
|
||||
span_context: SpanContext::new(
|
||||
(span_id as u128).into(),
|
||||
span_id.into(),
|
||||
TraceFlags::default(),
|
||||
false,
|
||||
TraceState::default(),
|
||||
),
|
||||
dropped_attributes_count: 0,
|
||||
parent_span_id: 0.into(),
|
||||
parent_span_is_remote: false,
|
||||
name: start_span.inner.typ.as_str().into(),
|
||||
start_time: UNIX_EPOCH + Duration::from_secs(start_span.inner.timestamp),
|
||||
end_time: UNIX_EPOCH + Duration::from_secs(end_span.inner.timestamp),
|
||||
attributes: start_span.keys.iter().filter_map(build_key_value).collect(),
|
||||
events,
|
||||
links: SpanLinks::default(),
|
||||
status: Status::default(),
|
||||
span_kind: SpanKind::Server,
|
||||
instrumentation_scope: instrumentation.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
impl OtelTracer {
|
||||
fn build_log_record(&self, event: &Event<EventDetails>, observed: SystemTime) -> SdkLogRecord {
|
||||
use opentelemetry::logs::LogRecord;
|
||||
|
||||
let mut record = SdkLogRecord::new();
|
||||
record.set_event_name(event.inner.typ.as_str());
|
||||
record.set_severity_number(match event.inner.level {
|
||||
Level::Trace => Severity::Trace,
|
||||
Level::Debug => Severity::Debug,
|
||||
Level::Info => Severity::Info,
|
||||
Level::Warn => Severity::Warn,
|
||||
Level::Error => Severity::Error,
|
||||
Level::Disable => Severity::Error,
|
||||
});
|
||||
record.set_severity_text(event.inner.level.as_str());
|
||||
record.set_body(AnyValue::String(event.inner.typ.description().into()));
|
||||
record.set_timestamp(UNIX_EPOCH + Duration::from_secs(event.inner.timestamp));
|
||||
record.set_observed_timestamp(observed);
|
||||
|
||||
if let Some(span_id) = event.span_id().filter(|span_id| *span_id != 0) {
|
||||
record.set_trace_context((span_id as u128).into(), span_id.into(), None);
|
||||
}
|
||||
|
||||
let mut seen_keys = KeySet::default();
|
||||
for (k, v) in event.keys.iter().chain(
|
||||
event
|
||||
.inner
|
||||
.span
|
||||
.as_ref()
|
||||
.map_or(([]).iter(), |span| span.keys.iter()),
|
||||
) {
|
||||
if *k != trc::Key::SpanId && seen_keys.insert(*k) {
|
||||
record.add_attribute(k.as_str(), build_any_value(v));
|
||||
}
|
||||
}
|
||||
|
||||
record
|
||||
}
|
||||
}
|
||||
|
||||
fn build_key_value(key_value: &(trc::Key, trc::Value)) -> Option<KeyValue> {
|
||||
(key_value.0 != trc::Key::SpanId).then(|| {
|
||||
KeyValue::new(
|
||||
build_key(&key_value.0),
|
||||
match &key_value.1 {
|
||||
trc::Value::String(v) => Value::String(String::from(v.as_str()).into()),
|
||||
trc::Value::UInt(v) => Value::I64(*v as i64),
|
||||
trc::Value::Int(v) => Value::I64(*v),
|
||||
trc::Value::Float(v) => Value::F64(*v),
|
||||
trc::Value::Timestamp(v) => {
|
||||
Value::String(DateTime::from_timestamp(*v as i64).to_rfc3339().into())
|
||||
}
|
||||
trc::Value::Duration(v) => Value::I64(*v as i64),
|
||||
trc::Value::Bytes(_) => Value::String("[binary data]".into()),
|
||||
trc::Value::Bool(v) => Value::Bool(*v),
|
||||
trc::Value::Ipv4(v) => Value::String(v.to_string().into()),
|
||||
trc::Value::Ipv6(v) => Value::String(v.to_string().into()),
|
||||
trc::Value::Event(_) => Value::String("[event data]".into()),
|
||||
trc::Value::Array(_) => Value::String("[array]".into()),
|
||||
trc::Value::None => Value::Bool(false),
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn build_key(key: &trc::Key) -> Key {
|
||||
Key::from_static_str(key.as_str())
|
||||
}
|
||||
|
||||
fn build_any_value(value: &trc::Value) -> AnyValue {
|
||||
match value {
|
||||
trc::Value::String(v) => AnyValue::String(String::from(v.as_str()).into()),
|
||||
trc::Value::UInt(v) => AnyValue::Int(*v as i64),
|
||||
trc::Value::Int(v) => AnyValue::Int(*v),
|
||||
trc::Value::Float(v) => AnyValue::Double(*v),
|
||||
trc::Value::Timestamp(v) => {
|
||||
AnyValue::String(DateTime::from_timestamp(*v as i64).to_rfc3339().into())
|
||||
}
|
||||
trc::Value::Duration(v) => AnyValue::Int(*v as i64),
|
||||
trc::Value::Bytes(_) => AnyValue::String("[binary data]".into()),
|
||||
trc::Value::Bool(v) => AnyValue::Boolean(*v),
|
||||
trc::Value::Ipv4(v) => AnyValue::String(v.to_string().into()),
|
||||
trc::Value::Ipv6(v) => AnyValue::String(v.to_string().into()),
|
||||
trc::Value::Event(v) => AnyValue::Map(Box::new(
|
||||
[(
|
||||
Key::from_static_str("eventName"),
|
||||
AnyValue::String(v.event_type().as_str().into()),
|
||||
)]
|
||||
.into_iter()
|
||||
.chain(
|
||||
v.keys()
|
||||
.iter()
|
||||
.map(|(k, v)| (build_key(k), build_any_value(v))),
|
||||
)
|
||||
.collect(),
|
||||
)),
|
||||
trc::Value::Array(v) => {
|
||||
AnyValue::ListAny(Box::new(v.iter().map(build_any_value).collect()))
|
||||
}
|
||||
trc::Value::None => AnyValue::Boolean(false),
|
||||
pub(crate) fn spawn_otel_tracer(builder: SubscriberBuilder, tracer: OtelTracer) {
|
||||
if let Err(err) = tracer.spawn(builder) {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = "Failed to start the OpenTelemetry exporter",
|
||||
Reason = err.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,13 +8,7 @@
|
|||
*
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
config::telemetry::StoreTracer,
|
||||
telemetry::tracers::{
|
||||
TraceEvents,
|
||||
spans::{SpanTracker, report_discarded_spans, tracks_span},
|
||||
},
|
||||
};
|
||||
use crate::{config::telemetry::StoreTracer, telemetry::tracers::TraceEvents};
|
||||
use registry::{
|
||||
schema::structs::{
|
||||
Trace, TraceKeyValue, TraceValue, TraceValueIpAddr, TraceValueList, TraceValueString,
|
||||
|
|
@ -28,6 +22,7 @@ use store::{
|
|||
search::{IndexDocument, SearchField, SearchFilter, SearchQuery, TracingSearchField},
|
||||
write::{BatchBuilder, SearchIndex, TelemetryClass, ValueClass},
|
||||
};
|
||||
use telemetry::exporter::spans::{SpanTracker, report_discarded_spans, tracks_span};
|
||||
use trc::{
|
||||
AddContext, AuthEvent, EventType, Key, MessageIngestEvent, OutgoingReportEvent, QueueEvent,
|
||||
Value, ipc::subscriber::SubscriberBuilder,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "coordinator"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "dav-proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "dav"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "directory"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "email"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -608,6 +608,7 @@ impl EmailIngest for Server {
|
|||
|
||||
// Encrypt message
|
||||
let do_encrypt = match params.source {
|
||||
IngestSource::Jmap { .. } if params.keywords.contains(&Keyword::Draft) => false,
|
||||
IngestSource::Jmap { .. } | IngestSource::Imap { .. } => {
|
||||
self.core.email.encrypt
|
||||
&& self.core.email.encrypt_append
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "groupware"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::scheduling::ItipValue;
|
||||
use crate::scheduling::{ItipTimeKind, ItipValue};
|
||||
use calcard::{
|
||||
common::timezone::Tz,
|
||||
icalendar::{ICalendarDay, ICalendarFrequency, ICalendarRecurrenceRule, ICalendarWeekday},
|
||||
|
|
@ -30,6 +30,8 @@ pub struct TextFormatter {
|
|||
pub locale: &'static Locale,
|
||||
date_short: DateTimeFormatter<fieldsets::YMDT>,
|
||||
date_long: DateTimeFormatter<fieldsets::YMDT>,
|
||||
day_short: DateTimeFormatter<fieldsets::YMD>,
|
||||
day_long: DateTimeFormatter<fieldsets::YMD>,
|
||||
weekday_short: DateTimeFormatter<fieldsets::E>,
|
||||
weekday: DateTimeFormatter<fieldsets::E>,
|
||||
month: DateTimeFormatter<fieldsets::M>,
|
||||
|
|
@ -74,6 +76,10 @@ impl TextFormatter {
|
|||
fieldsets::YMD::long().with_time_hm(),
|
||||
)
|
||||
.map_err(failed("Failed to load long date formatter"))?,
|
||||
day_short: DateTimeFormatter::try_new(datetime_prefs, fieldsets::YMD::medium())
|
||||
.map_err(failed("Failed to load short day formatter"))?,
|
||||
day_long: DateTimeFormatter::try_new(datetime_prefs, fieldsets::YMD::long())
|
||||
.map_err(failed("Failed to load long day formatter"))?,
|
||||
weekday_short: DateTimeFormatter::try_new(datetime_prefs, fieldsets::E::short())
|
||||
.map_err(failed("Failed to load short weekday formatter"))?,
|
||||
weekday: DateTimeFormatter::try_new(datetime_prefs, fieldsets::E::long())
|
||||
|
|
@ -92,22 +98,25 @@ impl TextFormatter {
|
|||
ItipValue::Text(text) => out.push_str(text),
|
||||
ItipValue::Time(time) => {
|
||||
let tz = Tz::from_id(time.tz_id).unwrap_or(Tz::UTC);
|
||||
let (weekday, date) = match style {
|
||||
DateStyle::Short => (&self.weekday_short, &self.date_short),
|
||||
DateStyle::Long => (&self.weekday, &self.date_long),
|
||||
let (weekday, date, day) = match style {
|
||||
DateStyle::Short => (&self.weekday_short, &self.date_short, &self.day_short),
|
||||
DateStyle::Long => (&self.weekday, &self.date_long, &self.day_long),
|
||||
};
|
||||
let local = tz
|
||||
.from_timestamp(Timestamp::from_second(time.start).unwrap_or_default())
|
||||
.naive_local();
|
||||
let _ = write!(
|
||||
out,
|
||||
"{}, {}",
|
||||
weekday.format(&local.date()),
|
||||
date.format(&local)
|
||||
);
|
||||
|
||||
if let Some(name) = tz.name().filter(|name| !name.is_empty()) {
|
||||
let _ = write!(out, " ({name})");
|
||||
let local_date = local.date();
|
||||
let _ = write!(out, "{}, ", weekday.format(&local_date));
|
||||
match time.kind {
|
||||
ItipTimeKind::DateTime => {
|
||||
let _ = write!(out, "{}", date.format(&local));
|
||||
if let Some(name) = tz.name().filter(|name| !name.is_empty()) {
|
||||
let _ = write!(out, " ({name})");
|
||||
}
|
||||
}
|
||||
ItipTimeKind::Date => {
|
||||
let _ = write!(out, "{}", day.format(&local_date));
|
||||
}
|
||||
}
|
||||
}
|
||||
ItipValue::Rrule(rrule) => self.recurrence(out, rrule),
|
||||
|
|
|
|||
|
|
@ -459,6 +459,7 @@ pub(crate) fn can_attendee_modify_property(
|
|||
| ICalendarProperty::Summary
|
||||
| ICalendarProperty::Description
|
||||
| ICalendarProperty::Comment
|
||||
| ICalendarProperty::Priority
|
||||
)
|
||||
}
|
||||
ICalendarComponentType::VTodo => matches!(
|
||||
|
|
@ -470,6 +471,7 @@ pub(crate) fn can_attendee_modify_property(
|
|||
| ICalendarProperty::PercentComplete
|
||||
| ICalendarProperty::Completed
|
||||
| ICalendarProperty::Comment
|
||||
| ICalendarProperty::Priority
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -198,6 +198,27 @@ pub enum ItipValue {
|
|||
pub struct ItipTime {
|
||||
pub start: i64,
|
||||
pub tz_id: u16,
|
||||
#[serde(default)]
|
||||
pub kind: ItipTimeKind,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Debug, Clone, Copy, Default, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize,
|
||||
)]
|
||||
pub enum ItipTimeKind {
|
||||
#[default]
|
||||
DateTime,
|
||||
Date,
|
||||
}
|
||||
|
||||
impl ItipTimeKind {
|
||||
pub fn of(date: &PartialDateTime) -> Self {
|
||||
if date.has_time() {
|
||||
ItipTimeKind::DateTime
|
||||
} else {
|
||||
ItipTimeKind::Date
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::scheduling::{ItipTime, itip::itip_date_entry};
|
||||
use crate::scheduling::{ItipTime, ItipTimeKind, itip::itip_date_entry};
|
||||
use calcard::{
|
||||
common::{
|
||||
PartialDateTime,
|
||||
|
|
@ -96,10 +96,12 @@ impl<'x> Series<'x> {
|
|||
.values
|
||||
.first()
|
||||
.and_then(|value| value.as_partial_date_time())
|
||||
.and_then(|date| date.to_date_time_with_tz(tz))
|
||||
.map(|date| ItipTime {
|
||||
start: date.timestamp(),
|
||||
tz_id: tz.as_id(),
|
||||
.and_then(|date| {
|
||||
date.to_date_time_with_tz(tz).map(|start| ItipTime {
|
||||
start: start.timestamp(),
|
||||
tz_id: tz.as_id(),
|
||||
kind: ItipTimeKind::of(date),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@
|
|||
use crate::calendar::expand::SECONDS_PER_DAY;
|
||||
use crate::scheduling::{
|
||||
Attendee, Email, InstanceId, ItipDateTime, ItipEntry, ItipEntryValue, ItipError, ItipField,
|
||||
ItipParticipant, ItipSnapshot, ItipSnapshots, ItipTime, ItipValue, Organizer, RecurrenceId,
|
||||
ItipParticipant, ItipSnapshot, ItipSnapshots, ItipTime, ItipTimeKind, ItipValue, Organizer,
|
||||
RecurrenceId,
|
||||
};
|
||||
use ahash::AHashMap;
|
||||
use calcard::icalendar::{
|
||||
|
|
@ -281,6 +282,7 @@ pub fn itip_snapshot<'x, 'y>(
|
|||
sched_comp.recurrence_time = Some(ItipTime {
|
||||
start,
|
||||
tz_id: tz.as_id(),
|
||||
kind: ItipTimeKind::of(date),
|
||||
});
|
||||
instance_id = InstanceId::Recurrence(RecurrenceId {
|
||||
entry_id: entry_id as u16,
|
||||
|
|
@ -451,7 +453,7 @@ impl<'x> ItipSnapshots<'x> {
|
|||
.and_then(ItipSnapshot::start_time)
|
||||
.map(|master_start| ItipTime {
|
||||
start: recurrence_id.date,
|
||||
tz_id: master_start.tz_id,
|
||||
..master_start
|
||||
})
|
||||
}),
|
||||
}
|
||||
|
|
@ -659,6 +661,7 @@ impl<'x> ItipSnapshot<'x> {
|
|||
(ICalendarProperty::Dtstart, ItipEntryValue::DateTime(start)) => Some(ItipTime {
|
||||
start: start.timestamp,
|
||||
tz_id: start.tz_code,
|
||||
kind: ItipTimeKind::of(start.date),
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
|
|
@ -706,6 +709,7 @@ impl ItipEntryValue<'_> {
|
|||
ItipEntryValue::DateTime(date) => Some(ItipValue::Time(ItipTime {
|
||||
start: date.timestamp,
|
||||
tz_id: date.tz_code,
|
||||
kind: ItipTimeKind::of(date.date),
|
||||
})),
|
||||
ItipEntryValue::RRule(rule) => Some(ItipValue::Rrule(Box::new((*rule).clone()))),
|
||||
ItipEntryValue::Text(value) => Some(ItipValue::Text(value.to_string())),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "http_proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "http"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
@ -8,6 +8,7 @@ store = { path = "../store" }
|
|||
common = { path = "../common" }
|
||||
utils = { path = "../utils" }
|
||||
trc = { path = "../trc" }
|
||||
telemetry = { path = "../telemetry" }
|
||||
email = { path = "../email" }
|
||||
smtp = { path = "../smtp" }
|
||||
jmap = { path = "../jmap" }
|
||||
|
|
@ -41,6 +42,7 @@ compact_str = "0.10.0"
|
|||
|
||||
[dev-dependencies]
|
||||
flate2 = "1.1"
|
||||
jmap-tools = { path = "../jmap-tools" }
|
||||
|
||||
[features]
|
||||
dev_mode = []
|
||||
|
|
|
|||
|
|
@ -431,3 +431,8 @@ impl UnauthorizedResponse for HttpResponse {
|
|||
.with_text_body(serde_json::to_string(&RequestError::unauthorized()).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/http/src/api/tests.rs"]
|
||||
mod tests;
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ use super::{
|
|||
DeviceAuthResponse, ErrorType, FormData, MAX_POST_LEN, OAuthCode, PkceCodeChallenge,
|
||||
TokenResponse,
|
||||
authorize::{
|
||||
AuthorizationError, granted_scope, is_resource_path, issuer, resource_origin, scope_labels,
|
||||
validate_authorization,
|
||||
Authorization, AuthorizationError, granted_scope, is_resource_path, issuer,
|
||||
resource_origin, scope_labels, validate_authorization,
|
||||
},
|
||||
logout::END_SESSION_PATH,
|
||||
request_origin,
|
||||
|
|
@ -37,7 +37,7 @@ use hyper::{StatusCode, body::Bytes};
|
|||
use registry::schema::enums::OAuthGrantType;
|
||||
use std::{borrow::Cow, future::Future};
|
||||
use store::{
|
||||
Serialize,
|
||||
Serialize, blake3,
|
||||
dispatch::lookup::KeyValue,
|
||||
write::{Archive, Archiver},
|
||||
};
|
||||
|
|
@ -150,6 +150,12 @@ pub enum LoginRequest {
|
|||
#[serde(default)]
|
||||
consent: Option<bool>,
|
||||
},
|
||||
#[serde(rename_all = "camelCase")]
|
||||
AuthConsent {
|
||||
token: String,
|
||||
query: String,
|
||||
consent: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
|
||||
|
|
@ -169,6 +175,9 @@ pub enum LoginResponse {
|
|||
Verified,
|
||||
Denied,
|
||||
MfaRequired,
|
||||
ConsentRequired {
|
||||
token: String,
|
||||
},
|
||||
Expired,
|
||||
Failure,
|
||||
}
|
||||
|
|
@ -183,7 +192,6 @@ pub struct ClientInfo {
|
|||
pub scopes: Vec<&'static str>,
|
||||
pub verified: bool,
|
||||
pub consent_required: bool,
|
||||
pub deny_location: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, PartialEq, Eq)]
|
||||
|
|
@ -254,95 +262,26 @@ impl OAuthApiHandler for Server {
|
|||
query,
|
||||
consent,
|
||||
} => {
|
||||
let issuer = issuer(self, origin);
|
||||
let authorization = match validate_authorization(
|
||||
self,
|
||||
&query,
|
||||
&ResolveContext {
|
||||
mode: ResolveMode::Authorize,
|
||||
origin: Some(origin),
|
||||
remote_ip: session.remote_ip,
|
||||
},
|
||||
&issuer,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Ok(authorization) => authorization,
|
||||
Err(AuthorizationError::Invalid { error, description }) => {
|
||||
return Ok(JsonResponse::new(LoginResponse::Invalid {
|
||||
error,
|
||||
description: description.into(),
|
||||
})
|
||||
.no_cache()
|
||||
.into_http_response());
|
||||
}
|
||||
Err(AuthorizationError::Redirect { location }) => {
|
||||
return Ok(JsonResponse::new(LoginResponse::Redirect { location })
|
||||
.no_cache()
|
||||
.into_http_response());
|
||||
}
|
||||
};
|
||||
|
||||
if authorization.client.requires_consent() && consent != Some(true) {
|
||||
LoginResponse::Redirect {
|
||||
location: authorization.error_location(ErrorType::AccessDenied, &issuer),
|
||||
}
|
||||
} else {
|
||||
match authenticate_login(
|
||||
self,
|
||||
session,
|
||||
&authorization.client,
|
||||
self.authorize_code(
|
||||
session,
|
||||
origin,
|
||||
LoginCredentials {
|
||||
account_name,
|
||||
account_secret,
|
||||
mfa_token,
|
||||
)
|
||||
},
|
||||
&query,
|
||||
consent,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
LoginRequest::AuthConsent {
|
||||
token,
|
||||
query,
|
||||
consent,
|
||||
} => {
|
||||
self.confirm_consent(session, origin, &token, &query, consent)
|
||||
.await?
|
||||
{
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
Ok(login) if !authorization.client.allows_tenant(login.tenant_id) => {
|
||||
LoginResponse::Redirect {
|
||||
location: authorization
|
||||
.error_location(ErrorType::AccessDenied, &issuer),
|
||||
}
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
Ok(login) => {
|
||||
let client_code = rng()
|
||||
.sample_iter(Alphanumeric)
|
||||
.take(DEVICE_CODE_LEN)
|
||||
.map(char::from)
|
||||
.collect::<String>();
|
||||
let location = authorization.code_location(&client_code, &issuer);
|
||||
|
||||
let value = Archiver::new(OAuthCode {
|
||||
status: OAuthStatus::Authorized,
|
||||
account_id: login.account_id,
|
||||
credential_version: login.credential_version,
|
||||
client_id: authorization.client_id,
|
||||
nonce: authorization.nonce,
|
||||
params: authorization.redirect_uri,
|
||||
code_challenge: authorization.code_challenge,
|
||||
scope: authorization.scope,
|
||||
})
|
||||
.untrusted()
|
||||
.serialize()
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
self.in_memory_store()
|
||||
.key_set(
|
||||
KeyValue::with_prefix(KV_OAUTH, client_code.as_bytes(), value)
|
||||
.expires(self.core.oauth.oauth_expiry_auth_code),
|
||||
)
|
||||
.await?;
|
||||
|
||||
LoginResponse::Authenticated { location }
|
||||
}
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
}
|
||||
LoginRequest::AuthDevice {
|
||||
account_name,
|
||||
|
|
@ -409,9 +348,6 @@ impl OAuthApiHandler for Server {
|
|||
scopes: authorization.scope_labels(),
|
||||
verified: client.is_verified(),
|
||||
consent_required: client.requires_consent(),
|
||||
deny_location: Some(
|
||||
authorization.error_location(ErrorType::AccessDenied, &issuer),
|
||||
),
|
||||
})
|
||||
}
|
||||
Err(AuthorizationError::Invalid { error, description }) => {
|
||||
|
|
@ -645,7 +581,6 @@ async fn device_client_info(
|
|||
scopes: scope_labels(&client, oauth.scope.as_ref().map(|scope| scope.as_str())),
|
||||
verified: client.is_verified(),
|
||||
consent_required: true,
|
||||
deny_location: None,
|
||||
})),
|
||||
_ => Ok(None),
|
||||
}
|
||||
|
|
@ -718,6 +653,305 @@ async fn authenticate_login(
|
|||
}
|
||||
}
|
||||
|
||||
struct LoginCredentials {
|
||||
account_name: String,
|
||||
account_secret: String,
|
||||
mfa_token: Option<String>,
|
||||
}
|
||||
|
||||
trait ConsentHandler: Sync + Send {
|
||||
fn validate_login_query(
|
||||
&self,
|
||||
session: &HttpSessionData,
|
||||
origin: RequestOrigin<'_>,
|
||||
query: &str,
|
||||
issuer: &str,
|
||||
) -> impl Future<Output = trc::Result<Result<Authorization, LoginResponse>>> + Send;
|
||||
|
||||
fn authorize_code(
|
||||
&self,
|
||||
session: &HttpSessionData,
|
||||
origin: RequestOrigin<'_>,
|
||||
credentials: LoginCredentials,
|
||||
query: &str,
|
||||
consent: Option<bool>,
|
||||
) -> impl Future<Output = trc::Result<LoginResponse>> + Send;
|
||||
|
||||
fn request_consent(
|
||||
&self,
|
||||
authorization: Authorization,
|
||||
login: &LoginAccount,
|
||||
query: &str,
|
||||
) -> impl Future<Output = trc::Result<LoginResponse>> + Send;
|
||||
|
||||
fn confirm_consent(
|
||||
&self,
|
||||
session: &HttpSessionData,
|
||||
origin: RequestOrigin<'_>,
|
||||
token: &str,
|
||||
query: &str,
|
||||
consent: bool,
|
||||
) -> impl Future<Output = trc::Result<LoginResponse>> + Send;
|
||||
|
||||
fn take_pending_consent(
|
||||
&self,
|
||||
token: &str,
|
||||
query: &str,
|
||||
) -> impl Future<Output = trc::Result<Option<(u32, u64)>>> + Send;
|
||||
|
||||
fn issue_auth_code(
|
||||
&self,
|
||||
authorization: Authorization,
|
||||
account_id: u32,
|
||||
credential_version: u64,
|
||||
issuer: &str,
|
||||
) -> impl Future<Output = trc::Result<LoginResponse>> + Send;
|
||||
}
|
||||
|
||||
impl ConsentHandler for Server {
|
||||
async fn validate_login_query(
|
||||
&self,
|
||||
session: &HttpSessionData,
|
||||
origin: RequestOrigin<'_>,
|
||||
query: &str,
|
||||
issuer: &str,
|
||||
) -> trc::Result<Result<Authorization, LoginResponse>> {
|
||||
validate_authorization(
|
||||
self,
|
||||
query,
|
||||
&ResolveContext {
|
||||
mode: ResolveMode::Authorize,
|
||||
origin: Some(origin),
|
||||
remote_ip: session.remote_ip,
|
||||
},
|
||||
issuer,
|
||||
)
|
||||
.await
|
||||
.map(|result| {
|
||||
result.map_err(|err| match err {
|
||||
AuthorizationError::Invalid { error, description } => LoginResponse::Invalid {
|
||||
error,
|
||||
description: description.into(),
|
||||
},
|
||||
AuthorizationError::Redirect { location } => LoginResponse::Redirect { location },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async fn authorize_code(
|
||||
&self,
|
||||
session: &HttpSessionData,
|
||||
origin: RequestOrigin<'_>,
|
||||
credentials: LoginCredentials,
|
||||
query: &str,
|
||||
consent: Option<bool>,
|
||||
) -> trc::Result<LoginResponse> {
|
||||
let issuer = issuer(self, origin);
|
||||
let authorization = match self
|
||||
.validate_login_query(session, origin, query, &issuer)
|
||||
.await?
|
||||
{
|
||||
Ok(authorization) => authorization,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
let login = match authenticate_login(
|
||||
self,
|
||||
session,
|
||||
&authorization.client,
|
||||
credentials.account_name,
|
||||
credentials.account_secret,
|
||||
credentials.mfa_token,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Ok(login) => login,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
if !authorization.client.allows_tenant(login.tenant_id) {
|
||||
return Ok(LoginResponse::Redirect {
|
||||
location: authorization.error_location(ErrorType::AccessDenied, &issuer),
|
||||
});
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
match consent {
|
||||
Some(true) => {}
|
||||
Some(false) => {
|
||||
return Ok(LoginResponse::Redirect {
|
||||
location: authorization.error_location(ErrorType::AccessDenied, &issuer),
|
||||
});
|
||||
}
|
||||
None if !authorization.client.requires_consent() => {}
|
||||
None if !authorization.prompt_consent
|
||||
&& self
|
||||
.has_oauth_grant(
|
||||
login.account_id,
|
||||
&authorization.client_id,
|
||||
authorization.client.kind(),
|
||||
authorization.consent_scopes(),
|
||||
)
|
||||
.await? => {}
|
||||
None => {
|
||||
return self.request_consent(authorization, &login, query).await;
|
||||
}
|
||||
}
|
||||
|
||||
self.issue_auth_code(
|
||||
authorization,
|
||||
login.account_id,
|
||||
login.credential_version,
|
||||
&issuer,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn request_consent(
|
||||
&self,
|
||||
authorization: Authorization,
|
||||
login: &LoginAccount,
|
||||
query: &str,
|
||||
) -> trc::Result<LoginResponse> {
|
||||
let token = rng()
|
||||
.sample_iter(Alphanumeric)
|
||||
.take(DEVICE_CODE_LEN)
|
||||
.map(char::from)
|
||||
.collect::<String>();
|
||||
let value = Archiver::new(OAuthCode {
|
||||
status: OAuthStatus::ConsentPending,
|
||||
account_id: login.account_id,
|
||||
credential_version: login.credential_version,
|
||||
client_id: authorization.client_id,
|
||||
nonce: None,
|
||||
params: query_digest(query).to_hex().to_string(),
|
||||
code_challenge: PkceCodeChallenge::None,
|
||||
scope: None,
|
||||
})
|
||||
.untrusted()
|
||||
.serialize()
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
self.in_memory_store()
|
||||
.key_set(
|
||||
KeyValue::with_prefix(KV_OAUTH, token.as_bytes(), value)
|
||||
.expires(self.core.oauth.oauth_expiry_auth_code),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(LoginResponse::ConsentRequired { token })
|
||||
}
|
||||
|
||||
async fn confirm_consent(
|
||||
&self,
|
||||
session: &HttpSessionData,
|
||||
origin: RequestOrigin<'_>,
|
||||
token: &str,
|
||||
query: &str,
|
||||
consent: bool,
|
||||
) -> trc::Result<LoginResponse> {
|
||||
let Some((account_id, credential_version)) =
|
||||
self.take_pending_consent(token, query).await?
|
||||
else {
|
||||
return Ok(LoginResponse::Invalid {
|
||||
error: ErrorType::InvalidRequest,
|
||||
description: "The sign-in has expired. Please start again from the application."
|
||||
.into(),
|
||||
});
|
||||
};
|
||||
let issuer = issuer(self, origin);
|
||||
let authorization = match self
|
||||
.validate_login_query(session, origin, query, &issuer)
|
||||
.await?
|
||||
{
|
||||
Ok(authorization) => authorization,
|
||||
Err(response) => return Ok(response),
|
||||
};
|
||||
|
||||
if consent {
|
||||
self.issue_auth_code(authorization, account_id, credential_version, &issuer)
|
||||
.await
|
||||
} else {
|
||||
Ok(LoginResponse::Redirect {
|
||||
location: authorization.error_location(ErrorType::AccessDenied, &issuer),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn take_pending_consent(
|
||||
&self,
|
||||
token: &str,
|
||||
query: &str,
|
||||
) -> trc::Result<Option<(u32, u64)>> {
|
||||
if token.len() != DEVICE_CODE_LEN || !token.bytes().all(|ch| ch.is_ascii_alphanumeric()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let key = KeyValue::<()>::build_key(KV_OAUTH, token.as_bytes());
|
||||
let Some(stored) = self
|
||||
.in_memory_store()
|
||||
.key_get::<Archive<ArchiveBytes>>(key.as_slice())
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let pending = stored
|
||||
.unarchive::<OAuthCode>()
|
||||
.caused_by(trc::location!())?;
|
||||
if pending.status != OAuthStatus::ConsentPending
|
||||
|| pending.params != query_digest(query).to_hex().as_str()
|
||||
|| !self.in_memory_store().key_delete(key.as_slice()).await?
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(Some((
|
||||
pending.account_id.into(),
|
||||
pending.credential_version.into(),
|
||||
)))
|
||||
}
|
||||
|
||||
async fn issue_auth_code(
|
||||
&self,
|
||||
authorization: Authorization,
|
||||
account_id: u32,
|
||||
credential_version: u64,
|
||||
issuer: &str,
|
||||
) -> trc::Result<LoginResponse> {
|
||||
let client_code = rng()
|
||||
.sample_iter(Alphanumeric)
|
||||
.take(DEVICE_CODE_LEN)
|
||||
.map(char::from)
|
||||
.collect::<String>();
|
||||
let location = authorization.code_location(&client_code, issuer);
|
||||
|
||||
let value = Archiver::new(OAuthCode {
|
||||
status: OAuthStatus::Authorized,
|
||||
account_id,
|
||||
credential_version,
|
||||
client_id: authorization.client_id,
|
||||
nonce: authorization.nonce,
|
||||
params: authorization.redirect_uri,
|
||||
code_challenge: authorization.code_challenge,
|
||||
scope: authorization.scope,
|
||||
})
|
||||
.untrusted()
|
||||
.serialize()
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
self.in_memory_store()
|
||||
.key_set(
|
||||
KeyValue::with_prefix(KV_OAUTH, client_code.as_bytes(), value)
|
||||
.expires(self.core.oauth.oauth_expiry_auth_code),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(LoginResponse::Authenticated { location })
|
||||
}
|
||||
}
|
||||
|
||||
async fn approve_device(
|
||||
server: &Server,
|
||||
session: &HttpSessionData,
|
||||
|
|
@ -835,6 +1069,10 @@ async fn approve_device(
|
|||
Ok(response)
|
||||
}
|
||||
|
||||
fn query_digest(query: &str) -> blake3::Hash {
|
||||
blake3::hash(query.as_bytes())
|
||||
}
|
||||
|
||||
fn is_user_code(code: &str) -> bool {
|
||||
code.len() == USER_CODE_LEN + 1
|
||||
&& code.bytes().enumerate().all(|(pos, ch)| {
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ pub struct Authorization {
|
|||
pub nonce: Option<String>,
|
||||
pub scope: Option<String>,
|
||||
pub code_challenge: PkceCodeChallenge,
|
||||
pub prompt_consent: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
|
@ -57,6 +58,7 @@ enum Param {
|
|||
CodeChallenge,
|
||||
CodeChallengeMethod,
|
||||
Resource,
|
||||
Prompt,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
|
|
@ -69,6 +71,7 @@ struct AuthorizationQuery<'x> {
|
|||
nonce: Option<Cow<'x, str>>,
|
||||
code_challenge: Option<Cow<'x, str>>,
|
||||
code_challenge_method: Option<Cow<'x, str>>,
|
||||
prompt: Option<Cow<'x, str>>,
|
||||
resources: Vec<Cow<'x, str>>,
|
||||
duplicates: u16,
|
||||
too_many_resources: bool,
|
||||
|
|
@ -88,6 +91,7 @@ impl Param {
|
|||
"code_challenge" => Param::CodeChallenge,
|
||||
"code_challenge_method" => Param::CodeChallengeMethod,
|
||||
"resource" => Param::Resource,
|
||||
"prompt" => Param::Prompt,
|
||||
)
|
||||
.copied()
|
||||
}
|
||||
|
|
@ -121,6 +125,7 @@ impl<'x> AuthorizationQuery<'x> {
|
|||
Param::Nonce => &mut parsed.nonce,
|
||||
Param::CodeChallenge => &mut parsed.code_challenge,
|
||||
Param::CodeChallengeMethod => &mut parsed.code_challenge_method,
|
||||
Param::Prompt => &mut parsed.prompt,
|
||||
};
|
||||
if slot.is_some() {
|
||||
parsed.duplicates |= param.bit();
|
||||
|
|
@ -279,6 +284,11 @@ pub async fn validate_authorization(
|
|||
nonce: query.nonce.map(Cow::into_owned),
|
||||
scope,
|
||||
code_challenge,
|
||||
prompt_consent: query.prompt.as_deref().is_some_and(|prompt| {
|
||||
prompt
|
||||
.split_ascii_whitespace()
|
||||
.any(|value| value == "consent")
|
||||
}),
|
||||
client,
|
||||
}))
|
||||
}
|
||||
|
|
@ -295,6 +305,14 @@ impl Authorization {
|
|||
)
|
||||
}
|
||||
|
||||
pub fn consent_scopes(&self) -> OAuthScopes {
|
||||
if self.client.allowed_scopes().is_some() {
|
||||
OAuthScopes::parse(self.scope.as_deref().unwrap_or_default()).interoperable()
|
||||
} else {
|
||||
OAuthScopes::NONE
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scope_labels(&self) -> Vec<&'static str> {
|
||||
scope_labels(&self.client, self.scope.as_deref())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ pub enum OAuthStatus {
|
|||
TokenIssued,
|
||||
Pending,
|
||||
Denied,
|
||||
ConsentPending,
|
||||
}
|
||||
|
||||
const MAX_POST_LEN: usize = 2048;
|
||||
|
|
|
|||
|
|
@ -397,6 +397,9 @@ impl TokenHandler for Server {
|
|||
}
|
||||
ArchivedOAuthStatus::Denied => Ok(TokenResponse::error(ErrorType::AccessDenied)),
|
||||
ArchivedOAuthStatus::TokenIssued => Ok(TokenResponse::error(ErrorType::ExpiredToken)),
|
||||
ArchivedOAuthStatus::ConsentPending => {
|
||||
Ok(TokenResponse::error(ErrorType::InvalidGrant))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ use crate::{
|
|||
use common::{
|
||||
BuildServer, Inner, KV_ACME, Server,
|
||||
auth::oauth::{client::RequestOrigin, scope::OAuthScopes},
|
||||
config::telemetry::PrometheusAuth,
|
||||
ipc::PushEvent,
|
||||
manager::{
|
||||
app_client::APP_CLIENT_DOCUMENT,
|
||||
|
|
@ -72,6 +73,7 @@ use percent_encoding::percent_decode_str;
|
|||
use registry::schema::enums::Permission;
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
use store::dispatch::lookup::KeyValue;
|
||||
use telemetry::prometheus::negotiate::negotiate;
|
||||
use trc::SecurityEvent;
|
||||
use types::{blob::BlobId, id::Id};
|
||||
|
||||
|
|
@ -693,18 +695,28 @@ impl ParseHttp for Server {
|
|||
"metrics" => match path.next().unwrap_or_default() {
|
||||
"prometheus" => {
|
||||
if let Some(prometheus) = &self.core.metrics.prometheus {
|
||||
if !prometheus.auth.is_authorized(req.authorization_basic()) {
|
||||
if req.method() != Method::GET {
|
||||
return Ok(HttpResponse::new(StatusCode::METHOD_NOT_ALLOWED)
|
||||
.with_header(header::ALLOW, "GET"));
|
||||
}
|
||||
if matches!(prometheus.auth, PrometheusAuth::None) {
|
||||
self.is_http_anonymous_request_allowed(session.remote_ip)
|
||||
.await?;
|
||||
} else if !prometheus.auth.is_authorized(req.authorization_basic()) {
|
||||
return Err(trc::AuthEvent::Failed
|
||||
.into_err()
|
||||
.details("Invalid or missing credentials.")
|
||||
.caused_by(trc::location!()));
|
||||
}
|
||||
|
||||
return Ok(Resource::new(
|
||||
"text/plain; version=0.0.4",
|
||||
self.export_prometheus_metrics().await?.into_bytes(),
|
||||
)
|
||||
.into_http_response());
|
||||
let format = negotiate(
|
||||
req.headers()
|
||||
.get(header::ACCEPT)
|
||||
.map(|value| value.as_bytes()),
|
||||
);
|
||||
return Ok(HttpResponse::new(StatusCode::OK)
|
||||
.with_content_type(format.content_type())
|
||||
.with_binary_body(self.export_prometheus_metrics(prometheus, format)));
|
||||
}
|
||||
}
|
||||
"otel" => {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "imap_proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "imap"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "jmap_proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -223,13 +223,26 @@ impl<T: JmapObject> SetResponse<T> {
|
|||
}
|
||||
|
||||
pub fn created(&mut self, id: String, document_id: impl Into<T::Id>) {
|
||||
self.created.insert(
|
||||
id,
|
||||
Value::Object(Map::from(vec![(
|
||||
Key::Property(T::ID_PROPERTY),
|
||||
Value::Element(document_id.into().into()),
|
||||
)])),
|
||||
self.created_with_properties(id, document_id, []);
|
||||
}
|
||||
|
||||
pub fn created_with_properties(
|
||||
&mut self,
|
||||
id: String,
|
||||
document_id: impl Into<T::Id>,
|
||||
properties: impl IntoIterator<Item = (T::Property, Value<'static, T::Property, T::Element>)>,
|
||||
) {
|
||||
let properties = properties.into_iter();
|
||||
let (lower, upper) = properties.size_hint();
|
||||
let mut object = Map::with_capacity(upper.unwrap_or(lower) + 1);
|
||||
object.insert_unchecked(
|
||||
Key::Property(T::ID_PROPERTY),
|
||||
Value::Element(document_id.into().into()),
|
||||
);
|
||||
for (property, value) in properties {
|
||||
object.insert(property, value);
|
||||
}
|
||||
self.created.insert(id, Value::Object(object));
|
||||
}
|
||||
|
||||
pub fn invalid_property_create(
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "jmap-tools"
|
||||
description = "JMAP object parser with JSON Pointer querying and patching support"
|
||||
version = "0.1.9"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "jmap"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ use registry::schema::enums::StorageQuota;
|
|||
use store::{
|
||||
ValueKey,
|
||||
ahash::AHashSet,
|
||||
write::{Archive, ArchiveBytes, BatchBuilder, PendingId},
|
||||
write::{Archive, ArchiveBytes, BatchBuilder, PendingId, ValueClass},
|
||||
};
|
||||
use trc::AddContext;
|
||||
use types::{
|
||||
|
|
@ -46,6 +46,55 @@ use types::{
|
|||
id::Id,
|
||||
};
|
||||
|
||||
const DEFAULT_NAME: &str = "Address Book";
|
||||
|
||||
type CreatedValue = Value<'static, AddressBookProperty, AddressBookValue>;
|
||||
|
||||
const DEFAULTED: [AddressBookProperty; 5] = [
|
||||
AddressBookProperty::Name,
|
||||
AddressBookProperty::Description,
|
||||
AddressBookProperty::SortOrder,
|
||||
AddressBookProperty::IsSubscribed,
|
||||
AddressBookProperty::ShareWith,
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Omitted([bool; DEFAULTED.len()]);
|
||||
|
||||
impl Omitted {
|
||||
fn from_create(object: &Value<'_, AddressBookProperty, AddressBookValue>) -> Self {
|
||||
Omitted(
|
||||
DEFAULTED.map(|property| object.as_object_and_get(&Key::Property(property)).is_none()),
|
||||
)
|
||||
}
|
||||
|
||||
fn server_set(
|
||||
self,
|
||||
is_default: bool,
|
||||
) -> impl Iterator<Item = (AddressBookProperty, CreatedValue)> {
|
||||
[
|
||||
(AddressBookProperty::Name, Value::Str(DEFAULT_NAME.into())),
|
||||
(AddressBookProperty::Description, Value::Null),
|
||||
(AddressBookProperty::SortOrder, Value::Number(0u64.into())),
|
||||
(AddressBookProperty::IsSubscribed, Value::Bool(false)),
|
||||
(
|
||||
AddressBookProperty::ShareWith,
|
||||
JmapRights::grants_value::<addressbook::AddressBook>(&[]),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.zip(self.0)
|
||||
.filter_map(|(entry, is_omitted)| is_omitted.then_some(entry))
|
||||
.chain([
|
||||
(
|
||||
AddressBookProperty::MyRights,
|
||||
JmapRights::all_rights::<addressbook::AddressBook>(),
|
||||
),
|
||||
(AddressBookProperty::IsDefault, Value::Bool(is_default)),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
pub trait AddressBookSet: Sync + Send {
|
||||
fn address_book_set(
|
||||
&self,
|
||||
|
|
@ -81,6 +130,7 @@ impl AddressBookSet for Server {
|
|||
let is_shared = access_token.is_shared(account_id);
|
||||
let mut set_default: Option<PendingId> = None;
|
||||
let mut created_slots = PendingCreates::new();
|
||||
let mut created_omitted = Vec::new();
|
||||
|
||||
// Obtain quota
|
||||
let quota = if request.has_creates() && !is_shared {
|
||||
|
|
@ -123,7 +173,7 @@ impl AddressBookSet for Server {
|
|||
.collect::<String>(),
|
||||
preferences: vec![AddressBookPreferences {
|
||||
account_id,
|
||||
name: "Address Book".to_string(),
|
||||
name: DEFAULT_NAME.to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
|
|
@ -138,6 +188,7 @@ impl AddressBookSet for Server {
|
|||
continue 'create;
|
||||
}
|
||||
};
|
||||
let omitted = Omitted::from_create(&object);
|
||||
if let Err(err) =
|
||||
update_address_book(None, object, &mut address_book, access_token, account_id)
|
||||
{
|
||||
|
|
@ -215,6 +266,7 @@ impl AddressBookSet for Server {
|
|||
set_default = Some(PendingId::Slot(document_id));
|
||||
}
|
||||
|
||||
created_omitted.push((id.clone(), document_id, omitted));
|
||||
created_slots.push(id, document_id);
|
||||
}
|
||||
|
||||
|
|
@ -604,7 +656,7 @@ impl AddressBookSet for Server {
|
|||
.with_account_id(account_id)
|
||||
.with_collection(Collection::Principal)
|
||||
.with_document(0);
|
||||
for document_id in destroyed_books {
|
||||
for &document_id in &destroyed_books {
|
||||
batch.clear_if_equals(PrincipalField::DefaultAddressBookId, document_id);
|
||||
}
|
||||
}
|
||||
|
|
@ -625,6 +677,36 @@ impl AddressBookSet for Server {
|
|||
};
|
||||
|
||||
created_slots.resolve(&mut response, &assigned_ids);
|
||||
let default_address_book_id = if created_omitted.is_empty() {
|
||||
None
|
||||
} else {
|
||||
self.store()
|
||||
.get_value::<u32>(ValueKey {
|
||||
account_id,
|
||||
collection: Collection::Principal.into(),
|
||||
document_id: 0,
|
||||
class: ValueClass::Property(PrincipalField::DefaultAddressBookId.into()),
|
||||
})
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.or_else(|| {
|
||||
cache
|
||||
.document_ids(true)
|
||||
.filter(|id| !destroyed_books.contains(id))
|
||||
.chain(
|
||||
created_omitted
|
||||
.iter()
|
||||
.map(|(_, slot, _)| assigned_ids.slot(*slot)),
|
||||
)
|
||||
.min()
|
||||
})
|
||||
};
|
||||
for (create_id, slot, omitted) in created_omitted {
|
||||
response.add_created_properties(
|
||||
&create_id,
|
||||
omitted.server_set(default_address_book_id == Some(assigned_ids.slot(slot))),
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(change_id) = assigned_ids.change_id(account_id, SyncCollection::AddressBook)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1354,6 +1354,13 @@ impl CalendarServerSet for Calendar {
|
|||
CalendarProperty::MyRights,
|
||||
JmapRights::all_rights::<calendar::Calendar>(),
|
||||
),
|
||||
(CalendarProperty::Description, Value::Null),
|
||||
(CalendarProperty::Color, Value::Null),
|
||||
(CalendarProperty::TimeZone, Value::Null),
|
||||
(
|
||||
CalendarProperty::ShareWith,
|
||||
JmapRights::grants_value::<calendar::Calendar>(&[]),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(property, _)| !client_properties.contains(property))
|
||||
|
|
|
|||
|
|
@ -170,6 +170,14 @@ struct PatchTarget {
|
|||
const EVENT_METADATA_FLAGS: u16 =
|
||||
EVENT_DRAFT | EVENT_INVITE_SELF | EVENT_INVITE_OTHERS | EVENT_HIDE_ATTENDEES;
|
||||
|
||||
const DEFAULTED_FLAGS: [JSCalendarProperty<Id>; 5] = [
|
||||
JSCalendarProperty::IsDraft,
|
||||
JSCalendarProperty::UseDefaultAlerts,
|
||||
JSCalendarProperty::MayInviteSelf,
|
||||
JSCalendarProperty::MayInviteOthers,
|
||||
JSCalendarProperty::HideAttendees,
|
||||
];
|
||||
|
||||
impl CalendarEventSet for Server {
|
||||
async fn calendar_event_set(
|
||||
&self,
|
||||
|
|
@ -1623,6 +1631,11 @@ impl CalendarEventSet for Server {
|
|||
updates.as_object_and_get(&Key::Property(JSCalendarProperty::Version)),
|
||||
Some(Value::Str(_))
|
||||
);
|
||||
let omitted_flags = DEFAULTED_FLAGS.map(|property| {
|
||||
updates
|
||||
.as_object_and_get(&Key::Property(property))
|
||||
.is_none()
|
||||
});
|
||||
let mut event = CalendarEvent::default();
|
||||
let mut content = CalendarEventContent::default();
|
||||
let (write, mut js_calendar_group, before) = match source {
|
||||
|
|
@ -1922,11 +1935,31 @@ impl CalendarEventSet for Server {
|
|||
.with_component(content.data.event.main_component())
|
||||
.with_origin(is_origin(&content.data.event, account_info.addresses()))
|
||||
.server_set(&client_values, before.as_ref());
|
||||
if write == EventWrite::Create && !has_version {
|
||||
server_set.push((
|
||||
JSCalendarProperty::Version,
|
||||
Value::Str(JSCALENDAR_VERSION.into()),
|
||||
));
|
||||
if write == EventWrite::Create {
|
||||
if !has_version {
|
||||
server_set.push((
|
||||
JSCalendarProperty::Version,
|
||||
Value::Str(JSCALENDAR_VERSION.into()),
|
||||
));
|
||||
}
|
||||
let use_default_alerts = content
|
||||
.preferences(personal_id)
|
||||
.is_some_and(|preferences| preferences.use_default_alerts());
|
||||
server_set.extend(
|
||||
[
|
||||
event.flags & EVENT_DRAFT != 0,
|
||||
use_default_alerts,
|
||||
event.flags & EVENT_INVITE_SELF != 0,
|
||||
event.flags & EVENT_INVITE_OTHERS != 0,
|
||||
event.flags & EVENT_HIDE_ATTENDEES != 0,
|
||||
]
|
||||
.into_iter()
|
||||
.zip(DEFAULTED_FLAGS)
|
||||
.zip(omitted_flags)
|
||||
.filter_map(|((value, property), is_omitted)| {
|
||||
is_omitted.then_some((property, Value::Bool(value)))
|
||||
}),
|
||||
);
|
||||
}
|
||||
let imported = ImportedValues {
|
||||
participants: is_organizer_assigned,
|
||||
|
|
|
|||
|
|
@ -12,7 +12,9 @@ use crate::api::pending_creates::PendingCreates;
|
|||
use crate::blob::embedded::EmbeddedExport;
|
||||
use crate::changes::state::JmapCacheState;
|
||||
use crate::contact::{CreatedUids, assert_is_unique_uid};
|
||||
use calcard::jscontact::{JSContact, JSContactProperty, JSContactValue};
|
||||
use calcard::jscontact::{
|
||||
JSCONTACT_VERSION, JSContact, JSContactProperty, JSContactType, JSContactValue,
|
||||
};
|
||||
use common::{
|
||||
DavName, GroupwareResources, Server,
|
||||
auth::AccessToken,
|
||||
|
|
@ -136,6 +138,7 @@ impl ContactCardSet for Server {
|
|||
// Process creates
|
||||
let mut batch = BatchBuilder::new();
|
||||
let mut created_slots = PendingCreates::new();
|
||||
let mut created_server_set = Vec::new();
|
||||
let mut created_uids = CreatedUids::default();
|
||||
'create: for (id, mut object) in request.unwrap_create() {
|
||||
if !quota.has_room(created_slots.len()) {
|
||||
|
|
@ -150,6 +153,12 @@ impl ContactCardSet for Server {
|
|||
continue 'create;
|
||||
}
|
||||
};
|
||||
let omits_type = object
|
||||
.as_object_and_get(&Key::Property(JSContactProperty::Type))
|
||||
.is_none();
|
||||
let omits_version = object
|
||||
.as_object_and_get(&Key::Property(JSContactProperty::Version))
|
||||
.is_none();
|
||||
|
||||
match self
|
||||
.create_contact_card(
|
||||
|
|
@ -168,6 +177,9 @@ impl ContactCardSet for Server {
|
|||
.await?
|
||||
{
|
||||
Ok(document_id) => {
|
||||
if omits_type || omits_version {
|
||||
created_server_set.push((id.clone(), omits_type, omits_version));
|
||||
}
|
||||
created_slots.push(id, document_id);
|
||||
}
|
||||
Err(err) => {
|
||||
|
|
@ -587,6 +599,23 @@ impl ContactCardSet for Server {
|
|||
};
|
||||
|
||||
created_slots.resolve(&mut response, &assigned_ids);
|
||||
for (create_id, omits_type, omits_version) in created_server_set {
|
||||
response.add_created_properties(
|
||||
&create_id,
|
||||
[
|
||||
omits_type.then_some((
|
||||
JSContactProperty::Type,
|
||||
Value::Element(JSContactValue::Type(JSContactType::Card)),
|
||||
)),
|
||||
omits_version.then_some((
|
||||
JSContactProperty::Version,
|
||||
Value::Str(JSCONTACT_VERSION.into()),
|
||||
)),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
);
|
||||
}
|
||||
|
||||
response.new_state =
|
||||
State::Exact(assigned_ids.last_change_id(account_id, SyncCollection::AddressBook))
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@
|
|||
*/
|
||||
|
||||
use super::{StoredIdentities, get::IdentityGet};
|
||||
use crate::api::pending_creates::PendingCreates;
|
||||
use common::{Server, storage::index::ObjectIndexBuilder};
|
||||
use email::identity::{EmailAddress, Identity};
|
||||
use jmap_proto::{
|
||||
|
|
@ -30,6 +29,41 @@ use types::{
|
|||
};
|
||||
use utils::sanitize_email;
|
||||
|
||||
type CreatedValue = Value<'static, IdentityProperty, IdentityValue>;
|
||||
|
||||
const DEFAULTED: [IdentityProperty; 5] = [
|
||||
IdentityProperty::Name,
|
||||
IdentityProperty::ReplyTo,
|
||||
IdentityProperty::Bcc,
|
||||
IdentityProperty::TextSignature,
|
||||
IdentityProperty::HtmlSignature,
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Omitted([bool; DEFAULTED.len()]);
|
||||
|
||||
impl Omitted {
|
||||
fn from_create(object: &Value<'_, IdentityProperty, IdentityValue>) -> Self {
|
||||
Omitted(
|
||||
DEFAULTED.map(|property| object.as_object_and_get(&Key::Property(property)).is_none()),
|
||||
)
|
||||
}
|
||||
|
||||
fn server_set(self) -> impl Iterator<Item = (IdentityProperty, CreatedValue)> {
|
||||
[
|
||||
(IdentityProperty::Name, Value::Str("".into())),
|
||||
(IdentityProperty::ReplyTo, Value::Null),
|
||||
(IdentityProperty::Bcc, Value::Null),
|
||||
(IdentityProperty::TextSignature, Value::Str("".into())),
|
||||
(IdentityProperty::HtmlSignature, Value::Str("".into())),
|
||||
]
|
||||
.into_iter()
|
||||
.zip(self.0)
|
||||
.filter_map(|(entry, is_omitted)| is_omitted.then_some(entry))
|
||||
.chain([(IdentityProperty::MayDelete, Value::Bool(true))])
|
||||
}
|
||||
}
|
||||
|
||||
pub trait IdentitySet: Sync + Send {
|
||||
fn identity_set(
|
||||
&self,
|
||||
|
|
@ -58,9 +92,10 @@ impl IdentitySet for Server {
|
|||
|
||||
// Process creates
|
||||
let mut batch = BatchBuilder::new();
|
||||
let mut pending_creates = PendingCreates::new();
|
||||
let mut pending_creates = Vec::new();
|
||||
'create: for (id, object) in request.unwrap_create() {
|
||||
let mut identity = Identity::default();
|
||||
let omitted = Omitted::from_create(&object);
|
||||
|
||||
for (property, mut value) in object.into_expanded_object() {
|
||||
if let Err(err) = response
|
||||
|
|
@ -128,7 +163,7 @@ impl IdentitySet for Server {
|
|||
.caused_by(trc::location!())?
|
||||
.commit_point();
|
||||
identity_count += 1;
|
||||
pending_creates.push(id, slot);
|
||||
pending_creates.push((id, slot, omitted));
|
||||
}
|
||||
|
||||
// Process updates
|
||||
|
|
@ -233,7 +268,9 @@ impl IdentitySet for Server {
|
|||
State::Exact(assigned_ids.last_change_id(account_id, SyncCollection::Identity))
|
||||
.into();
|
||||
|
||||
pending_creates.resolve(&mut response, &assigned_ids);
|
||||
for (id, slot, omitted) in pending_creates {
|
||||
response.created_with_properties(id, assigned_ids.slot(slot), omitted.server_set());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
|
|
|
|||
|
|
@ -75,6 +75,69 @@ pub struct SetContext<'x> {
|
|||
counters: AHashMap<u32, MailboxCounters>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Omitted {
|
||||
parent_id: bool,
|
||||
role: bool,
|
||||
sort_order: bool,
|
||||
is_subscribed: bool,
|
||||
}
|
||||
|
||||
type CreatedValue = Value<'static, MailboxProperty, MailboxValue>;
|
||||
|
||||
impl Omitted {
|
||||
fn from_create(object: &Map<'_, MailboxProperty, MailboxValue>) -> Self {
|
||||
let mut omitted = Omitted {
|
||||
parent_id: true,
|
||||
role: true,
|
||||
sort_order: true,
|
||||
is_subscribed: true,
|
||||
};
|
||||
for key in object.keys() {
|
||||
match key {
|
||||
Key::Property(MailboxProperty::ParentId) => omitted.parent_id = false,
|
||||
Key::Property(MailboxProperty::Role) => omitted.role = false,
|
||||
Key::Property(MailboxProperty::SortOrder) => omitted.sort_order = false,
|
||||
Key::Property(MailboxProperty::IsSubscribed) => omitted.is_subscribed = false,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
omitted
|
||||
}
|
||||
|
||||
fn server_set(
|
||||
self,
|
||||
my_rights: CreatedValue,
|
||||
) -> impl Iterator<Item = (MailboxProperty, CreatedValue)> {
|
||||
[
|
||||
(MailboxProperty::TotalEmails, Value::Number(0u64.into())),
|
||||
(MailboxProperty::UnreadEmails, Value::Number(0u64.into())),
|
||||
(MailboxProperty::TotalThreads, Value::Number(0u64.into())),
|
||||
(MailboxProperty::UnreadThreads, Value::Number(0u64.into())),
|
||||
(MailboxProperty::MyRights, my_rights),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(
|
||||
[
|
||||
(self.parent_id, MailboxProperty::ParentId, Value::Null),
|
||||
(self.role, MailboxProperty::Role, Value::Null),
|
||||
(
|
||||
self.sort_order,
|
||||
MailboxProperty::SortOrder,
|
||||
Value::Number(0u64.into()),
|
||||
),
|
||||
(
|
||||
self.is_subscribed,
|
||||
MailboxProperty::IsSubscribed,
|
||||
Value::Bool(false),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(is_omitted, property, value)| is_omitted.then_some((property, value))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait MailboxSet: Sync + Send {
|
||||
fn mailbox_set(
|
||||
&self,
|
||||
|
|
@ -175,6 +238,7 @@ impl MailboxSet for Server {
|
|||
// Process creates
|
||||
let mut batch = BatchBuilder::new();
|
||||
let mut pending_creates: AHashMap<String, Slot> = AHashMap::new();
|
||||
let mut created = Vec::new();
|
||||
'create: for (id, mut object) in request.unwrap_create() {
|
||||
let metadata_patches =
|
||||
match object_metadata.extract(MetadataPatches::for_create(), &mut object) {
|
||||
|
|
@ -203,6 +267,7 @@ impl MailboxSet for Server {
|
|||
continue 'create;
|
||||
}
|
||||
|
||||
let omitted = Omitted::from_create(&object);
|
||||
match self
|
||||
.mailbox_set_item(
|
||||
object,
|
||||
|
|
@ -213,6 +278,18 @@ impl MailboxSet for Server {
|
|||
.await?
|
||||
{
|
||||
Ok((mut builder, parent)) => {
|
||||
let my_rights = if ctx.is_shared {
|
||||
JmapRights::rights::<mailbox::Mailbox>(
|
||||
builder
|
||||
.changes()
|
||||
.map(|mailbox| {
|
||||
mailbox.acls.as_slice().effective_acl(ctx.access_token)
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
} else {
|
||||
JmapRights::all_rights::<mailbox::Mailbox>()
|
||||
};
|
||||
let metadata_writes = if let Some(metadata_patches) = metadata_patches {
|
||||
let access = if ctx.is_shared {
|
||||
MetadataAccess {
|
||||
|
|
@ -265,7 +342,8 @@ impl MailboxSet for Server {
|
|||
}
|
||||
batch.commit_point();
|
||||
|
||||
pending_creates.insert(id, slot);
|
||||
pending_creates.insert(id.clone(), slot);
|
||||
created.push((id, slot, omitted, my_rights));
|
||||
}
|
||||
Err(err) => {
|
||||
ctx.response.not_created.append(id, err);
|
||||
|
|
@ -283,10 +361,14 @@ impl MailboxSet for Server {
|
|||
.last_change_id(account_id, SyncCollection::Email)
|
||||
.into();
|
||||
|
||||
for (id, slot) in pending_creates {
|
||||
for (id, slot, omitted, my_rights) in created {
|
||||
let document_id = assigned_ids.slot(slot);
|
||||
ctx.mailbox_ids.insert(document_id);
|
||||
ctx.response.created(id, document_id);
|
||||
ctx.response.created_with_properties(
|
||||
id,
|
||||
document_id,
|
||||
omitted.server_set(my_rights),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -303,7 +303,7 @@ async fn registry_object_get(
|
|||
.registry()
|
||||
.query::<Vec<Id>>(
|
||||
query
|
||||
.with_account_opt(is_account_filtered.then_some(get.account_id))
|
||||
.with_account(get.account_id)
|
||||
.with_limit(server.core.jmap.get_max_objects),
|
||||
)
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -243,12 +243,9 @@ pub(crate) async fn archived_item_get(
|
|||
let ids = if let Some(ids) = get.ids.take() {
|
||||
ids
|
||||
} else {
|
||||
let query = if !get.is_account_filtered {
|
||||
RegistryQuery::new(get.object_type).greater_than_or_equal(Property::AccountId, 0u64)
|
||||
} else {
|
||||
RegistryQuery::new(get.object_type).with_account(get.account_id)
|
||||
}
|
||||
.with_limit(get.server.core.jmap.get_max_objects);
|
||||
let query = RegistryQuery::new(get.object_type)
|
||||
.with_account(get.account_id)
|
||||
.with_limit(get.server.core.jmap.get_max_objects);
|
||||
|
||||
get.server.registry().query::<Vec<Id>>(query).await?
|
||||
};
|
||||
|
|
@ -299,15 +296,14 @@ pub(crate) async fn archived_item_query(
|
|||
false
|
||||
}
|
||||
}
|
||||
Property::AccountId => true,
|
||||
_ => false,
|
||||
})?;
|
||||
|
||||
let query = if let Some(account_id) = account_id {
|
||||
RegistryQuery::new(req.object_type).with_account(account_id.document_id())
|
||||
} else if !can_impersonate {
|
||||
RegistryQuery::new(req.object_type).with_account(req.request.account_id.document_id())
|
||||
} else {
|
||||
RegistryQuery::new(req.object_type).greater_than_or_equal(Property::AccountId, 0u64)
|
||||
RegistryQuery::new(req.object_type).with_account(req.request.account_id.document_id())
|
||||
};
|
||||
|
||||
let params = req
|
||||
|
|
|
|||
|
|
@ -192,9 +192,7 @@ impl RegistryQuery for Server {
|
|||
}
|
||||
// SPDX-SnippetEnd
|
||||
let can_impersonate = access_token.has_permission(Permission::Impersonate);
|
||||
if !can_impersonate {
|
||||
query = query.with_account(request.account_id.document_id());
|
||||
}
|
||||
let mut has_account_filter = false;
|
||||
let indexes = object_type.indexes();
|
||||
request.extract_filters(|property, op, value| match property {
|
||||
// SPDX-SnippetBegin
|
||||
|
|
@ -247,6 +245,7 @@ impl RegistryQuery for Server {
|
|||
};
|
||||
|
||||
if let Some(value) = value {
|
||||
has_account_filter |= property == Property::AccountId;
|
||||
query.filters.push(store::registry::RegistryFilter {
|
||||
property,
|
||||
op,
|
||||
|
|
@ -260,6 +259,9 @@ impl RegistryQuery for Server {
|
|||
}
|
||||
}
|
||||
})?;
|
||||
if !has_account_filter {
|
||||
query = query.with_account(request.account_id.document_id());
|
||||
}
|
||||
|
||||
let params = request
|
||||
.extract_parameters(self.core.jmap.query_max_results, Some(Property::Id))?;
|
||||
|
|
|
|||
|
|
@ -74,7 +74,10 @@ use utils::{map::vec_map::VecMap, outbound::OutboundPolicy};
|
|||
#[cfg(feature = "enterprise")]
|
||||
use crate::registry::mapping::principal::{tenant_object_quota, validate_tenant_quota};
|
||||
#[cfg(feature = "enterprise")]
|
||||
use registry::schema::{prelude::OBJ_FILTER_TENANT, structs::Tenant};
|
||||
use registry::schema::{
|
||||
prelude::OBJ_FILTER_TENANT,
|
||||
structs::{Permissions, Tenant},
|
||||
};
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
pub trait RegistrySet: Sync + Send {
|
||||
|
|
@ -362,6 +365,19 @@ async fn registry_object_set(
|
|||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
ObjectInner::Tenant(tenant)
|
||||
if tenant_grants_impersonate(tenant)
|
||||
&& !modification
|
||||
.as_tenant()
|
||||
.is_some_and(tenant_grants_impersonate) =>
|
||||
{
|
||||
Err(SetError::invalid_properties()
|
||||
.with_property(Property::Permissions)
|
||||
.with_description(
|
||||
"The impersonate permission is reserved for server administrators",
|
||||
))
|
||||
}
|
||||
#[cfg(feature = "enterprise")]
|
||||
ObjectInner::Tenant(tenant) => match &tenant.logo {
|
||||
Some(logo)
|
||||
if modification
|
||||
|
|
@ -1088,6 +1104,13 @@ pub(crate) fn map_write_error(err: RegistryWriteResult) -> SetError<Property> {
|
|||
RegistryWriteResult::InvalidForeignKey { object_id } => {
|
||||
SetError::new(SetErrorType::InvalidForeignKey).with_object_id(object_id)
|
||||
}
|
||||
RegistryWriteResult::ForeignKeyOutOfScope { object_id, scope } => {
|
||||
SetError::new(SetErrorType::InvalidForeignKey)
|
||||
.with_description(format!(
|
||||
"{object_id} is not assigned to the same {scope} as this object."
|
||||
))
|
||||
.with_object_id(object_id)
|
||||
}
|
||||
RegistryWriteResult::PrimaryKeyConflict {
|
||||
property,
|
||||
existing_id,
|
||||
|
|
@ -1103,3 +1126,17 @@ pub(crate) fn map_write_error(err: RegistryWriteResult) -> SetError<Property> {
|
|||
RegistryWriteResult::Success(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
fn tenant_grants_impersonate(tenant: &Tenant) -> bool {
|
||||
match &tenant.permissions {
|
||||
Permissions::Merge(list) | Permissions::Replace(list) => {
|
||||
list.enabled_permissions.contains(&Permission::Impersonate)
|
||||
}
|
||||
Permissions::Inherit => false,
|
||||
}
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ homepage = "https://stalw.art"
|
|||
keywords = ["imap", "jmap", "smtp", "email", "mail", "webdav", "server"]
|
||||
categories = ["email"]
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[[bin]]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "managesieve"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "nlp"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "pop3"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "registry"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -536,6 +536,7 @@ pub enum Property {
|
|||
ClaimUsername = 706,
|
||||
Cleartext = 807,
|
||||
ClientCapacity = 677,
|
||||
ClientHash = 1012,
|
||||
ClientId = 132,
|
||||
ClientIp = 391,
|
||||
ClientIpSource = 479,
|
||||
|
|
@ -1410,6 +1411,7 @@ pub enum Property {
|
|||
Require = 646,
|
||||
RequireTls = 622,
|
||||
ReservoirCapacity = 875,
|
||||
ResourceAttributes = 1014,
|
||||
ResourceGroup = 366,
|
||||
ResourceUrl = 64,
|
||||
ResponseCode = 250,
|
||||
|
|
@ -1470,6 +1472,7 @@ pub enum Property {
|
|||
Servers = 352,
|
||||
ServiceAccountJson = 380,
|
||||
ServiceName = 753,
|
||||
ServiceNamespace = 1013,
|
||||
Services = 933,
|
||||
SessionTimeout = 550,
|
||||
SessionToken = 357,
|
||||
|
|
|
|||
|
|
@ -778,6 +778,7 @@ impl EnumImpl for Property {
|
|||
b"claimUsername" => Property::ClaimUsername,
|
||||
b"cleartext" => Property::Cleartext,
|
||||
b"clientCapacity" => Property::ClientCapacity,
|
||||
b"clientHash" => Property::ClientHash,
|
||||
b"clientId" => Property::ClientId,
|
||||
b"clientIp" => Property::ClientIp,
|
||||
b"clientIpSource" => Property::ClientIpSource,
|
||||
|
|
@ -1462,6 +1463,7 @@ impl EnumImpl for Property {
|
|||
b"require" => Property::Require,
|
||||
b"requireTls" => Property::RequireTls,
|
||||
b"reservoirCapacity" => Property::ReservoirCapacity,
|
||||
b"resourceAttributes" => Property::ResourceAttributes,
|
||||
b"resourceGroup" => Property::ResourceGroup,
|
||||
b"resourceUrl" => Property::ResourceUrl,
|
||||
b"responseCode" => Property::ResponseCode,
|
||||
|
|
@ -1517,6 +1519,7 @@ impl EnumImpl for Property {
|
|||
b"servers" => Property::Servers,
|
||||
b"serviceAccountJson" => Property::ServiceAccountJson,
|
||||
b"serviceName" => Property::ServiceName,
|
||||
b"serviceNamespace" => Property::ServiceNamespace,
|
||||
b"services" => Property::Services,
|
||||
b"sessionTimeout" => Property::SessionTimeout,
|
||||
b"sessionToken" => Property::SessionToken,
|
||||
|
|
@ -1784,6 +1787,7 @@ impl EnumImpl for Property {
|
|||
b"claimUsername" => Property::ClaimUsername,
|
||||
b"cleartext" => Property::Cleartext,
|
||||
b"clientCapacity" => Property::ClientCapacity,
|
||||
b"clientHash" => Property::ClientHash,
|
||||
b"clientId" => Property::ClientId,
|
||||
b"clientIp" => Property::ClientIp,
|
||||
b"clientIpSource" => Property::ClientIpSource,
|
||||
|
|
@ -2426,6 +2430,7 @@ impl EnumImpl for Property {
|
|||
b"require" => Property::Require,
|
||||
b"requireTls" => Property::RequireTls,
|
||||
b"reservoirCapacity" => Property::ReservoirCapacity,
|
||||
b"resourceAttributes" => Property::ResourceAttributes,
|
||||
b"resourceGroup" => Property::ResourceGroup,
|
||||
b"resourceUrl" => Property::ResourceUrl,
|
||||
b"responseCode" => Property::ResponseCode,
|
||||
|
|
@ -2480,6 +2485,7 @@ impl EnumImpl for Property {
|
|||
b"servers" => Property::Servers,
|
||||
b"serviceAccountJson" => Property::ServiceAccountJson,
|
||||
b"serviceName" => Property::ServiceName,
|
||||
b"serviceNamespace" => Property::ServiceNamespace,
|
||||
b"services" => Property::Services,
|
||||
b"sessionTimeout" => Property::SessionTimeout,
|
||||
b"sessionToken" => Property::SessionToken,
|
||||
|
|
@ -2787,6 +2793,7 @@ impl EnumImpl for Property {
|
|||
Property::ClaimUsername => "claimUsername",
|
||||
Property::Cleartext => "cleartext",
|
||||
Property::ClientCapacity => "clientCapacity",
|
||||
Property::ClientHash => "clientHash",
|
||||
Property::ClientId => "clientId",
|
||||
Property::ClientIp => "clientIp",
|
||||
Property::ClientIpSource => "clientIpSource",
|
||||
|
|
@ -3661,6 +3668,7 @@ impl EnumImpl for Property {
|
|||
Property::Require => "require",
|
||||
Property::RequireTls => "requireTls",
|
||||
Property::ReservoirCapacity => "reservoirCapacity",
|
||||
Property::ResourceAttributes => "resourceAttributes",
|
||||
Property::ResourceGroup => "resourceGroup",
|
||||
Property::ResourceUrl => "resourceUrl",
|
||||
Property::ResponseCode => "responseCode",
|
||||
|
|
@ -3721,6 +3729,7 @@ impl EnumImpl for Property {
|
|||
Property::Servers => "servers",
|
||||
Property::ServiceAccountJson => "serviceAccountJson",
|
||||
Property::ServiceName => "serviceName",
|
||||
Property::ServiceNamespace => "serviceNamespace",
|
||||
Property::Services => "services",
|
||||
Property::SessionTimeout => "sessionTimeout",
|
||||
Property::SessionToken => "sessionToken",
|
||||
|
|
@ -4115,6 +4124,7 @@ impl EnumImpl for Property {
|
|||
706 => Some(Property::ClaimUsername),
|
||||
807 => Some(Property::Cleartext),
|
||||
677 => Some(Property::ClientCapacity),
|
||||
1012 => Some(Property::ClientHash),
|
||||
132 => Some(Property::ClientId),
|
||||
391 => Some(Property::ClientIp),
|
||||
479 => Some(Property::ClientIpSource),
|
||||
|
|
@ -4989,6 +4999,7 @@ impl EnumImpl for Property {
|
|||
646 => Some(Property::Require),
|
||||
622 => Some(Property::RequireTls),
|
||||
875 => Some(Property::ReservoirCapacity),
|
||||
1014 => Some(Property::ResourceAttributes),
|
||||
366 => Some(Property::ResourceGroup),
|
||||
64 => Some(Property::ResourceUrl),
|
||||
250 => Some(Property::ResponseCode),
|
||||
|
|
@ -5049,6 +5060,7 @@ impl EnumImpl for Property {
|
|||
352 => Some(Property::Servers),
|
||||
380 => Some(Property::ServiceAccountJson),
|
||||
753 => Some(Property::ServiceName),
|
||||
1013 => Some(Property::ServiceNamespace),
|
||||
933 => Some(Property::Services),
|
||||
550 => Some(Property::SessionTimeout),
|
||||
357 => Some(Property::SessionToken),
|
||||
|
|
@ -5264,7 +5276,7 @@ impl EnumImpl for Property {
|
|||
}
|
||||
}
|
||||
|
||||
const COUNT: usize = 1012;
|
||||
const COUNT: usize = 1015;
|
||||
}
|
||||
|
||||
impl serde::Serialize for Property {
|
||||
|
|
@ -5716,11 +5728,18 @@ impl ObjectType {
|
|||
),
|
||||
// SPDX-SnippetEnd
|
||||
],
|
||||
ObjectType::OAuthGrant => vec![IndexSchema::new(
|
||||
Property::AccountId,
|
||||
IndexSchemaType::Search,
|
||||
IndexSchemaValueType::Id,
|
||||
)],
|
||||
ObjectType::OAuthGrant => vec![
|
||||
IndexSchema::new(
|
||||
Property::AccountId,
|
||||
IndexSchemaType::Search,
|
||||
IndexSchemaValueType::Id,
|
||||
),
|
||||
IndexSchema::new(
|
||||
Property::ClientHash,
|
||||
IndexSchemaType::Search,
|
||||
IndexSchemaValueType::Keyword,
|
||||
),
|
||||
],
|
||||
ObjectType::PublicKey => vec![IndexSchema::new(
|
||||
Property::AccountId,
|
||||
IndexSchemaType::Search,
|
||||
|
|
|
|||
|
|
@ -3813,6 +3813,12 @@ pub struct Metrics {
|
|||
pub metrics: Map<trc::MetricType>,
|
||||
#[serde(rename = "metricsPolicy")]
|
||||
pub metrics_policy: EventPolicy,
|
||||
#[serde(rename = "serviceName")]
|
||||
pub service_name: String,
|
||||
#[serde(rename = "serviceNamespace")]
|
||||
pub service_namespace: Option<String>,
|
||||
#[serde(rename = "resourceAttributes")]
|
||||
pub resource_attributes: VecMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -3829,6 +3835,12 @@ pub struct MetricsOtelGrpc {
|
|||
pub url: Option<String>,
|
||||
pub interval: Duration,
|
||||
pub timeout: Duration,
|
||||
#[serde(rename = "allowInvalidCerts")]
|
||||
pub allow_invalid_certs: bool,
|
||||
#[serde(rename = "httpAuth")]
|
||||
pub http_auth: HttpAuth,
|
||||
#[serde(rename = "httpHeaders")]
|
||||
pub http_headers: VecMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -4407,6 +4419,8 @@ pub struct OAuthGrant {
|
|||
pub account_id: Id,
|
||||
#[serde(rename = "clientId")]
|
||||
pub client_id: String,
|
||||
#[serde(rename = "clientHash")]
|
||||
pub client_hash: String,
|
||||
#[serde(rename = "clientName")]
|
||||
pub client_name: Option<String>,
|
||||
#[serde(rename = "clientKind")]
|
||||
|
|
@ -6485,6 +6499,8 @@ pub struct TracerLog {
|
|||
#[serde(default)]
|
||||
pub struct TracerOtelGrpc {
|
||||
pub url: Option<String>,
|
||||
#[serde(rename = "allowInvalidCerts")]
|
||||
pub allow_invalid_certs: bool,
|
||||
#[serde(rename = "enableLogExporter")]
|
||||
pub enable_log_exporter: bool,
|
||||
#[serde(rename = "enableSpanExporter")]
|
||||
|
|
|
|||
|
|
@ -42726,6 +42726,21 @@ impl ObjectImpl for Metrics {
|
|||
value.validate(errors);
|
||||
let value = &self.prometheus;
|
||||
value.validate(errors);
|
||||
let value = &self.service_name;
|
||||
if value.is_empty() {
|
||||
errors.push(ValidationError::required(Property::ServiceName));
|
||||
}
|
||||
if let Some(value) = &self.service_namespace {
|
||||
if value.is_empty() {
|
||||
errors.push(ValidationError::required(Property::ServiceNamespace));
|
||||
}
|
||||
}
|
||||
let value = &self.resource_attributes;
|
||||
for value in value.values() {
|
||||
if value.is_empty() {
|
||||
errors.push(ValidationError::required(Property::ResourceAttributes));
|
||||
}
|
||||
}
|
||||
errors.len() == neb
|
||||
}
|
||||
|
||||
|
|
@ -42745,11 +42760,20 @@ impl ObjectImpl for Metrics {
|
|||
|
||||
impl Pickle for Metrics {
|
||||
fn pickle(&self, out: &mut Vec<u8>) {
|
||||
let block = crate::pickle::begin_block(out, 4, 0, 0);
|
||||
let mut bitmap = 0u64;
|
||||
if self.service_namespace.is_some() {
|
||||
bitmap |= 1 << 0;
|
||||
}
|
||||
let block = crate::pickle::begin_block(out, 7, 1, bitmap);
|
||||
self.open_telemetry.pickle(out);
|
||||
self.prometheus.pickle(out);
|
||||
self.metrics.pickle(out);
|
||||
self.metrics_policy.pickle(out);
|
||||
self.service_name.pickle(out);
|
||||
if let Some(value) = &self.service_namespace {
|
||||
value.pickle(out);
|
||||
}
|
||||
self.resource_attributes.pickle(out);
|
||||
crate::pickle::end_block(out, block);
|
||||
}
|
||||
|
||||
|
|
@ -42778,12 +42802,34 @@ impl Pickle for Metrics {
|
|||
} else {
|
||||
EventPolicy::Exclude
|
||||
};
|
||||
let field4: String = if block.has(4) {
|
||||
Pickle::unpickle(stream)?
|
||||
} else {
|
||||
"stalwart".to_string()
|
||||
};
|
||||
let field5: Option<String> = if block.has(5) {
|
||||
if block.flag(0) {
|
||||
Some(Pickle::unpickle(stream)?)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
let field6: VecMap<String, String> = if block.has(6) {
|
||||
Pickle::unpickle(stream)?
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
stream.close_block(block);
|
||||
Some(Self {
|
||||
open_telemetry: field0,
|
||||
prometheus: field1,
|
||||
metrics: field2,
|
||||
metrics_policy: field3,
|
||||
service_name: field4,
|
||||
service_namespace: field5,
|
||||
resource_attributes: field6,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -42795,6 +42841,9 @@ impl Default for Metrics {
|
|||
prometheus: Default::default(),
|
||||
metrics: Default::default(),
|
||||
metrics_policy: EventPolicy::Exclude,
|
||||
service_name: "stalwart".to_string(),
|
||||
service_namespace: Default::default(),
|
||||
resource_attributes: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -42805,7 +42854,7 @@ impl IntoValue for Metrics {
|
|||
}
|
||||
|
||||
fn into_value_with(self, opts: ValueOptions) -> JmapValue<'static> {
|
||||
let mut map = jmap_tools::Map::with_capacity(6);
|
||||
let mut map = jmap_tools::Map::with_capacity(9);
|
||||
map.insert_unchecked(
|
||||
Property::OpenTelemetry,
|
||||
self.open_telemetry.into_value_with(opts),
|
||||
|
|
@ -42816,6 +42865,18 @@ impl IntoValue for Metrics {
|
|||
Property::MetricsPolicy,
|
||||
self.metrics_policy.into_value_with(opts),
|
||||
);
|
||||
map.insert_unchecked(
|
||||
Property::ServiceName,
|
||||
self.service_name.into_value_with(opts),
|
||||
);
|
||||
map.insert_unchecked(
|
||||
Property::ServiceNamespace,
|
||||
self.service_namespace.into_value_with(opts),
|
||||
);
|
||||
map.insert_unchecked(
|
||||
Property::ResourceAttributes,
|
||||
self.resource_attributes.into_value_with(opts),
|
||||
);
|
||||
JmapValue::Object(map)
|
||||
}
|
||||
}
|
||||
|
|
@ -42831,6 +42892,15 @@ impl RegistryJsonPropertyPatch for Metrics {
|
|||
Some(Property::Prometheus) => self.prometheus.patch(pointer, value),
|
||||
Some(Property::Metrics) => self.metrics.patch(pointer, value),
|
||||
Some(Property::MetricsPolicy) => self.metrics_policy.patch(pointer, value),
|
||||
Some(Property::ServiceName) => self
|
||||
.service_name
|
||||
.patch(pointer.with_validators(&[StringValidator::Trim]), value),
|
||||
Some(Property::ServiceNamespace) => self
|
||||
.service_namespace
|
||||
.patch(pointer.with_validators(&[StringValidator::Trim]), value),
|
||||
Some(Property::ResourceAttributes) => self
|
||||
.resource_attributes
|
||||
.patch(pointer.with_validators(&[StringValidator::Trim]), value),
|
||||
Some(Property::Type) => Ok(MaybeUnpatched::Unpatched {
|
||||
property: Property::Type,
|
||||
value,
|
||||
|
|
@ -42854,8 +42924,10 @@ impl MetricsOtel {
|
|||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
fn validate_inline_secrets(&self, errors: &mut Vec<ValidationError>) {
|
||||
if let MetricsOtel::Http(inner) = self {
|
||||
inner.validate_inline_secrets(errors);
|
||||
match self {
|
||||
MetricsOtel::Http(inner) => inner.validate_inline_secrets(errors),
|
||||
MetricsOtel::Grpc(inner) => inner.validate_inline_secrets(errors),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -42964,8 +43036,26 @@ impl MetricsOtelGrpc {
|
|||
errors.push(ValidationError::required(Property::Url));
|
||||
}
|
||||
}
|
||||
let value = &self.http_auth;
|
||||
value.validate(errors);
|
||||
let value = &self.http_headers;
|
||||
for value in value.values() {
|
||||
if value.is_empty() {
|
||||
errors.push(ValidationError::required(Property::HttpHeaders));
|
||||
}
|
||||
}
|
||||
errors.len() == neb
|
||||
}
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
fn validate_inline_secrets(&self, errors: &mut Vec<ValidationError>) {
|
||||
self.http_auth.validate_inline_secrets(errors);
|
||||
}
|
||||
|
||||
// SPDX-SnippetEnd
|
||||
}
|
||||
|
||||
impl Pickle for MetricsOtelGrpc {
|
||||
|
|
@ -42974,12 +43064,17 @@ impl Pickle for MetricsOtelGrpc {
|
|||
if self.url.is_some() {
|
||||
bitmap |= 1 << 0;
|
||||
}
|
||||
let block = crate::pickle::begin_block(out, 3, 1, bitmap);
|
||||
if self.allow_invalid_certs {
|
||||
bitmap |= 1 << 1;
|
||||
}
|
||||
let block = crate::pickle::begin_block(out, 6, 2, bitmap);
|
||||
if let Some(value) = &self.url {
|
||||
value.pickle(out);
|
||||
}
|
||||
self.interval.pickle(out);
|
||||
self.timeout.pickle(out);
|
||||
self.http_auth.pickle(out);
|
||||
self.http_headers.pickle(out);
|
||||
crate::pickle::end_block(out, block);
|
||||
}
|
||||
|
||||
|
|
@ -43004,11 +43099,25 @@ impl Pickle for MetricsOtelGrpc {
|
|||
} else {
|
||||
Duration::from_millis(10000)
|
||||
};
|
||||
let field3: bool = if block.has(3) { block.flag(1) } else { false };
|
||||
let field4: HttpAuth = if block.has(4) {
|
||||
Pickle::unpickle(stream)?
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
let field5: VecMap<String, String> = if block.has(5) {
|
||||
Pickle::unpickle(stream)?
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
stream.close_block(block);
|
||||
Some(Self {
|
||||
url: field0,
|
||||
interval: field1,
|
||||
timeout: field2,
|
||||
allow_invalid_certs: field3,
|
||||
http_auth: field4,
|
||||
http_headers: field5,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -43019,6 +43128,9 @@ impl Default for MetricsOtelGrpc {
|
|||
url: Default::default(),
|
||||
interval: Duration::from_millis(60000),
|
||||
timeout: Duration::from_millis(10000),
|
||||
allow_invalid_certs: false,
|
||||
http_auth: Default::default(),
|
||||
http_headers: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -43029,10 +43141,19 @@ impl IntoValue for MetricsOtelGrpc {
|
|||
}
|
||||
|
||||
fn into_value_with(self, opts: ValueOptions) -> JmapValue<'static> {
|
||||
let mut map = jmap_tools::Map::with_capacity(5);
|
||||
let mut map = jmap_tools::Map::with_capacity(8);
|
||||
map.insert_unchecked(Property::Url, self.url.into_value_with(opts));
|
||||
map.insert_unchecked(Property::Interval, self.interval.into_value_with(opts));
|
||||
map.insert_unchecked(Property::Timeout, self.timeout.into_value_with(opts));
|
||||
map.insert_unchecked(
|
||||
Property::AllowInvalidCerts,
|
||||
self.allow_invalid_certs.into_value_with(opts),
|
||||
);
|
||||
map.insert_unchecked(Property::HttpAuth, self.http_auth.into_value_with(opts));
|
||||
map.insert_unchecked(
|
||||
Property::HttpHeaders,
|
||||
self.http_headers.into_value_with(opts),
|
||||
);
|
||||
JmapValue::Object(map)
|
||||
}
|
||||
}
|
||||
|
|
@ -43049,6 +43170,11 @@ impl RegistryJsonPropertyPatch for MetricsOtelGrpc {
|
|||
.patch(pointer.with_validators(&[StringValidator::Trim]), value),
|
||||
Some(Property::Interval) => self.interval.patch(pointer, value),
|
||||
Some(Property::Timeout) => self.timeout.patch(pointer, value),
|
||||
Some(Property::AllowInvalidCerts) => self.allow_invalid_certs.patch(pointer, value),
|
||||
Some(Property::HttpAuth) => self.http_auth.patch(pointer, value),
|
||||
Some(Property::HttpHeaders) => self
|
||||
.http_headers
|
||||
.patch(pointer.with_validators(&[StringValidator::Trim]), value),
|
||||
Some(Property::Type) => Ok(MaybeUnpatched::Unpatched {
|
||||
property: Property::Type,
|
||||
value,
|
||||
|
|
@ -50652,6 +50778,10 @@ impl ObjectImpl for OAuthGrant {
|
|||
if value.is_empty() {
|
||||
errors.push(ValidationError::required(Property::ClientId));
|
||||
}
|
||||
let value = &self.client_hash;
|
||||
if value.is_empty() {
|
||||
errors.push(ValidationError::required(Property::ClientHash));
|
||||
}
|
||||
if let Some(value) = &self.client_name {
|
||||
if value.is_empty() {
|
||||
errors.push(ValidationError::required(Property::ClientName));
|
||||
|
|
@ -50676,6 +50806,7 @@ impl ObjectImpl for OAuthGrant {
|
|||
fn index<'x>(&'x self, i: &mut IndexBuilder<'x>) {
|
||||
i.foreign_key(ObjectType::Account, self.account_id.into(), None);
|
||||
i.search(Property::AccountId, &self.account_id);
|
||||
i.search(Property::ClientHash, &self.client_hash);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -50691,7 +50822,7 @@ impl Pickle for OAuthGrant {
|
|||
if self.pending {
|
||||
bitmap |= 1 << 2;
|
||||
}
|
||||
let block = crate::pickle::begin_block(out, 10, 3, bitmap);
|
||||
let block = crate::pickle::begin_block(out, 11, 3, bitmap);
|
||||
self.account_id.pickle(out);
|
||||
self.client_id.pickle(out);
|
||||
if let Some(value) = &self.client_name {
|
||||
|
|
@ -50705,6 +50836,7 @@ impl Pickle for OAuthGrant {
|
|||
self.created_at.pickle(out);
|
||||
self.last_used_at.pickle(out);
|
||||
self.generation.pickle(out);
|
||||
self.client_hash.pickle(out);
|
||||
crate::pickle::end_block(out, block);
|
||||
}
|
||||
|
||||
|
|
@ -50767,6 +50899,11 @@ impl Pickle for OAuthGrant {
|
|||
0u64
|
||||
};
|
||||
let field9: bool = if block.has(9) { block.flag(2) } else { false };
|
||||
let field10: String = if block.has(10) {
|
||||
Pickle::unpickle(stream)?
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
stream.close_block(block);
|
||||
Some(Self {
|
||||
account_id: field0,
|
||||
|
|
@ -50779,6 +50916,7 @@ impl Pickle for OAuthGrant {
|
|||
last_used_at: field7,
|
||||
generation: field8,
|
||||
pending: field9,
|
||||
client_hash: field10,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -50788,6 +50926,7 @@ impl Default for OAuthGrant {
|
|||
Self {
|
||||
account_id: Default::default(),
|
||||
client_id: Default::default(),
|
||||
client_hash: Default::default(),
|
||||
client_name: Default::default(),
|
||||
client_kind: Default::default(),
|
||||
scopes: Default::default(),
|
||||
|
|
@ -50806,9 +50945,10 @@ impl IntoValue for OAuthGrant {
|
|||
}
|
||||
|
||||
fn into_value_with(self, opts: ValueOptions) -> JmapValue<'static> {
|
||||
let mut map = jmap_tools::Map::with_capacity(12);
|
||||
let mut map = jmap_tools::Map::with_capacity(13);
|
||||
map.insert_unchecked(Property::AccountId, self.account_id.into_value_with(opts));
|
||||
map.insert_unchecked(Property::ClientId, self.client_id.into_value_with(opts));
|
||||
map.insert_unchecked(Property::ClientHash, self.client_hash.into_value_with(opts));
|
||||
map.insert_unchecked(Property::ClientName, self.client_name.into_value_with(opts));
|
||||
map.insert_unchecked(Property::ClientKind, self.client_kind.into_value_with(opts));
|
||||
map.insert_unchecked(Property::Scopes, self.scopes.into_value_with(opts));
|
||||
|
|
@ -50835,6 +50975,7 @@ impl RegistryJsonPropertyPatch for OAuthGrant {
|
|||
.account_id
|
||||
.patch(pointer.assert_read_only()?.assert_can_set_account()?, value),
|
||||
Some(Property::ClientId) => pointer.assert_server_set(),
|
||||
Some(Property::ClientHash) => pointer.assert_server_set(),
|
||||
Some(Property::ClientName) => pointer.assert_server_set(),
|
||||
Some(Property::ClientKind) => pointer.assert_server_set(),
|
||||
Some(Property::Scopes) => pointer.assert_server_set(),
|
||||
|
|
@ -74031,7 +74172,10 @@ impl Pickle for TracerOtelGrpc {
|
|||
if self.lossy {
|
||||
bitmap |= 1 << 4;
|
||||
}
|
||||
let block = crate::pickle::begin_block(out, 12, 5, bitmap);
|
||||
if self.allow_invalid_certs {
|
||||
bitmap |= 1 << 5;
|
||||
}
|
||||
let block = crate::pickle::begin_block(out, 13, 6, bitmap);
|
||||
if let Some(value) = &self.url {
|
||||
value.pickle(out);
|
||||
}
|
||||
|
|
@ -74095,6 +74239,7 @@ impl Pickle for TracerOtelGrpc {
|
|||
} else {
|
||||
EventPolicy::Exclude
|
||||
};
|
||||
let field12: bool = if block.has(12) { block.flag(5) } else { false };
|
||||
stream.close_block(block);
|
||||
Some(Self {
|
||||
url: field0,
|
||||
|
|
@ -74109,6 +74254,7 @@ impl Pickle for TracerOtelGrpc {
|
|||
lossy: field9,
|
||||
events: field10,
|
||||
events_policy: field11,
|
||||
allow_invalid_certs: field12,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -74117,6 +74263,7 @@ impl Default for TracerOtelGrpc {
|
|||
fn default() -> Self {
|
||||
Self {
|
||||
url: Default::default(),
|
||||
allow_invalid_certs: false,
|
||||
enable_log_exporter: true,
|
||||
enable_span_exporter: true,
|
||||
throttle: Duration::from_millis(1000),
|
||||
|
|
@ -74138,8 +74285,12 @@ impl IntoValue for TracerOtelGrpc {
|
|||
}
|
||||
|
||||
fn into_value_with(self, opts: ValueOptions) -> JmapValue<'static> {
|
||||
let mut map = jmap_tools::Map::with_capacity(14);
|
||||
let mut map = jmap_tools::Map::with_capacity(15);
|
||||
map.insert_unchecked(Property::Url, self.url.into_value_with(opts));
|
||||
map.insert_unchecked(
|
||||
Property::AllowInvalidCerts,
|
||||
self.allow_invalid_certs.into_value_with(opts),
|
||||
);
|
||||
map.insert_unchecked(
|
||||
Property::EnableLogExporter,
|
||||
self.enable_log_exporter.into_value_with(opts),
|
||||
|
|
@ -74177,6 +74328,7 @@ impl RegistryJsonPropertyPatch for TracerOtelGrpc {
|
|||
Some(Property::Url) => self
|
||||
.url
|
||||
.patch(pointer.with_validators(&[StringValidator::Trim]), value),
|
||||
Some(Property::AllowInvalidCerts) => self.allow_invalid_certs.patch(pointer, value),
|
||||
Some(Property::EnableLogExporter) => self.enable_log_exporter.patch(pointer, value),
|
||||
Some(Property::EnableSpanExporter) => self.enable_span_exporter.patch(pointer, value),
|
||||
Some(Property::Throttle) => self.throttle.patch(pointer, value),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "s3"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "scim-proto"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "scim"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -227,6 +227,12 @@ impl IntoScimError for RegistryWriteResult {
|
|||
object_id.object().as_str()
|
||||
))
|
||||
}
|
||||
RegistryWriteResult::ForeignKeyOutOfScope { object_id, scope } => {
|
||||
ScimError::invalid_value(format!(
|
||||
"The referenced {} is not assigned to the same {scope}.",
|
||||
object_id.object().as_str()
|
||||
))
|
||||
}
|
||||
RegistryWriteResult::ValidationError { errors } => {
|
||||
let mut detail = String::with_capacity(64);
|
||||
for error in &errors {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "services"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -12,10 +12,7 @@ use std::{
|
|||
};
|
||||
|
||||
use crate::task_manager::reconcile::insert_task_if_absent;
|
||||
use common::{
|
||||
BuildServer, Inner, LONG_1D_SLUMBER,
|
||||
config::{mailstore::spamfilter, telemetry::OtelMetrics},
|
||||
};
|
||||
use common::{BuildServer, Inner, LONG_1D_SLUMBER, config::mailstore::spamfilter};
|
||||
use registry::{
|
||||
schema::{
|
||||
enums::{TaskSpamFilterMaintenanceType, TaskStoreMaintenanceType, TaskType},
|
||||
|
|
@ -129,7 +126,6 @@ pub fn spawn_task_scheduler(inner: Arc<Inner>) {
|
|||
|
||||
// OTEL Push Metrics
|
||||
if let Some(otel) = &server.core.metrics.otel {
|
||||
OtelMetrics::enable_errors();
|
||||
queue.schedule(Instant::now() + otel.interval, Event::OtelMetrics);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ use groupware::{
|
|||
schedule::{EventAlarmScheduler, EventAlarmUsers},
|
||||
},
|
||||
scheduling::{
|
||||
ItipTime, ItipValue,
|
||||
ItipTime, ItipTimeKind, ItipValue,
|
||||
format::{DateStyle, TextFormatter, hyperlink},
|
||||
},
|
||||
strip_mailto_scheme,
|
||||
|
|
@ -924,6 +924,7 @@ async fn build_template(
|
|||
&ItipValue::Time(ItipTime {
|
||||
start: alarm.event_start.timestamp(),
|
||||
tz_id: alarm.event_start_tz as u16,
|
||||
kind: ItipTimeKind::DateTime,
|
||||
}),
|
||||
DateStyle::Short,
|
||||
);
|
||||
|
|
@ -931,6 +932,7 @@ async fn build_template(
|
|||
&ItipValue::Time(ItipTime {
|
||||
start: alarm.event_end.timestamp(),
|
||||
tz_id: alarm.event_end_tz as u16,
|
||||
kind: ItipTimeKind::DateTime,
|
||||
}),
|
||||
DateStyle::Short,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ use registry::{
|
|||
prelude::{ObjectType, Property},
|
||||
structs::{Task, TaskAccountMaintenance, TaskDestroyAccount, TaskStatus},
|
||||
},
|
||||
types::EnumImpl,
|
||||
types::{EnumImpl, id::ObjectId},
|
||||
};
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
|
|
@ -26,7 +26,10 @@ use store::{Deserialize, IterateParams, U64_LEN};
|
|||
// SPDX-SnippetEnd
|
||||
use store::{
|
||||
SerializeInfallible, ValueKey,
|
||||
registry::RegistryQuery,
|
||||
registry::{
|
||||
RegistryQuery,
|
||||
write::{RegistryWrite, RegistryWriteResult},
|
||||
},
|
||||
search::SearchQuery,
|
||||
write::{
|
||||
Archive, ArchiveBytes, BatchBuilder, BlobLink, BlobOp, RegistryClass, SearchIndex,
|
||||
|
|
@ -111,6 +114,26 @@ async fn destroy_account(server: &Server, task: &TaskDestroyAccount) -> trc::Res
|
|||
let object_id = object.to_id();
|
||||
|
||||
for id in ids {
|
||||
if object == ObjectType::OAuthGrant {
|
||||
match server
|
||||
.registry()
|
||||
.write(RegistryWrite::delete(ObjectId::new(object, id)))
|
||||
.await
|
||||
{
|
||||
Ok(RegistryWriteResult::Success(_)) => continue,
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
trc::error!(
|
||||
err.caused_by(trc::location!())
|
||||
.account_id(account_id)
|
||||
.id(id.id())
|
||||
.details(
|
||||
"Failed to delete OAuth grant, clearing its account index only"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
batch
|
||||
.clear(ValueClass::Registry(RegistryClass::Item {
|
||||
object_id,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "sieve-rs"
|
||||
description = "Sieve filter interpreter"
|
||||
version = "2.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "smtp-proto"
|
||||
description = "SMTP protocol parser"
|
||||
version = "0.2.5"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "smtp-report"
|
||||
description = "DMARC aggregate, ARF and TLS-RPT report generation and parsing"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ homepage = "https://stalw.art/smtp"
|
|||
keywords = ["smtp", "email", "mail", "server"]
|
||||
categories = ["email"]
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "spam-filter"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -43,7 +43,10 @@ impl SpamFilterAnalyzeReceived for Server {
|
|||
ctx.result.add_tag("RCVD_HELO_USER");
|
||||
} else if let (Some(Host::Name(helo_domain)), Some(ip_rev)) =
|
||||
(helo_domain, ip_rev)
|
||||
&& !eq_lowercase_str(helo_domain, ip_rev)
|
||||
&& !eq_lowercase_str(
|
||||
helo_domain.strip_suffix('.').unwrap_or(helo_domain),
|
||||
ip_rev.strip_suffix('.').unwrap_or(ip_rev),
|
||||
)
|
||||
{
|
||||
// HELO domain does not match PTR record
|
||||
ctx.result.add_tag("FORGED_RCVD_TRAIL");
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "store"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
@ -9,7 +9,7 @@ types = { path = "../types" }
|
|||
nlp = { path = "../nlp" }
|
||||
trc = { path = "../trc" }
|
||||
registry = { path = "../registry" }
|
||||
rocksdb = { version = "0.24", optional = true, features = ["multi-threaded-cf"] }
|
||||
rocksdb = { version = "0.25", optional = true, features = ["multi-threaded-cf"] }
|
||||
foundationdb = { version = "0.11", features = ["embedded-fdb-include", "fdb-7_4"], optional = true }
|
||||
rusqlite = { version = "0.41", features = ["bundled"], optional = true }
|
||||
s3 = { path = "../s3", optional = true }
|
||||
|
|
|
|||
|
|
@ -103,6 +103,11 @@ impl RegistryStore {
|
|||
self.0.env_public_url.as_deref()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn process_nonce(&self) -> [u8; 16] {
|
||||
self.0.process_nonce
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_recovery_mode(&self) -> bool {
|
||||
self.0.env_recovery_mode
|
||||
|
|
|
|||
|
|
@ -453,6 +453,7 @@ pub struct RegistryStoreInner {
|
|||
pub(crate) env_hostname: String,
|
||||
pub(crate) env_public_url: Option<String>,
|
||||
pub(crate) id_generator: SnowflakeIdGenerator,
|
||||
pub(crate) process_nonce: [u8; 16],
|
||||
}
|
||||
|
||||
#[cfg(feature = "sqlite")]
|
||||
|
|
|
|||
|
|
@ -6,9 +6,16 @@
|
|||
|
||||
use crate::{RegistryStore, RegistryStoreInner, Store};
|
||||
use registry::schema::structs::DataStore;
|
||||
use std::{net::IpAddr, path::PathBuf};
|
||||
use std::{io, net::IpAddr, path::PathBuf};
|
||||
use tokio::{fs::OpenOptions, io::AsyncWriteExt};
|
||||
use utils::snowflake::SnowflakeIdGenerator;
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::{fs::Permissions, os::unix::fs::PermissionsExt};
|
||||
|
||||
#[cfg(unix)]
|
||||
const DATA_STORE_FILE_MODE: u32 = 0o600;
|
||||
|
||||
pub(crate) enum RegistryInit {
|
||||
Ok(DataStore),
|
||||
Err(String),
|
||||
|
|
@ -34,6 +41,7 @@ impl RegistryStoreInner {
|
|||
local_path,
|
||||
store: Store::None,
|
||||
id_generator: SnowflakeIdGenerator::new(),
|
||||
process_nonce: rand::random(),
|
||||
node_id: 0,
|
||||
env_recovery_mode: std::env::var("STALWART_RECOVERY_MODE")
|
||||
.ok()
|
||||
|
|
@ -96,13 +104,32 @@ impl RegistryStore {
|
|||
.caused_by(trc::location!())
|
||||
.reason(err)
|
||||
})?;
|
||||
tokio::fs::write(&self.0.local_path, json_text)
|
||||
let write_error = |err: io::Error| {
|
||||
trc::EventType::Registry(trc::RegistryEvent::LocalWriteError)
|
||||
.into_err()
|
||||
.caused_by(trc::location!())
|
||||
.reason(err)
|
||||
};
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
options.mode(DATA_STORE_FILE_MODE);
|
||||
let mut file = options
|
||||
.open(&self.0.local_path)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
trc::EventType::Registry(trc::RegistryEvent::LocalWriteError)
|
||||
.into_err()
|
||||
.caused_by(trc::location!())
|
||||
.reason(err)
|
||||
})
|
||||
.map_err(write_error)?;
|
||||
#[cfg(unix)]
|
||||
let _ = file
|
||||
.set_permissions(Permissions::from_mode(DATA_STORE_FILE_MODE))
|
||||
.await;
|
||||
file.write_all(json_text.as_bytes())
|
||||
.await
|
||||
.map_err(write_error)?;
|
||||
file.flush().await.map_err(write_error)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/store/src/registry/local/tests.rs"]
|
||||
mod tests;
|
||||
|
|
|
|||
|
|
@ -51,6 +51,10 @@ pub enum RegistryWriteResult {
|
|||
InvalidForeignKey {
|
||||
object_id: ObjectId,
|
||||
},
|
||||
ForeignKeyOutOfScope {
|
||||
object_id: ObjectId,
|
||||
scope: ForeignKeyScope,
|
||||
},
|
||||
PrimaryKeyConflict {
|
||||
property: Property,
|
||||
existing_id: ObjectId,
|
||||
|
|
@ -61,6 +65,12 @@ pub enum RegistryWriteResult {
|
|||
NotSupported,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ForeignKeyScope {
|
||||
Tenant,
|
||||
Account,
|
||||
}
|
||||
|
||||
pub enum RegistryWrite<'x> {
|
||||
Insert {
|
||||
object: &'x Object,
|
||||
|
|
@ -274,8 +284,9 @@ impl RegistryStore {
|
|||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
return Ok(RegistryWriteResult::InvalidForeignKey {
|
||||
return Ok(RegistryWriteResult::ForeignKeyOutOfScope {
|
||||
object_id: *foreign_id,
|
||||
scope: ForeignKeyScope::Tenant,
|
||||
});
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
|
@ -296,8 +307,9 @@ impl RegistryStore {
|
|||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
return Ok(RegistryWriteResult::InvalidForeignKey {
|
||||
return Ok(RegistryWriteResult::ForeignKeyOutOfScope {
|
||||
object_id: *foreign_id,
|
||||
scope: ForeignKeyScope::Account,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -683,6 +695,15 @@ impl<'x> RegistryWrite<'x> {
|
|||
}
|
||||
}
|
||||
|
||||
impl Display for ForeignKeyScope {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
ForeignKeyScope::Tenant => "tenant",
|
||||
ForeignKeyScope::Account => "account",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for RegistryWriteResult {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
|
|
@ -703,6 +724,9 @@ impl Display for RegistryWriteResult {
|
|||
RegistryWriteResult::InvalidForeignKey { object_id } => {
|
||||
write!(f, "Invalid foreign key: {}", object_id)
|
||||
}
|
||||
RegistryWriteResult::ForeignKeyOutOfScope { object_id, scope } => {
|
||||
write!(f, "{object_id} is not in the same {scope} as this object")
|
||||
}
|
||||
RegistryWriteResult::PrimaryKeyConflict {
|
||||
property,
|
||||
existing_id,
|
||||
|
|
|
|||
29
crates/telemetry/Cargo.toml
Normal file
29
crates/telemetry/Cargo.toml
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
[package]
|
||||
name = "telemetry"
|
||||
version = "1.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
trc = { path = "../trc" }
|
||||
ahash = "0.8.12"
|
||||
bytes = "1"
|
||||
http = "1.1"
|
||||
http-body-util = "0.1.5"
|
||||
hyper = { version = "1.12.0", features = ["client", "http1", "http2"] }
|
||||
hyper-util = { version = "0.1.21", features = ["tokio"] }
|
||||
tokio = { version = "1.54", features = ["net", "time", "rt", "sync", "macros"] }
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = ["aws_lc_rs", "tls12"] }
|
||||
rustls = { version = "0.23.46", default-features = false, features = ["std", "aws_lc_rs", "tls12"] }
|
||||
rustls-pki-types = "1"
|
||||
encodify = "1.0"
|
||||
httpdate = "1.0.3"
|
||||
memchr = "2.8"
|
||||
itoa = "1.0.18"
|
||||
zmij = "1.0.23"
|
||||
hashify = "0.3"
|
||||
|
||||
[features]
|
||||
enterprise = ["trc/enterprise"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
68
crates/telemetry/src/exporter/metrics.rs
Normal file
68
crates/telemetry/src/exporter/metrics.rs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{OtlpConfig, unix_nanos, unix_nanos_now};
|
||||
use crate::{
|
||||
otlp::{metrics::encode_metrics, request::RequestBuilder, resource::Resource},
|
||||
transport::{
|
||||
TransportError,
|
||||
endpoint::Signal,
|
||||
sender::{Outcome, Sender},
|
||||
},
|
||||
};
|
||||
use std::time::{Duration, SystemTime};
|
||||
use tokio::time::Instant;
|
||||
use trc::TelemetryEvent;
|
||||
|
||||
pub struct OtlpMetricsExporter {
|
||||
sender: Sender,
|
||||
resource: Resource,
|
||||
builder: RequestBuilder,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl OtlpMetricsExporter {
|
||||
pub fn new(config: OtlpConfig, resource: Resource) -> Result<Self, TransportError> {
|
||||
let seed = u64::from_be_bytes(resource.trace_prefix) ^ Signal::Metrics as u64;
|
||||
Ok(Self {
|
||||
sender: config.sender(Signal::Metrics, seed)?,
|
||||
builder: RequestBuilder::new(&resource, config.framing()),
|
||||
timeout: config.timeout(),
|
||||
resource,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn push(&mut self, is_enterprise: bool, start_time: SystemTime, interval: Duration) {
|
||||
encode_metrics(
|
||||
&mut self.builder,
|
||||
is_enterprise,
|
||||
unix_nanos(start_time),
|
||||
unix_nanos_now(),
|
||||
);
|
||||
let Some(request) = self.builder.seal(&self.resource) else {
|
||||
return;
|
||||
};
|
||||
let deadline = Instant::now() + self.timeout.min(interval);
|
||||
match self.sender.send(request.body, deadline).await {
|
||||
Outcome::Delivered => {}
|
||||
Outcome::PartialSuccess { rejected, message } => {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelMetricsExporterError),
|
||||
Details = "Metrics partially rejected by the collector",
|
||||
Total = rejected,
|
||||
Reason = message,
|
||||
);
|
||||
}
|
||||
Outcome::Rejected { reason } | Outcome::Deferred { reason } => {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelMetricsExporterError),
|
||||
Details = "Failed to export metrics",
|
||||
Reason = reason,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
371
crates/telemetry/src/exporter/mod.rs
Normal file
371
crates/telemetry/src/exporter/mod.rs
Normal file
|
|
@ -0,0 +1,371 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub mod metrics;
|
||||
pub mod queue;
|
||||
pub mod spans;
|
||||
|
||||
use crate::{
|
||||
otlp::{
|
||||
logs::encode_log,
|
||||
request::{Framing, RequestBuilder},
|
||||
resource::Resource,
|
||||
traces::encode_span,
|
||||
value::ValueEncoder,
|
||||
},
|
||||
transport::{
|
||||
TransportError,
|
||||
conn::tls_connector,
|
||||
endpoint::{Endpoint, Signal, Transport},
|
||||
sender::{Headers, Outcome, Sender},
|
||||
},
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use queue::{SignalKind, SignalQueue};
|
||||
use rustls::ClientConfig;
|
||||
use spans::{SpanTracker, report_discarded_spans, tracks_span};
|
||||
use std::{
|
||||
future::{Future, poll_fn},
|
||||
pin::{Pin, pin},
|
||||
sync::Arc,
|
||||
task::Poll,
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::time::{Instant, sleep_until, timeout_at};
|
||||
use trc::ipc::subscriber::{EventBatch, SharedInterests, SubscriberBuilder};
|
||||
|
||||
pub const DEFAULT_MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024;
|
||||
pub const DEFAULT_MAX_PENDING_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_REQUEST_BYTES: usize = 64 * 1024 * 1024;
|
||||
const MAX_DRAIN_TIME: Duration = Duration::from_millis(800);
|
||||
const MIN_EXPORT_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
const IDLE_WAKEUP: Duration = Duration::from_secs(365 * 24 * 60 * 60);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct OtlpConfig {
|
||||
pub endpoint: Endpoint,
|
||||
pub transport: Transport,
|
||||
pub headers: Headers,
|
||||
pub tls: Arc<ClientConfig>,
|
||||
pub timeout: Duration,
|
||||
pub max_request_bytes: usize,
|
||||
pub max_pending_bytes: usize,
|
||||
}
|
||||
|
||||
pub struct OtlpTracer {
|
||||
pub otlp: OtlpConfig,
|
||||
pub resource: Resource,
|
||||
pub throttle: Duration,
|
||||
pub export_logs: bool,
|
||||
pub export_spans: bool,
|
||||
}
|
||||
|
||||
struct TracerState {
|
||||
resource: Resource,
|
||||
throttle: Duration,
|
||||
timeout: Duration,
|
||||
max_request_bytes: usize,
|
||||
max_pending_bytes: usize,
|
||||
logs: Option<SignalQueue>,
|
||||
spans: Option<SignalQueue>,
|
||||
tracker: SpanTracker,
|
||||
values: ValueEncoder,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for OtlpConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("OtlpConfig")
|
||||
.field("endpoint", &self.endpoint)
|
||||
.field("transport", &self.transport)
|
||||
.field("timeout", &self.timeout)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for OtlpTracer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("OtlpTracer")
|
||||
.field("otlp", &self.otlp)
|
||||
.field("throttle", &self.throttle)
|
||||
.field("export_logs", &self.export_logs)
|
||||
.field("export_spans", &self.export_spans)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl OtlpConfig {
|
||||
fn framing(&self) -> Framing {
|
||||
match self.transport {
|
||||
Transport::Http => Framing::Http,
|
||||
Transport::Grpc => Framing::Grpc,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sender(&self, signal: Signal, seed: u64) -> Result<Sender, TransportError> {
|
||||
Sender::new(
|
||||
self.endpoint.clone(),
|
||||
self.transport,
|
||||
signal,
|
||||
self.headers.clone(),
|
||||
self.endpoint
|
||||
.is_tls()
|
||||
.then(|| tls_connector(&self.tls, self.transport)),
|
||||
seed,
|
||||
)
|
||||
}
|
||||
|
||||
fn max_request_bytes(&self) -> usize {
|
||||
self.max_request_bytes.clamp(1, MAX_REQUEST_BYTES)
|
||||
}
|
||||
|
||||
fn timeout(&self) -> Duration {
|
||||
self.timeout.max(MIN_EXPORT_TIMEOUT)
|
||||
}
|
||||
}
|
||||
|
||||
impl OtlpTracer {
|
||||
pub fn spawn(self, builder: SubscriberBuilder) -> Result<(), TransportError> {
|
||||
let seed = u64::from_be_bytes(self.resource.trace_prefix);
|
||||
let queue = |kind: SignalKind, signal: Signal, enabled: bool| {
|
||||
enabled
|
||||
.then(|| {
|
||||
self.otlp
|
||||
.sender(signal, seed ^ signal as u64)
|
||||
.map(|sender| {
|
||||
SignalQueue::new(
|
||||
kind,
|
||||
RequestBuilder::new(&self.resource, self.otlp.framing()),
|
||||
sender,
|
||||
)
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let logs = queue(SignalKind::Logs, Signal::Logs, self.export_logs)?;
|
||||
let spans = queue(SignalKind::Spans, Signal::Traces, self.export_spans)?;
|
||||
let state = TracerState {
|
||||
throttle: self.throttle,
|
||||
timeout: self.otlp.timeout(),
|
||||
max_request_bytes: self.otlp.max_request_bytes(),
|
||||
max_pending_bytes: self.otlp.max_pending_bytes,
|
||||
resource: self.resource,
|
||||
logs,
|
||||
spans,
|
||||
tracker: SpanTracker::default(),
|
||||
values: ValueEncoder::default(),
|
||||
};
|
||||
let (_, rx, interests) = builder.register();
|
||||
tokio::spawn(state.run(rx, interests));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TracerState {
|
||||
async fn run(
|
||||
mut self,
|
||||
mut rx: tokio::sync::mpsc::Receiver<EventBatch>,
|
||||
interests: SharedInterests,
|
||||
) {
|
||||
let mut logs_slot = pin!(None::<(Sender, Bytes, Instant)>.map(start_send));
|
||||
let mut spans_slot = pin!(None::<(Sender, Bytes, Instant)>.map(start_send));
|
||||
let timer = sleep_until(Instant::now() + IDLE_WAKEUP);
|
||||
let mut timer = pin!(timer);
|
||||
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
let deadline = now + self.timeout;
|
||||
if logs_slot.is_none()
|
||||
&& let Some((sender, body)) = self
|
||||
.logs
|
||||
.as_mut()
|
||||
.and_then(|queue| queue.next_send(&self.resource, self.throttle, now))
|
||||
{
|
||||
logs_slot.set(Some(start_send((sender, body, deadline))));
|
||||
}
|
||||
if spans_slot.is_none()
|
||||
&& let Some((sender, body)) = self
|
||||
.spans
|
||||
.as_mut()
|
||||
.and_then(|queue| queue.next_send(&self.resource, self.throttle, now))
|
||||
{
|
||||
spans_slot.set(Some(start_send((sender, body, deadline))));
|
||||
}
|
||||
let wake_at = [&self.logs, &self.spans]
|
||||
.into_iter()
|
||||
.filter_map(|queue| {
|
||||
queue
|
||||
.as_ref()
|
||||
.and_then(|queue| queue.wake_at(self.throttle))
|
||||
})
|
||||
.min()
|
||||
.unwrap_or(now + IDLE_WAKEUP);
|
||||
if timer.deadline() != wake_at {
|
||||
timer.as_mut().reset(wake_at);
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
biased;
|
||||
(sender, outcome) = poll_slot(logs_slot.as_mut()), if logs_slot.is_some() => {
|
||||
logs_slot.set(None);
|
||||
if let Some(queue) = self.logs.as_mut() {
|
||||
queue.complete(sender, outcome, self.throttle);
|
||||
}
|
||||
}
|
||||
(sender, outcome) = poll_slot(spans_slot.as_mut()), if spans_slot.is_some() => {
|
||||
spans_slot.set(None);
|
||||
if let Some(queue) = self.spans.as_mut() {
|
||||
queue.complete(sender, outcome, self.throttle);
|
||||
}
|
||||
}
|
||||
_ = timer.as_mut() => {}
|
||||
batch = rx.recv() => match batch {
|
||||
Some(events) => self.encode(events, &interests),
|
||||
None => break,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let drain_deadline = Instant::now() + self.timeout.min(MAX_DRAIN_TIME);
|
||||
let resource = &self.resource;
|
||||
tokio::join!(
|
||||
drain(
|
||||
self.logs.as_mut(),
|
||||
logs_slot,
|
||||
resource,
|
||||
self.throttle,
|
||||
drain_deadline
|
||||
),
|
||||
drain(
|
||||
self.spans.as_mut(),
|
||||
spans_slot,
|
||||
resource,
|
||||
self.throttle,
|
||||
drain_deadline
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fn encode(&mut self, events: EventBatch, interests: &SharedInterests) {
|
||||
let now = Instant::now();
|
||||
let observed = unix_nanos_now();
|
||||
let trace_prefix = self.resource.trace_prefix;
|
||||
if self.spans.is_some()
|
||||
&& let Some(event) = events.last()
|
||||
{
|
||||
self.tracker.sweep(event.inner.timestamp);
|
||||
}
|
||||
|
||||
for event in events {
|
||||
if let Some(logs) = self.logs.as_mut()
|
||||
&& logs.has_room(self.max_pending_bytes)
|
||||
{
|
||||
encode_log(
|
||||
logs.builder(),
|
||||
&mut self.values,
|
||||
&event,
|
||||
observed,
|
||||
&trace_prefix,
|
||||
);
|
||||
logs.record_added(&self.resource, self.max_request_bytes, now);
|
||||
}
|
||||
|
||||
if let Some(spans) = self.spans.as_mut()
|
||||
&& let Some(span) = event.inner.span.as_ref()
|
||||
&& let Some(span_id) = span.span_id()
|
||||
{
|
||||
if !event.inner.typ.is_span_end() {
|
||||
if tracks_span(interests, span) {
|
||||
self.tracker.track(span_id, event);
|
||||
}
|
||||
} else if let Some(span_events) = self.tracker.finish(span_id)
|
||||
&& spans.has_room(self.max_pending_bytes)
|
||||
&& encode_span(
|
||||
spans.builder(),
|
||||
&mut self.values,
|
||||
span,
|
||||
&event,
|
||||
span_events.iter().map(AsRef::as_ref),
|
||||
&trace_prefix,
|
||||
)
|
||||
{
|
||||
spans.record_added(&self.resource, self.max_request_bytes, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((events, spans)) = self.tracker.take_discarded() {
|
||||
report_discarded_spans(events, spans);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_send(
|
||||
(sender, body, deadline): (Sender, Bytes, Instant),
|
||||
) -> impl Future<Output = (Sender, Outcome)> {
|
||||
sender.run(body, deadline)
|
||||
}
|
||||
|
||||
fn poll_slot<F: Future>(mut slot: Pin<&mut Option<F>>) -> impl Future<Output = F::Output> + '_ {
|
||||
poll_fn(move |cx| match slot.as_mut().as_pin_mut() {
|
||||
Some(future) => future.poll(cx),
|
||||
None => Poll::Pending,
|
||||
})
|
||||
}
|
||||
|
||||
async fn drain<F: Future<Output = (Sender, Outcome)>>(
|
||||
queue: Option<&mut SignalQueue>,
|
||||
slot: Pin<&mut Option<F>>,
|
||||
resource: &Resource,
|
||||
throttle: Duration,
|
||||
deadline: Instant,
|
||||
) {
|
||||
if let Some(queue) = queue {
|
||||
drain_queue(queue, slot, resource, throttle, deadline).await;
|
||||
queue.report_unsent();
|
||||
}
|
||||
}
|
||||
|
||||
async fn drain_queue<F: Future<Output = (Sender, Outcome)>>(
|
||||
queue: &mut SignalQueue,
|
||||
mut slot: Pin<&mut Option<F>>,
|
||||
resource: &Resource,
|
||||
throttle: Duration,
|
||||
deadline: Instant,
|
||||
) {
|
||||
if slot.is_some() {
|
||||
match timeout_at(deadline, poll_slot(slot.as_mut())).await {
|
||||
Ok((sender, outcome)) => queue.complete(sender, outcome, throttle),
|
||||
Err(_) => return,
|
||||
}
|
||||
slot.set(None);
|
||||
}
|
||||
queue.seal(resource);
|
||||
while let Some((mut sender, body)) = queue.take_sender() {
|
||||
if Instant::now() >= deadline {
|
||||
return;
|
||||
}
|
||||
let outcome = sender.send(body, deadline).await;
|
||||
let deferred = matches!(outcome, Outcome::Deferred { .. });
|
||||
queue.complete(sender, outcome, throttle);
|
||||
if deferred {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unix_nanos_now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |elapsed| {
|
||||
u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn unix_nanos(time: SystemTime) -> u64 {
|
||||
time.duration_since(UNIX_EPOCH).map_or(0, |elapsed| {
|
||||
u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX)
|
||||
})
|
||||
}
|
||||
264
crates/telemetry/src/exporter/queue.rs
Normal file
264
crates/telemetry/src/exporter/queue.rs
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
otlp::{
|
||||
request::{RequestBuilder, SealedRequest},
|
||||
resource::Resource,
|
||||
},
|
||||
transport::sender::{Outcome, Sender},
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use std::{collections::VecDeque, time::Duration};
|
||||
use tokio::time::Instant;
|
||||
use trc::TelemetryEvent;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SignalKind {
|
||||
Logs,
|
||||
Spans,
|
||||
}
|
||||
|
||||
pub struct SignalQueue {
|
||||
kind: SignalKind,
|
||||
builder: RequestBuilder,
|
||||
queue: VecDeque<SealedRequest>,
|
||||
queued_bytes: usize,
|
||||
opened_at: Option<Instant>,
|
||||
retry_at: Option<Instant>,
|
||||
sender: Option<Sender>,
|
||||
discarded: u64,
|
||||
oversized: u64,
|
||||
}
|
||||
|
||||
impl SignalKind {
|
||||
fn discarded_details(self) -> &'static str {
|
||||
match self {
|
||||
SignalKind::Logs => "Log export queue full, discarded logs",
|
||||
SignalKind::Spans => "Span export queue full, discarded spans",
|
||||
}
|
||||
}
|
||||
|
||||
fn oversized_details(self) -> &'static str {
|
||||
match self {
|
||||
SignalKind::Logs => "Log record exceeds the request size limit, discarded logs",
|
||||
SignalKind::Spans => "Span exceeds the request size limit, discarded spans",
|
||||
}
|
||||
}
|
||||
|
||||
fn unsent_details(self) -> &'static str {
|
||||
match self {
|
||||
SignalKind::Logs => "Logs not exported before shutdown, discarded",
|
||||
SignalKind::Spans => "Spans not exported before shutdown, discarded",
|
||||
}
|
||||
}
|
||||
|
||||
fn failed_details(self) -> &'static str {
|
||||
match self {
|
||||
SignalKind::Logs => "Failed to export logs",
|
||||
SignalKind::Spans => "Failed to export spans",
|
||||
}
|
||||
}
|
||||
|
||||
fn deferred_details(self) -> &'static str {
|
||||
match self {
|
||||
SignalKind::Logs => "Failed to export logs, will retry",
|
||||
SignalKind::Spans => "Failed to export spans, will retry",
|
||||
}
|
||||
}
|
||||
|
||||
fn partial_details(self) -> &'static str {
|
||||
match self {
|
||||
SignalKind::Logs => "Logs partially rejected by the collector",
|
||||
SignalKind::Spans => "Spans partially rejected by the collector",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SignalQueue {
|
||||
pub fn new(kind: SignalKind, builder: RequestBuilder, sender: Sender) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
builder,
|
||||
queue: VecDeque::new(),
|
||||
queued_bytes: 0,
|
||||
opened_at: None,
|
||||
retry_at: None,
|
||||
sender: Some(sender),
|
||||
discarded: 0,
|
||||
oversized: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn builder(&mut self) -> &mut RequestBuilder {
|
||||
&mut self.builder
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn has_room(&mut self, max_pending_bytes: usize) -> bool {
|
||||
if self.queued_bytes + self.builder.capacity() < max_pending_bytes {
|
||||
true
|
||||
} else {
|
||||
self.discarded += 1;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn record_added(&mut self, resource: &Resource, max_request_bytes: usize, now: Instant) {
|
||||
if self.opened_at.is_none() {
|
||||
self.opened_at = Some(now);
|
||||
}
|
||||
if self.builder.body_len_bound() > max_request_bytes {
|
||||
self.split(resource, max_request_bytes, now);
|
||||
}
|
||||
}
|
||||
|
||||
#[cold]
|
||||
#[inline(never)]
|
||||
fn split(&mut self, resource: &Resource, max_request_bytes: usize, now: Instant) {
|
||||
if let Some(request) = self.builder.seal_before_last(resource) {
|
||||
self.push(request);
|
||||
self.opened_at = Some(now);
|
||||
}
|
||||
if self.builder.body_len_bound() > max_request_bytes {
|
||||
self.builder.discard();
|
||||
self.oversized += 1;
|
||||
self.opened_at = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn seal(&mut self, resource: &Resource) {
|
||||
if let Some(request) = self.builder.seal(resource) {
|
||||
self.push(request);
|
||||
}
|
||||
self.opened_at = None;
|
||||
}
|
||||
|
||||
fn push(&mut self, request: SealedRequest) {
|
||||
self.queued_bytes += request.capacity;
|
||||
self.queue.push_back(request);
|
||||
}
|
||||
|
||||
pub fn next_send(
|
||||
&mut self,
|
||||
resource: &Resource,
|
||||
throttle: Duration,
|
||||
now: Instant,
|
||||
) -> Option<(Sender, Bytes)> {
|
||||
self.sender.as_ref()?;
|
||||
if self.retry_at.is_some_and(|retry_at| now < retry_at) {
|
||||
return None;
|
||||
}
|
||||
self.retry_at = None;
|
||||
self.report_discarded();
|
||||
if self.queue.is_empty()
|
||||
&& self
|
||||
.opened_at
|
||||
.is_some_and(|opened_at| now >= opened_at + throttle)
|
||||
{
|
||||
self.seal(resource);
|
||||
}
|
||||
let body = self.queue.front()?.body.clone();
|
||||
self.sender.take().map(|sender| (sender, body))
|
||||
}
|
||||
|
||||
pub fn wake_at(&self, throttle: Duration) -> Option<Instant> {
|
||||
if self.sender.is_none() {
|
||||
None
|
||||
} else if let Some(retry_at) = self.retry_at {
|
||||
Some(retry_at)
|
||||
} else if self.queue.is_empty() {
|
||||
self.opened_at.map(|opened_at| opened_at + throttle)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_sender(&mut self) -> Option<(Sender, Bytes)> {
|
||||
let body = self.queue.front()?.body.clone();
|
||||
self.sender.take().map(|sender| (sender, body))
|
||||
}
|
||||
|
||||
pub fn complete(&mut self, sender: Sender, outcome: Outcome, throttle: Duration) {
|
||||
let next_attempt_at = sender.next_attempt_at();
|
||||
self.sender = Some(sender);
|
||||
match outcome {
|
||||
Outcome::Delivered => self.pop(),
|
||||
Outcome::PartialSuccess { rejected, message } => {
|
||||
self.pop();
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = self.kind.partial_details(),
|
||||
Total = rejected,
|
||||
Reason = message,
|
||||
);
|
||||
}
|
||||
Outcome::Rejected { reason } => {
|
||||
if let Some(request) = self.queue.front() {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = self.kind.failed_details(),
|
||||
Total = request.records,
|
||||
Reason = reason,
|
||||
);
|
||||
}
|
||||
self.pop();
|
||||
}
|
||||
Outcome::Deferred { reason } => {
|
||||
let min_retry_at = Instant::now() + throttle;
|
||||
self.retry_at =
|
||||
Some(next_attempt_at.map_or(min_retry_at, |at| at.max(min_retry_at)));
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = self.kind.deferred_details(),
|
||||
Reason = reason,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pop(&mut self) {
|
||||
if let Some(request) = self.queue.pop_front() {
|
||||
self.queued_bytes -= request.capacity;
|
||||
}
|
||||
}
|
||||
|
||||
fn report_discarded(&mut self) {
|
||||
if self.discarded > 0 {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = self.kind.discarded_details(),
|
||||
Total = std::mem::take(&mut self.discarded),
|
||||
);
|
||||
}
|
||||
if self.oversized > 0 {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = self.kind.oversized_details(),
|
||||
Total = std::mem::take(&mut self.oversized),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn report_unsent(&mut self) {
|
||||
self.report_discarded();
|
||||
let unsent = self
|
||||
.queue
|
||||
.iter()
|
||||
.map(|request| request.records)
|
||||
.sum::<usize>()
|
||||
+ self.builder.records();
|
||||
if unsent > 0 {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::OtelExporterError),
|
||||
Details = self.kind.unsent_details(),
|
||||
Total = unsent,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -20,7 +20,7 @@ const PRESSURE_MAX_HOLD: u64 = 60 * 60;
|
|||
type SpanEvents = Vec<Arc<Event<EventDetails>>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SpanTracker {
|
||||
pub struct SpanTracker {
|
||||
spans: AHashMap<u64, SpanEvents>,
|
||||
tracked_events: usize,
|
||||
discarded_events: usize,
|
||||
|
|
@ -98,14 +98,14 @@ impl SpanTracker {
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn tracks_span(interests: &SharedInterests, span: &Event<EventDetails>) -> bool {
|
||||
pub fn tracks_span(interests: &SharedInterests, span: &Event<EventDetails>) -> bool {
|
||||
span.inner
|
||||
.typ
|
||||
.span_end()
|
||||
.is_some_and(|span_end| interests.get(span_end.to_id() as usize))
|
||||
}
|
||||
|
||||
pub(crate) fn report_discarded_spans(events: usize, spans: usize) {
|
||||
pub fn report_discarded_spans(events: usize, spans: usize) {
|
||||
if events > 0 {
|
||||
trc::event!(
|
||||
Telemetry(TelemetryEvent::EventsDropped),
|
||||
|
|
@ -124,5 +124,5 @@ pub(crate) fn report_discarded_spans(events: usize, spans: usize) {
|
|||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../../stalwart-tests/unit/common/src/telemetry/tracers/spans/tests.rs"]
|
||||
#[path = "../../../../../stalwart-tests/unit/telemetry/src/exporter/spans/tests.rs"]
|
||||
mod tests;
|
||||
12
crates/telemetry/src/lib.rs
Normal file
12
crates/telemetry/src/lib.rs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub mod exporter;
|
||||
pub mod metrics;
|
||||
pub mod otlp;
|
||||
pub mod prometheus;
|
||||
pub mod proto;
|
||||
pub mod transport;
|
||||
67
crates/telemetry/src/metrics.rs
Normal file
67
crates/telemetry/src/metrics.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use trc::atomics::histogram::AtomicHistogram;
|
||||
|
||||
pub const HISTOGRAM_BUCKETS: usize = 12;
|
||||
pub const HISTOGRAM_BOUNDS: usize = HISTOGRAM_BUCKETS - 1;
|
||||
const SECONDS_UNIT: &str = "s";
|
||||
const MILLIS_PER_SECOND: f64 = 1000.0;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MetricScale {
|
||||
Identity,
|
||||
MillisToSeconds,
|
||||
}
|
||||
|
||||
pub struct HistogramSnapshot {
|
||||
pub buckets: [u64; HISTOGRAM_BUCKETS],
|
||||
pub bounds: [u64; HISTOGRAM_BOUNDS],
|
||||
pub count: u64,
|
||||
pub sum: u64,
|
||||
pub min: Option<u64>,
|
||||
pub max: Option<u64>,
|
||||
}
|
||||
|
||||
impl MetricScale {
|
||||
#[inline(always)]
|
||||
pub fn from_otel_unit(unit: &str) -> Self {
|
||||
if unit == SECONDS_UNIT {
|
||||
MetricScale::MillisToSeconds
|
||||
} else {
|
||||
MetricScale::Identity
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn apply(self, value: u64) -> f64 {
|
||||
match self {
|
||||
MetricScale::Identity => value as f64,
|
||||
MetricScale::MillisToSeconds => value as f64 / MILLIS_PER_SECOND,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistogramSnapshot {
|
||||
pub fn new(histogram: &AtomicHistogram<HISTOGRAM_BUCKETS>) -> Self {
|
||||
let mut buckets = [0u64; HISTOGRAM_BUCKETS];
|
||||
for (slot, value) in buckets.iter_mut().zip(histogram.buckets_iter()) {
|
||||
*slot = value;
|
||||
}
|
||||
let mut bounds = [0u64; HISTOGRAM_BOUNDS];
|
||||
for (slot, value) in bounds.iter_mut().zip(histogram.upper_bounds_iter()) {
|
||||
*slot = value;
|
||||
}
|
||||
Self {
|
||||
count: buckets.iter().sum(),
|
||||
buckets,
|
||||
bounds,
|
||||
sum: histogram.sum(),
|
||||
min: histogram.min(),
|
||||
max: histogram.max(),
|
||||
}
|
||||
}
|
||||
}
|
||||
90
crates/telemetry/src/otlp/logs.rs
Normal file
90
crates/telemetry/src/otlp/logs.rs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{request::RequestBuilder, span_id_value, trace_id, unix_nanos, value::ValueEncoder};
|
||||
use crate::proto::writer::LenHint;
|
||||
use trc::{Event, EventDetails, Key, Level, event::KeySet};
|
||||
|
||||
const SCOPE_LOG_RECORDS: u32 = 2;
|
||||
|
||||
const LOG_TIME: u32 = 1;
|
||||
const LOG_SEVERITY_NUMBER: u32 = 2;
|
||||
const LOG_SEVERITY_TEXT: u32 = 3;
|
||||
const LOG_BODY: u32 = 5;
|
||||
const LOG_ATTRIBUTES: u32 = 6;
|
||||
const LOG_FLAGS: u32 = 8;
|
||||
const LOG_TRACE_ID: u32 = 9;
|
||||
const LOG_SPAN_ID: u32 = 10;
|
||||
const LOG_OBSERVED_TIME: u32 = 11;
|
||||
const LOG_EVENT_NAME: u32 = 12;
|
||||
|
||||
const ANY_STRING: u32 = 1;
|
||||
const TRACE_FLAG_SAMPLED: u32 = 0x01;
|
||||
|
||||
const SEVERITY_TRACE: u64 = 1;
|
||||
const SEVERITY_DEBUG: u64 = 5;
|
||||
const SEVERITY_INFO: u64 = 9;
|
||||
const SEVERITY_WARN: u64 = 13;
|
||||
const SEVERITY_ERROR: u64 = 17;
|
||||
|
||||
#[inline(always)]
|
||||
fn severity_number(level: Level) -> u64 {
|
||||
match level {
|
||||
Level::Trace => SEVERITY_TRACE,
|
||||
Level::Debug => SEVERITY_DEBUG,
|
||||
Level::Info => SEVERITY_INFO,
|
||||
Level::Warn => SEVERITY_WARN,
|
||||
Level::Error | Level::Disable => SEVERITY_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode_log(
|
||||
request: &mut RequestBuilder,
|
||||
values: &mut ValueEncoder,
|
||||
event: &Event<EventDetails>,
|
||||
observed_unix_nano: u64,
|
||||
trace_prefix: &[u8; 8],
|
||||
) {
|
||||
let w = request.writer();
|
||||
let description = event.inner.typ.description();
|
||||
|
||||
let record = w.begin(SCOPE_LOG_RECORDS, LenHint::Medium);
|
||||
w.fixed64(LOG_TIME, unix_nanos(event.inner.timestamp));
|
||||
w.uint64(LOG_SEVERITY_NUMBER, severity_number(event.inner.level));
|
||||
w.bytes(LOG_SEVERITY_TEXT, event.inner.level.as_str().as_bytes());
|
||||
w.len_prefix(
|
||||
LOG_BODY,
|
||||
crate::proto::len_field_len(ANY_STRING, description.len()),
|
||||
);
|
||||
w.bytes_always(ANY_STRING, description.as_bytes());
|
||||
|
||||
let mut span_id = 0u64;
|
||||
let mut seen_keys = KeySet::default();
|
||||
let span_keys = event
|
||||
.inner
|
||||
.span
|
||||
.as_ref()
|
||||
.map_or(&[][..], |span| span.keys.as_slice());
|
||||
for (pos, (key, value)) in event.keys.iter().chain(span_keys).enumerate() {
|
||||
if *key == Key::SpanId {
|
||||
if pos < event.keys.len() && span_id == 0 {
|
||||
span_id = span_id_value(value);
|
||||
}
|
||||
} else if seen_keys.insert(*key) {
|
||||
values.key_value(w, LOG_ATTRIBUTES, *key, value);
|
||||
}
|
||||
}
|
||||
|
||||
if span_id != 0 {
|
||||
w.fixed32(LOG_FLAGS, TRACE_FLAG_SAMPLED);
|
||||
w.bytes_always(LOG_TRACE_ID, &trace_id(trace_prefix, span_id));
|
||||
w.bytes_always(LOG_SPAN_ID, &span_id.to_be_bytes());
|
||||
}
|
||||
w.fixed64(LOG_OBSERVED_TIME, observed_unix_nano);
|
||||
w.bytes(LOG_EVENT_NAME, event.inner.typ.as_str().as_bytes());
|
||||
w.end(record);
|
||||
request.commit();
|
||||
}
|
||||
146
crates/telemetry/src/otlp/metrics.rs
Normal file
146
crates/telemetry/src/otlp/metrics.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::request::RequestBuilder;
|
||||
use crate::{
|
||||
metrics::{HistogramSnapshot, MetricScale},
|
||||
proto::writer::{LenHint, ProtoWriter},
|
||||
};
|
||||
use trc::Collector;
|
||||
|
||||
const SCOPE_METRICS: u32 = 2;
|
||||
|
||||
const METRIC_NAME: u32 = 1;
|
||||
const METRIC_DESCRIPTION: u32 = 2;
|
||||
const METRIC_UNIT: u32 = 3;
|
||||
const METRIC_GAUGE: u32 = 5;
|
||||
const METRIC_SUM: u32 = 7;
|
||||
const METRIC_HISTOGRAM: u32 = 9;
|
||||
|
||||
const DATA_POINTS: u32 = 1;
|
||||
const AGGREGATION_TEMPORALITY: u32 = 2;
|
||||
const SUM_IS_MONOTONIC: u32 = 3;
|
||||
const TEMPORALITY_CUMULATIVE: u64 = 2;
|
||||
|
||||
const POINT_START_TIME: u32 = 2;
|
||||
const POINT_TIME: u32 = 3;
|
||||
const NUMBER_AS_DOUBLE: u32 = 4;
|
||||
const NUMBER_AS_INT: u32 = 6;
|
||||
|
||||
const HISTOGRAM_COUNT: u32 = 4;
|
||||
const HISTOGRAM_SUM: u32 = 5;
|
||||
const HISTOGRAM_BUCKET_COUNTS: u32 = 6;
|
||||
const HISTOGRAM_EXPLICIT_BOUNDS: u32 = 7;
|
||||
const HISTOGRAM_MIN: u32 = 11;
|
||||
const HISTOGRAM_MAX: u32 = 12;
|
||||
|
||||
const COUNTER_UNIT: &str = "{event}";
|
||||
|
||||
pub fn encode_metrics(
|
||||
request: &mut RequestBuilder,
|
||||
is_enterprise: bool,
|
||||
start_unix_nano: u64,
|
||||
now_unix_nano: u64,
|
||||
) {
|
||||
for counter in Collector::collect_counters(is_enterprise) {
|
||||
let event = counter.id();
|
||||
let name = event.otel_metric_name();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let w = request.writer();
|
||||
let metric = begin_metric(w, name, event.description(), COUNTER_UNIT);
|
||||
let sum = w.begin(METRIC_SUM, LenHint::Small);
|
||||
let point = w.begin(DATA_POINTS, LenHint::Small);
|
||||
w.fixed64(POINT_START_TIME, start_unix_nano);
|
||||
w.fixed64(POINT_TIME, now_unix_nano);
|
||||
w.sfixed64_always(NUMBER_AS_INT, saturating_i64(counter.value()));
|
||||
w.end(point);
|
||||
w.uint64(AGGREGATION_TEMPORALITY, TEMPORALITY_CUMULATIVE);
|
||||
w.bool_always(SUM_IS_MONOTONIC, true);
|
||||
w.end(sum);
|
||||
w.end(metric);
|
||||
request.commit();
|
||||
}
|
||||
|
||||
for gauge in Collector::collect_gauges(is_enterprise) {
|
||||
let metric_type = gauge.id();
|
||||
let name = metric_type.otel_name();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let unit = metric_type.otel_unit();
|
||||
let w = request.writer();
|
||||
let metric = begin_metric(w, name, metric_type.description(), unit);
|
||||
let gauge_msg = w.begin(METRIC_GAUGE, LenHint::Small);
|
||||
let point = w.begin(DATA_POINTS, LenHint::Small);
|
||||
w.fixed64(POINT_TIME, now_unix_nano);
|
||||
match MetricScale::from_otel_unit(unit) {
|
||||
MetricScale::Identity => {
|
||||
w.sfixed64_always(NUMBER_AS_INT, saturating_i64(gauge.get()));
|
||||
}
|
||||
scale => w.double_always(NUMBER_AS_DOUBLE, scale.apply(gauge.get())),
|
||||
}
|
||||
w.end(point);
|
||||
w.end(gauge_msg);
|
||||
w.end(metric);
|
||||
request.commit();
|
||||
}
|
||||
|
||||
for histogram in Collector::collect_histograms(is_enterprise) {
|
||||
let metric_type = histogram.id();
|
||||
let name = metric_type.otel_name();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let unit = metric_type.otel_unit();
|
||||
let scale = MetricScale::from_otel_unit(unit);
|
||||
let snapshot = HistogramSnapshot::new(histogram);
|
||||
let w = request.writer();
|
||||
let metric = begin_metric(w, name, metric_type.description(), unit);
|
||||
let histogram_msg = w.begin(METRIC_HISTOGRAM, LenHint::Medium);
|
||||
let point = w.begin(DATA_POINTS, LenHint::Medium);
|
||||
w.fixed64(POINT_START_TIME, start_unix_nano);
|
||||
w.fixed64(POINT_TIME, now_unix_nano);
|
||||
w.fixed64_always(HISTOGRAM_COUNT, snapshot.count);
|
||||
w.double_always(HISTOGRAM_SUM, scale.apply(snapshot.sum));
|
||||
w.packed_fixed64(HISTOGRAM_BUCKET_COUNTS, snapshot.buckets.iter().copied());
|
||||
w.packed_double(
|
||||
HISTOGRAM_EXPLICIT_BOUNDS,
|
||||
snapshot.bounds.iter().map(|bound| scale.apply(*bound)),
|
||||
);
|
||||
if let Some(min) = snapshot.min {
|
||||
w.double_always(HISTOGRAM_MIN, scale.apply(min));
|
||||
}
|
||||
if let Some(max) = snapshot.max {
|
||||
w.double_always(HISTOGRAM_MAX, scale.apply(max));
|
||||
}
|
||||
w.end(point);
|
||||
w.uint64(AGGREGATION_TEMPORALITY, TEMPORALITY_CUMULATIVE);
|
||||
w.end(histogram_msg);
|
||||
w.end(metric);
|
||||
request.commit();
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn begin_metric(
|
||||
w: &mut ProtoWriter,
|
||||
name: &str,
|
||||
description: &str,
|
||||
unit: &str,
|
||||
) -> crate::proto::writer::Nested {
|
||||
let metric = w.begin(SCOPE_METRICS, LenHint::Medium);
|
||||
w.bytes(METRIC_NAME, name.as_bytes());
|
||||
w.bytes(METRIC_DESCRIPTION, description.as_bytes());
|
||||
w.bytes(METRIC_UNIT, unit.as_bytes());
|
||||
metric
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn saturating_i64(value: u64) -> i64 {
|
||||
i64::try_from(value).unwrap_or(i64::MAX)
|
||||
}
|
||||
39
crates/telemetry/src/otlp/mod.rs
Normal file
39
crates/telemetry/src/otlp/mod.rs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub mod logs;
|
||||
pub mod metrics;
|
||||
pub mod request;
|
||||
pub mod resource;
|
||||
pub mod traces;
|
||||
pub mod value;
|
||||
|
||||
use trc::Value;
|
||||
|
||||
const NANOS_PER_SECOND: u64 = 1_000_000_000;
|
||||
|
||||
#[inline(always)]
|
||||
pub fn unix_nanos(seconds: u64) -> u64 {
|
||||
seconds.saturating_mul(NANOS_PER_SECOND)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn trace_id(prefix: &[u8; 8], span_id: u64) -> [u8; 16] {
|
||||
let mut id = [0u8; 16];
|
||||
let (head, tail) = id.split_at_mut(8);
|
||||
head.copy_from_slice(prefix);
|
||||
tail.copy_from_slice(&span_id.to_be_bytes());
|
||||
id
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn span_id_value(value: &Value) -> u64 {
|
||||
match value {
|
||||
Value::UInt(id) => *id,
|
||||
Value::Int(id) => *id as u64,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
188
crates/telemetry/src/otlp/request.rs
Normal file
188
crates/telemetry/src/otlp/request.rs
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::resource::Resource;
|
||||
use crate::proto::{SliceCursor, varint_len, writer::ProtoWriter};
|
||||
use bytes::{Buf, Bytes, BytesMut};
|
||||
|
||||
pub const GRPC_PREFIX_LEN: usize = 5;
|
||||
const MAX_LEN_VARINT: usize = 5;
|
||||
const TAG_RESOURCE_ITEMS: u8 = 0x0a;
|
||||
const TAG_SCOPE_ITEMS: u8 = 0x12;
|
||||
const MIN_REQUEST_CAPACITY: usize = 4096;
|
||||
const HEADROOM_SHIFT: u32 = 6;
|
||||
const MIN_COMPACT_SLACK: usize = 64 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Framing {
|
||||
Http,
|
||||
Grpc,
|
||||
}
|
||||
|
||||
pub struct RequestBuilder {
|
||||
w: ProtoWriter,
|
||||
gap: usize,
|
||||
records: usize,
|
||||
last_start: usize,
|
||||
records_end: usize,
|
||||
framing: Framing,
|
||||
capacity_hint: usize,
|
||||
}
|
||||
|
||||
pub struct SealedRequest {
|
||||
pub body: Bytes,
|
||||
pub records: usize,
|
||||
pub capacity: usize,
|
||||
}
|
||||
|
||||
impl RequestBuilder {
|
||||
pub fn new(resource: &Resource, framing: Framing) -> Self {
|
||||
let gap = GRPC_PREFIX_LEN
|
||||
+ 1
|
||||
+ MAX_LEN_VARINT
|
||||
+ resource.resource.len()
|
||||
+ 1
|
||||
+ MAX_LEN_VARINT
|
||||
+ resource.scope.len();
|
||||
let mut builder = Self {
|
||||
w: ProtoWriter::with_capacity(0),
|
||||
gap,
|
||||
records: 0,
|
||||
last_start: gap,
|
||||
records_end: gap,
|
||||
framing,
|
||||
capacity_hint: MIN_REQUEST_CAPACITY,
|
||||
};
|
||||
builder.reset();
|
||||
builder
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
let capacity = self.capacity_hint + (self.capacity_hint >> HEADROOM_SHIFT);
|
||||
self.w = ProtoWriter::with_capacity(capacity.max(self.gap + MIN_REQUEST_CAPACITY));
|
||||
self.w.inner_mut().resize(self.gap, 0);
|
||||
self.records = 0;
|
||||
self.last_start = self.gap;
|
||||
self.records_end = self.gap;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn writer(&mut self) -> &mut ProtoWriter {
|
||||
&mut self.w
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn commit(&mut self) {
|
||||
self.records += 1;
|
||||
self.last_start = self.records_end;
|
||||
self.records_end = self.w.len();
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn records(&self) -> usize {
|
||||
self.records
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn body_len_bound(&self) -> usize {
|
||||
self.w.len()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.w.capacity()
|
||||
}
|
||||
|
||||
pub fn discard(&mut self) {
|
||||
self.w.inner_mut().truncate(self.gap);
|
||||
self.records = 0;
|
||||
self.last_start = self.gap;
|
||||
self.records_end = self.gap;
|
||||
}
|
||||
|
||||
pub fn seal(&mut self, resource: &Resource) -> Option<SealedRequest> {
|
||||
if self.records == 0 {
|
||||
return None;
|
||||
}
|
||||
let records = self.records;
|
||||
let buf = self.take_buffer();
|
||||
self.capacity_hint = buf.len();
|
||||
self.reset();
|
||||
Some(self.finish(buf, resource, records))
|
||||
}
|
||||
|
||||
pub fn seal_before_last(&mut self, resource: &Resource) -> Option<SealedRequest> {
|
||||
if self.records < 2 {
|
||||
return None;
|
||||
}
|
||||
let records = self.records - 1;
|
||||
let last_start = self.last_start;
|
||||
let mut buf = self.take_buffer();
|
||||
self.capacity_hint = last_start;
|
||||
self.reset();
|
||||
if let Some(last) = buf.get(last_start..) {
|
||||
self.w.raw(last);
|
||||
self.commit();
|
||||
}
|
||||
buf.truncate(last_start);
|
||||
Some(self.finish(buf, resource, records))
|
||||
}
|
||||
|
||||
fn take_buffer(&mut self) -> BytesMut {
|
||||
std::mem::replace(&mut self.w, ProtoWriter::with_capacity(0)).into_inner()
|
||||
}
|
||||
|
||||
fn finish(&self, mut buf: BytesMut, resource: &Resource, records: usize) -> SealedRequest {
|
||||
let records_len = buf.len() - self.gap;
|
||||
let scope_items_len = resource.scope.len() + records_len;
|
||||
let resource_items_len =
|
||||
resource.resource.len() + 1 + varint_len(scope_items_len as u64) + scope_items_len;
|
||||
let header_len = 1
|
||||
+ varint_len(resource_items_len as u64)
|
||||
+ resource.resource.len()
|
||||
+ 1
|
||||
+ varint_len(scope_items_len as u64)
|
||||
+ resource.scope.len();
|
||||
let header_start = self.gap - header_len;
|
||||
let message_len = (buf.len() - header_start) as u32;
|
||||
|
||||
let start = match self.framing {
|
||||
Framing::Http => header_start,
|
||||
Framing::Grpc => header_start - GRPC_PREFIX_LEN,
|
||||
};
|
||||
if let Some(header) = buf.get_mut(start..self.gap) {
|
||||
let mut cursor = SliceCursor::new(header);
|
||||
if self.framing == Framing::Grpc {
|
||||
cursor.put(&[0]);
|
||||
cursor.put(&message_len.to_be_bytes());
|
||||
}
|
||||
cursor.put(&[TAG_RESOURCE_ITEMS]);
|
||||
cursor.put_varint(resource_items_len as u64);
|
||||
cursor.put(&resource.resource);
|
||||
cursor.put(&[TAG_SCOPE_ITEMS]);
|
||||
cursor.put_varint(scope_items_len as u64);
|
||||
cursor.put(&resource.scope);
|
||||
}
|
||||
|
||||
let slack = buf.capacity() - buf.len();
|
||||
if slack > buf.len().max(MIN_COMPACT_SLACK) {
|
||||
let body = Bytes::copy_from_slice(buf.get(start..).unwrap_or_default());
|
||||
return SealedRequest {
|
||||
capacity: body.len(),
|
||||
body,
|
||||
records,
|
||||
};
|
||||
}
|
||||
let capacity = buf.capacity();
|
||||
let mut body = buf.freeze();
|
||||
body.advance(start);
|
||||
SealedRequest {
|
||||
body,
|
||||
records,
|
||||
capacity,
|
||||
}
|
||||
}
|
||||
}
|
||||
138
crates/telemetry/src/otlp/resource.rs
Normal file
138
crates/telemetry/src/otlp/resource.rs
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::value::ValueEncoder;
|
||||
use crate::proto::writer::{LenHint, ProtoWriter};
|
||||
|
||||
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
const SDK_NAME: &str = "stalwart";
|
||||
const SDK_LANGUAGE: &str = "rust";
|
||||
const SCOPE_NAME: &str = "stalwart";
|
||||
|
||||
const ENVELOPE_RESOURCE: u32 = 1;
|
||||
const RESOURCE_ATTRIBUTES: u32 = 1;
|
||||
const ENVELOPE_SCOPE: u32 = 1;
|
||||
const SCOPE_NAME_FIELD: u32 = 1;
|
||||
const SCOPE_VERSION_FIELD: u32 = 2;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ProcessIdentity {
|
||||
nonce: [u8; 16],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Resource {
|
||||
pub(crate) resource: Box<[u8]>,
|
||||
pub(crate) scope: Box<[u8]>,
|
||||
pub(crate) trace_prefix: [u8; 8],
|
||||
}
|
||||
|
||||
impl ProcessIdentity {
|
||||
pub fn new(nonce: [u8; 16]) -> Self {
|
||||
Self { nonce }
|
||||
}
|
||||
|
||||
pub fn trace_prefix(&self) -> [u8; 8] {
|
||||
let mut prefix = [0u8; 8];
|
||||
prefix.copy_from_slice(&self.nonce[..8]);
|
||||
if prefix == [0u8; 8] {
|
||||
prefix[0] = 1;
|
||||
}
|
||||
prefix
|
||||
}
|
||||
|
||||
pub fn write_instance_id(&self, out: &mut String) {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut uuid = self.nonce;
|
||||
uuid[6] = (uuid[6] & 0x0f) | 0x40;
|
||||
uuid[8] = (uuid[8] & 0x3f) | 0x80;
|
||||
for (pos, byte) in uuid.iter().enumerate() {
|
||||
if matches!(pos, 4 | 6 | 8 | 10) {
|
||||
out.push('-');
|
||||
}
|
||||
out.push(HEX[(byte >> 4) as usize] as char);
|
||||
out.push(HEX[(byte & 0x0f) as usize] as char);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Resource {
|
||||
pub fn new<'x>(
|
||||
identity: &ProcessIdentity,
|
||||
service_name: &str,
|
||||
service_namespace: Option<&str>,
|
||||
attributes: impl IntoIterator<Item = (&'x str, &'x str)>,
|
||||
) -> Self {
|
||||
let mut values = ValueEncoder::default();
|
||||
let mut instance_id = String::with_capacity(36);
|
||||
identity.write_instance_id(&mut instance_id);
|
||||
|
||||
let mut w = ProtoWriter::with_capacity(256);
|
||||
let resource = w.begin(ENVELOPE_RESOURCE, LenHint::Medium);
|
||||
values.string_key_value(&mut w, RESOURCE_ATTRIBUTES, "service.name", service_name);
|
||||
if let Some(namespace) = service_namespace.filter(|namespace| !namespace.is_empty()) {
|
||||
values.string_key_value(&mut w, RESOURCE_ATTRIBUTES, "service.namespace", namespace);
|
||||
}
|
||||
values.string_key_value(
|
||||
&mut w,
|
||||
RESOURCE_ATTRIBUTES,
|
||||
"service.version",
|
||||
SERVER_VERSION,
|
||||
);
|
||||
values.string_key_value(
|
||||
&mut w,
|
||||
RESOURCE_ATTRIBUTES,
|
||||
"service.instance.id",
|
||||
&instance_id,
|
||||
);
|
||||
values.string_key_value(&mut w, RESOURCE_ATTRIBUTES, "telemetry.sdk.name", SDK_NAME);
|
||||
values.string_key_value(
|
||||
&mut w,
|
||||
RESOURCE_ATTRIBUTES,
|
||||
"telemetry.sdk.language",
|
||||
SDK_LANGUAGE,
|
||||
);
|
||||
values.string_key_value(
|
||||
&mut w,
|
||||
RESOURCE_ATTRIBUTES,
|
||||
"telemetry.sdk.version",
|
||||
SERVER_VERSION,
|
||||
);
|
||||
for (key, value) in attributes {
|
||||
if !key.is_empty() && !is_reserved_key(key) {
|
||||
values.string_key_value(&mut w, RESOURCE_ATTRIBUTES, key, value);
|
||||
}
|
||||
}
|
||||
w.end(resource);
|
||||
let resource = Box::from(w.as_slice());
|
||||
|
||||
let mut w = ProtoWriter::with_capacity(32);
|
||||
let scope = w.begin(ENVELOPE_SCOPE, LenHint::Small);
|
||||
w.bytes(SCOPE_NAME_FIELD, SCOPE_NAME.as_bytes());
|
||||
w.bytes(SCOPE_VERSION_FIELD, SERVER_VERSION.as_bytes());
|
||||
w.end(scope);
|
||||
let scope = Box::from(w.as_slice());
|
||||
|
||||
Self {
|
||||
resource,
|
||||
scope,
|
||||
trace_prefix: identity.trace_prefix(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_reserved_key(key: &str) -> bool {
|
||||
hashify::set!(
|
||||
key.as_bytes(),
|
||||
"service.name",
|
||||
"service.namespace",
|
||||
"service.version",
|
||||
"service.instance.id",
|
||||
"telemetry.sdk.name",
|
||||
"telemetry.sdk.language",
|
||||
"telemetry.sdk.version",
|
||||
)
|
||||
}
|
||||
81
crates/telemetry/src/otlp/traces.rs
Normal file
81
crates/telemetry/src/otlp/traces.rs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{request::RequestBuilder, span_id_value, trace_id, unix_nanos, value::ValueEncoder};
|
||||
use crate::proto::writer::{LenHint, ProtoWriter};
|
||||
use trc::{Event, EventDetails, Key};
|
||||
|
||||
const SCOPE_SPANS: u32 = 2;
|
||||
|
||||
const SPAN_TRACE_ID: u32 = 1;
|
||||
const SPAN_SPAN_ID: u32 = 2;
|
||||
const SPAN_NAME: u32 = 5;
|
||||
const SPAN_KIND: u32 = 6;
|
||||
const SPAN_START_TIME: u32 = 7;
|
||||
const SPAN_END_TIME: u32 = 8;
|
||||
const SPAN_ATTRIBUTES: u32 = 9;
|
||||
const SPAN_EVENTS: u32 = 11;
|
||||
const SPAN_FLAGS: u32 = 16;
|
||||
|
||||
const EVENT_TIME: u32 = 1;
|
||||
const EVENT_NAME: u32 = 2;
|
||||
const EVENT_ATTRIBUTES: u32 = 3;
|
||||
|
||||
const SPAN_KIND_SERVER: u64 = 2;
|
||||
const SPAN_FLAGS_SAMPLED_NOT_REMOTE: u32 = 0x101;
|
||||
|
||||
pub fn encode_span<'x>(
|
||||
request: &mut RequestBuilder,
|
||||
values: &mut ValueEncoder,
|
||||
start: &Event<EventDetails>,
|
||||
end: &'x Event<EventDetails>,
|
||||
events: impl Iterator<Item = &'x Event<EventDetails>>,
|
||||
trace_prefix: &[u8; 8],
|
||||
) -> bool {
|
||||
let span_id = start
|
||||
.keys
|
||||
.iter()
|
||||
.find(|(key, _)| *key == Key::SpanId)
|
||||
.map_or(0, |(_, value)| span_id_value(value));
|
||||
if span_id == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let w = request.writer();
|
||||
let span = w.begin(SCOPE_SPANS, LenHint::Medium);
|
||||
w.bytes_always(SPAN_TRACE_ID, &trace_id(trace_prefix, span_id));
|
||||
w.bytes_always(SPAN_SPAN_ID, &span_id.to_be_bytes());
|
||||
w.bytes(SPAN_NAME, start.inner.typ.as_str().as_bytes());
|
||||
w.uint64(SPAN_KIND, SPAN_KIND_SERVER);
|
||||
w.fixed64(SPAN_START_TIME, unix_nanos(start.inner.timestamp));
|
||||
w.fixed64(SPAN_END_TIME, unix_nanos(end.inner.timestamp));
|
||||
write_attributes(w, values, SPAN_ATTRIBUTES, start);
|
||||
for event in events.chain(std::iter::once(end)) {
|
||||
let span_event = w.begin(SPAN_EVENTS, LenHint::Small);
|
||||
w.fixed64(EVENT_TIME, unix_nanos(event.inner.timestamp));
|
||||
w.bytes(EVENT_NAME, event.inner.typ.as_str().as_bytes());
|
||||
write_attributes(w, values, EVENT_ATTRIBUTES, event);
|
||||
w.end(span_event);
|
||||
}
|
||||
w.fixed32(SPAN_FLAGS, SPAN_FLAGS_SAMPLED_NOT_REMOTE);
|
||||
w.end(span);
|
||||
request.commit();
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn write_attributes(
|
||||
w: &mut ProtoWriter,
|
||||
values: &mut ValueEncoder,
|
||||
field: u32,
|
||||
event: &Event<EventDetails>,
|
||||
) {
|
||||
for (key, value) in &event.keys {
|
||||
if *key != Key::SpanId {
|
||||
values.key_value(w, field, *key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
195
crates/telemetry/src/otlp/value.rs
Normal file
195
crates/telemetry/src/otlp/value.rs
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::proto::{
|
||||
len_field_len, tag_len, varint_len,
|
||||
writer::{LenHint, ProtoWriter},
|
||||
};
|
||||
use std::fmt::Write;
|
||||
use trc::{Key, Value, serializers::timestamp::write_rfc3339};
|
||||
|
||||
const KEY_VALUE_KEY: u32 = 1;
|
||||
const KEY_VALUE_VALUE: u32 = 2;
|
||||
|
||||
const ANY_STRING: u32 = 1;
|
||||
const ANY_BOOL: u32 = 2;
|
||||
const ANY_INT: u32 = 3;
|
||||
const ANY_DOUBLE: u32 = 4;
|
||||
const ANY_ARRAY: u32 = 5;
|
||||
const ANY_KVLIST: u32 = 6;
|
||||
const ANY_BYTES: u32 = 7;
|
||||
|
||||
const ARRAY_VALUES: u32 = 1;
|
||||
const KVLIST_VALUES: u32 = 1;
|
||||
|
||||
const MAX_DEPTH: u8 = 8;
|
||||
const DEPTH_PLACEHOLDER: &str = "[max depth]";
|
||||
const EVENT_NAME_KEY: &str = "eventName";
|
||||
|
||||
enum Scalar<'x> {
|
||||
Str(&'x [u8]),
|
||||
Int(i64),
|
||||
Double(f64),
|
||||
Bool(bool),
|
||||
Bytes(&'x [u8]),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ValueEncoder {
|
||||
scratch: String,
|
||||
}
|
||||
|
||||
impl Scalar<'_> {
|
||||
#[inline(always)]
|
||||
fn encoded_len(&self) -> usize {
|
||||
match self {
|
||||
Scalar::Str(value) => len_field_len(ANY_STRING, value.len()),
|
||||
Scalar::Bytes(value) => len_field_len(ANY_BYTES, value.len()),
|
||||
Scalar::Int(value) => tag_len(ANY_INT) + varint_len(*value as u64),
|
||||
Scalar::Double(_) => tag_len(ANY_DOUBLE) + 8,
|
||||
Scalar::Bool(_) => tag_len(ANY_BOOL) + 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn write(&self, w: &mut ProtoWriter) {
|
||||
match self {
|
||||
Scalar::Str(value) => w.bytes_always(ANY_STRING, value),
|
||||
Scalar::Bytes(value) => w.bytes_always(ANY_BYTES, value),
|
||||
Scalar::Int(value) => w.int64_always(ANY_INT, *value),
|
||||
Scalar::Double(value) => w.double_always(ANY_DOUBLE, *value),
|
||||
Scalar::Bool(value) => w.bool_always(ANY_BOOL, *value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn unsigned(value: u64, scratch: &mut String) -> Scalar<'_> {
|
||||
match i64::try_from(value) {
|
||||
Ok(value) => Scalar::Int(value),
|
||||
Err(_) => {
|
||||
scratch.clear();
|
||||
scratch.push_str(itoa::Buffer::new().format(value));
|
||||
Scalar::Str(scratch.as_bytes())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn scalar<'x>(value: &'x Value, scratch: &'x mut String) -> Option<Scalar<'x>> {
|
||||
let scalar = match value {
|
||||
Value::String(value) => Scalar::Str(value.as_bytes()),
|
||||
Value::UInt(value) | Value::Duration(value) => unsigned(*value, scratch),
|
||||
Value::Int(value) => Scalar::Int(*value),
|
||||
Value::Float(value) => Scalar::Double(*value),
|
||||
Value::Bool(value) => Scalar::Bool(*value),
|
||||
Value::Bytes(value) => Scalar::Bytes(value),
|
||||
Value::Timestamp(value) => {
|
||||
scratch.clear();
|
||||
write_rfc3339(scratch, *value);
|
||||
Scalar::Str(scratch.as_bytes())
|
||||
}
|
||||
Value::Ipv4(value) => {
|
||||
scratch.clear();
|
||||
let _ = write!(scratch, "{value}");
|
||||
Scalar::Str(scratch.as_bytes())
|
||||
}
|
||||
Value::Ipv6(value) => {
|
||||
scratch.clear();
|
||||
let _ = write!(scratch, "{value}");
|
||||
Scalar::Str(scratch.as_bytes())
|
||||
}
|
||||
Value::Event(_) | Value::Array(_) | Value::None => return None,
|
||||
};
|
||||
Some(scalar)
|
||||
}
|
||||
|
||||
impl ValueEncoder {
|
||||
#[inline]
|
||||
pub fn key_value(&mut self, w: &mut ProtoWriter, field: u32, key: Key, value: &Value) {
|
||||
self.key_value_str(w, field, key.as_str(), value, 0);
|
||||
}
|
||||
|
||||
fn key_value_str(
|
||||
&mut self,
|
||||
w: &mut ProtoWriter,
|
||||
field: u32,
|
||||
key: &str,
|
||||
value: &Value,
|
||||
depth: u8,
|
||||
) {
|
||||
if let Some(scalar) = scalar(value, &mut self.scratch) {
|
||||
let any_len = scalar.encoded_len();
|
||||
w.len_prefix(
|
||||
field,
|
||||
len_field_len(KEY_VALUE_KEY, key.len()) + len_field_len(KEY_VALUE_VALUE, any_len),
|
||||
);
|
||||
w.bytes_always(KEY_VALUE_KEY, key.as_bytes());
|
||||
w.len_prefix(KEY_VALUE_VALUE, any_len);
|
||||
scalar.write(w);
|
||||
} else if !matches!(value, Value::None) {
|
||||
let kv = w.begin(field, LenHint::Small);
|
||||
w.bytes_always(KEY_VALUE_KEY, key.as_bytes());
|
||||
self.complex(w, KEY_VALUE_VALUE, value, depth);
|
||||
w.end(kv);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn string_key_value(&mut self, w: &mut ProtoWriter, field: u32, key: &str, value: &str) {
|
||||
let any_len = len_field_len(ANY_STRING, value.len());
|
||||
w.len_prefix(
|
||||
field,
|
||||
len_field_len(KEY_VALUE_KEY, key.len()) + len_field_len(KEY_VALUE_VALUE, any_len),
|
||||
);
|
||||
w.bytes_always(KEY_VALUE_KEY, key.as_bytes());
|
||||
w.len_prefix(KEY_VALUE_VALUE, any_len);
|
||||
w.bytes_always(ANY_STRING, value.as_bytes());
|
||||
}
|
||||
|
||||
fn any_value(&mut self, w: &mut ProtoWriter, field: u32, value: &Value, depth: u8) {
|
||||
if let Some(scalar) = scalar(value, &mut self.scratch) {
|
||||
w.len_prefix(field, scalar.encoded_len());
|
||||
scalar.write(w);
|
||||
} else if matches!(value, Value::None) {
|
||||
w.len_prefix(field, 0);
|
||||
} else {
|
||||
self.complex(w, field, value, depth);
|
||||
}
|
||||
}
|
||||
|
||||
fn complex(&mut self, w: &mut ProtoWriter, field: u32, value: &Value, depth: u8) {
|
||||
if depth >= MAX_DEPTH {
|
||||
w.len_prefix(field, len_field_len(ANY_STRING, DEPTH_PLACEHOLDER.len()));
|
||||
w.bytes_always(ANY_STRING, DEPTH_PLACEHOLDER.as_bytes());
|
||||
return;
|
||||
}
|
||||
let any = w.begin(field, LenHint::Small);
|
||||
match value {
|
||||
Value::Array(values) => {
|
||||
let array = w.begin(ANY_ARRAY, LenHint::Small);
|
||||
for value in values {
|
||||
self.any_value(w, ARRAY_VALUES, value, depth + 1);
|
||||
}
|
||||
w.end(array);
|
||||
}
|
||||
Value::Event(event) => {
|
||||
let kvlist = w.begin(ANY_KVLIST, LenHint::Small);
|
||||
self.string_key_value(
|
||||
w,
|
||||
KVLIST_VALUES,
|
||||
EVENT_NAME_KEY,
|
||||
event.event_type().as_str(),
|
||||
);
|
||||
for (key, value) in event.keys() {
|
||||
self.key_value_str(w, KVLIST_VALUES, key.as_str(), value, depth + 1);
|
||||
}
|
||||
w.end(kvlist);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
w.end(any);
|
||||
}
|
||||
}
|
||||
33
crates/telemetry/src/prometheus/mod.rs
Normal file
33
crates/telemetry/src/prometheus/mod.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub mod negotiate;
|
||||
pub mod number;
|
||||
pub mod text;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PromFormat {
|
||||
Text004,
|
||||
Text100,
|
||||
OpenMetrics100,
|
||||
}
|
||||
|
||||
impl PromFormat {
|
||||
pub fn content_type(self) -> &'static str {
|
||||
match self {
|
||||
PromFormat::Text004 => "text/plain; version=0.0.4; charset=utf-8",
|
||||
PromFormat::Text100 => "text/plain; version=1.0.0; charset=utf-8; escaping=underscores",
|
||||
PromFormat::OpenMetrics100 => {
|
||||
"application/openmetrics-text; version=1.0.0; charset=utf-8; escaping=underscores"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_open_metrics(self) -> bool {
|
||||
self == PromFormat::OpenMetrics100
|
||||
}
|
||||
}
|
||||
121
crates/telemetry/src/prometheus/negotiate.rs
Normal file
121
crates/telemetry/src/prometheus/negotiate.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::PromFormat;
|
||||
|
||||
const MAX_MEDIA_RANGES: usize = 32;
|
||||
const MAX_PARAMETERS: usize = 8;
|
||||
const MAX_QUALITY: u16 = 1000;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum MediaKind {
|
||||
OpenMetrics,
|
||||
Text,
|
||||
Any,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Parameter {
|
||||
Version,
|
||||
Quality,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Version {
|
||||
V001,
|
||||
V004,
|
||||
V100,
|
||||
}
|
||||
|
||||
pub fn negotiate(accept: Option<&[u8]>) -> PromFormat {
|
||||
let mut best: Option<(u16, PromFormat)> = None;
|
||||
for range in accept
|
||||
.unwrap_or_default()
|
||||
.split(|byte| *byte == b',')
|
||||
.take(MAX_MEDIA_RANGES)
|
||||
{
|
||||
if let Some((quality, format)) = parse_range(range)
|
||||
&& quality > 0
|
||||
&& best.is_none_or(|(best_quality, _)| quality > best_quality)
|
||||
{
|
||||
best = Some((quality, format));
|
||||
}
|
||||
}
|
||||
best.map_or(PromFormat::Text004, |(_, format)| format)
|
||||
}
|
||||
|
||||
fn parse_range(range: &[u8]) -> Option<(u16, PromFormat)> {
|
||||
let mut parts = range.split(|byte| *byte == b';');
|
||||
let kind = *hashify::map_ignore_case!(
|
||||
parts.next()?.trim_ascii(),
|
||||
MediaKind,
|
||||
"application/openmetrics-text" => MediaKind::OpenMetrics,
|
||||
"text/plain" => MediaKind::Text,
|
||||
"text/*" => MediaKind::Any,
|
||||
"*/*" => MediaKind::Any,
|
||||
)?;
|
||||
|
||||
let mut version = None;
|
||||
let mut quality = MAX_QUALITY;
|
||||
for parameter in parts.take(MAX_PARAMETERS) {
|
||||
let mut pair = parameter.splitn(2, |byte| *byte == b'=');
|
||||
let name = pair.next().unwrap_or_default().trim_ascii();
|
||||
let value = pair.next().unwrap_or_default().trim_ascii();
|
||||
let value = value
|
||||
.strip_prefix(b"\"")
|
||||
.and_then(|value| value.strip_suffix(b"\""))
|
||||
.unwrap_or(value);
|
||||
match hashify::map_ignore_case!(
|
||||
name,
|
||||
Parameter,
|
||||
"version" => Parameter::Version,
|
||||
"q" => Parameter::Quality,
|
||||
) {
|
||||
Some(Parameter::Version) => {
|
||||
version = Some(*hashify::map!(
|
||||
value,
|
||||
Version,
|
||||
"0.0.1" => Version::V001,
|
||||
"0.0.4" => Version::V004,
|
||||
"1.0.0" => Version::V100,
|
||||
)?);
|
||||
}
|
||||
Some(Parameter::Quality) => quality = parse_quality(value)?,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
let format = match (kind, version) {
|
||||
(MediaKind::OpenMetrics, None | Some(Version::V100)) => PromFormat::OpenMetrics100,
|
||||
(MediaKind::Text, None | Some(Version::V004)) | (MediaKind::Any, _) => PromFormat::Text004,
|
||||
(MediaKind::Text, Some(Version::V100)) => PromFormat::Text100,
|
||||
_ => return None,
|
||||
};
|
||||
Some((quality, format))
|
||||
}
|
||||
|
||||
fn parse_quality(value: &[u8]) -> Option<u16> {
|
||||
let (first, rest) = value.split_first()?;
|
||||
let fraction = match rest {
|
||||
[] => &[][..],
|
||||
[b'.', fraction @ ..] if fraction.len() <= 3 => fraction,
|
||||
_ => return None,
|
||||
};
|
||||
let mut quality = match first {
|
||||
b'0' => 0u16,
|
||||
b'1' => MAX_QUALITY,
|
||||
_ => return None,
|
||||
};
|
||||
let mut scale = 100u16;
|
||||
for digit in fraction {
|
||||
if !digit.is_ascii_digit() || (quality == MAX_QUALITY && *digit != b'0') {
|
||||
return None;
|
||||
}
|
||||
quality += (digit - b'0') as u16 * scale;
|
||||
scale /= 10;
|
||||
}
|
||||
Some(quality)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue