matomo-rs 0.1.1

Async client for the Matomo Reporting API, focused on data export and migration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! `reqwest`-backed [`Client`] implementation and the ergonomic high-level API.
//!
//! Gated behind the `reqwest` feature. No TLS backend is pulled in by default;
//! pair it with `reqwest-rustls` or `reqwest-native-tls`, or supply your own
//! [`reqwest::Client`] via [`MatomoClient::with_reqwest_client`].

use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use http::{Request, Response};
use secrecy::ExposeSecret;
use serde::de::DeserializeOwned;
use serde_json::Value;
use thiserror::Error;
use url::Url;

use crate::auth::Auth;
use crate::error::{Error, Result};
use crate::request::Params;
use crate::transport::{Client, Endpoint, Query, QueryError};

mod handles;
mod preflight;

pub use handles::{
    ActionsHandle, ApiHandle, Cursor, LiveHandle, ReferrersHandle, VisitStream, VisitsSummaryHandle,
};

use preflight::PreflightState;

/// A reqwest-based Matomo API client and the ergonomic entry point.
#[derive(Clone)]
pub struct MatomoClient(Arc<Inner>);

pub(crate) struct Inner {
    http: ::reqwest::Client,
    base_url: Url,
    auth: Auth,
    skip_preflight: bool,
    preflight: PreflightState,
}

impl std::fmt::Debug for MatomoClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MatomoClient")
            .field("base_url", &self.0.base_url.as_str())
            .field("auth", &self.0.auth)
            .field("skip_preflight", &self.0.skip_preflight)
            .finish_non_exhaustive()
    }
}

/// Transport-level errors surfaced by [`MatomoClient`].
#[derive(Debug, Error)]
pub enum MatomoClientError {
    /// The underlying `reqwest` call failed (DNS, TLS, timeout, ...).
    #[error("communication with matomo: {source}")]
    Communication {
        #[from]
        source: ::reqwest::Error,
    },
    /// Constructing the `http::Response` from the reqwest response failed.
    #[error("http error: {source}")]
    Http {
        #[from]
        source: http::Error,
    },
    /// The request URI could not be resolved against the base URL.
    #[error("invalid request uri: {source}")]
    Url {
        #[from]
        source: url::ParseError,
    },
    /// The server responded with a non-success HTTP status.
    #[error("http status {status}: {body}")]
    Status {
        status: http::StatusCode,
        body: String,
    },
}

impl MatomoClient {
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    pub(crate) fn inner(&self) -> &Arc<Inner> {
        &self.0
    }

    /// Run an [`Endpoint`] and map its [`QueryError`] onto the public [`Error`].
    pub(crate) async fn query<T: Endpoint + Send + Sync>(
        &self,
        endpoint: T,
    ) -> Result<T::Response> {
        if !self.0.skip_preflight {
            let id_site = sniff_id_site(&endpoint.params());
            preflight::run(self, endpoint.method(), id_site.as_deref()).await?;
        }
        endpoint.execute(self).await.map_err(map_query_error)
    }

    /// Like [`Self::query`] but skips preflight (used by preflight itself).
    pub(crate) async fn query_unchecked<T: Endpoint + Send + Sync>(
        &self,
        endpoint: T,
    ) -> Result<T::Response> {
        endpoint.execute(self).await.map_err(map_query_error)
    }

    // Module accessors.
    #[must_use]
    pub fn api(&self) -> ApiHandle<'_> {
        ApiHandle::new(self)
    }
    #[must_use]
    pub fn visits_summary(&self) -> VisitsSummaryHandle<'_> {
        VisitsSummaryHandle::new(self)
    }
    #[must_use]
    pub fn live(&self) -> LiveHandle<'_> {
        LiveHandle::new(self)
    }
    #[must_use]
    pub fn actions(&self) -> ActionsHandle<'_> {
        ActionsHandle::new(self)
    }
    #[must_use]
    pub fn referrers(&self) -> ReferrersHandle<'_> {
        ReferrersHandle::new(self)
    }

    // Escape hatches.

    /// Parse once into a `Value`, branching on Matomo's error envelope.
    ///
    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or a non-JSON
    /// body.
    pub async fn call(&self, method: &'static str, params: &Params) -> Result<Value> {
        self.query(RawEndpoint {
            method,
            params: params.clone(),
        })
        .await
    }

    /// Typed call. Single parse: bytes → `Value` once, error-check, then decode.
    ///
    /// # Errors
    ///
    /// Fails like [`Self::call`], plus [`Error::Decode`] when the JSON does
    /// not match `T`.
    pub async fn call_typed<T: DeserializeOwned>(
        &self,
        method: &'static str,
        params: &Params,
    ) -> Result<T> {
        let value = self.call(method, params).await?;
        serde_json::from_value(value).map_err(|source| Error::Decode { source, method })
    }

    /// Lowest-level call: the raw response bytes, no parsing.
    ///
    /// # Errors
    ///
    /// Fails on transport errors, non-success HTTP statuses, or a failed
    /// preflight check.
    pub async fn call_raw(&self, method: &'static str, params: &Params) -> Result<Bytes> {
        if !self.0.skip_preflight {
            let id_site = sniff_id_site(params);
            preflight::run(self, method, id_site.as_deref()).await?;
        }
        self.call_raw_unchecked(method, params).await
    }

    pub(crate) async fn call_raw_unchecked(
        &self,
        method: &'static str,
        params: &Params,
    ) -> Result<Bytes> {
        let req = crate::transport::build_dispatch_request::<MatomoClientError>(method, params)
            .map_err(map_query_error)?;
        let resp = self.execute(req).await.map_err(map_transport_only)?;
        Ok(resp.into_body())
    }
}

fn sniff_id_site(params: &Params) -> Option<String> {
    params
        .fields()
        .iter()
        .find(|(k, _)| k == "idSite")
        .map(|(_, v)| v.clone())
}

/// Endpoint used by the `call`/`call_typed` escape hatches: any method, any
/// params, decode to a raw `Value`.
struct RawEndpoint {
    method: &'static str,
    params: Params,
}

impl Endpoint for RawEndpoint {
    type Response = Value;
    fn method(&self) -> &'static str {
        self.method
    }
    fn params(&self) -> Params {
        self.params.clone()
    }
}

fn map_query_error(e: QueryError<MatomoClientError>) -> Error {
    match e {
        QueryError::Transport { source } => map_transport_only(source),
        QueryError::Api {
            message,
            method,
            kind,
        } => Error::Api {
            message,
            method,
            kind,
        },
        QueryError::NonJsonBody { method, body } => Error::NonJsonBody { method, body },
        QueryError::Decode { source, method } => Error::Decode { source, method },
        QueryError::Build { source } => Error::Transport { source },
        QueryError::Encode { source } => {
            Error::Config(format!("failed to encode form body: {source}"))
        }
    }
}

fn map_transport_only(e: MatomoClientError) -> Error {
    match e {
        MatomoClientError::Communication { source } => Error::Http(source),
        MatomoClientError::Http { source } => Error::Transport { source },
        MatomoClientError::Url { source } => {
            Error::Config(format!("invalid request uri: {source}"))
        }
        MatomoClientError::Status { status, body } => Error::Status { status, body },
    }
}

impl Client for MatomoClient {
    type Error = MatomoClientError;

    async fn execute(
        &self,
        req: Request<Bytes>,
    ) -> std::result::Result<Response<Bytes>, Self::Error> {
        // base_url is normalized with a trailing slash, so joining the relative
        // request path lands on the sub-path instead of replacing it.
        let url = self
            .0
            .base_url
            .join(req.uri().path().trim_start_matches('/'))?;
        let mut builder = self
            .0
            .http
            .request(req.method().clone(), url)
            .headers(req.headers().clone());

        let mut body = req.into_body();
        match &self.0.auth {
            Auth::Token(t) => {
                // Infallible: a single &str pair cannot fail to url-encode.
                let extra = serde_urlencoded::to_string([("token_auth", t.expose_secret())])
                    .expect("encoding a single str pair cannot fail");
                let mut buf = Vec::with_capacity(body.len() + 1 + extra.len());
                buf.extend_from_slice(&body);
                if !body.is_empty() {
                    buf.push(b'&');
                }
                buf.extend_from_slice(extra.as_bytes());
                body = Bytes::from(buf);
            }
            Auth::Bearer(t) => {
                builder = builder.bearer_auth(t.expose_secret());
            }
        }

        let reqwest_resp = builder.body(body).send().await?;

        let status = reqwest_resp.status();
        let version = reqwest_resp.version();
        let headers = reqwest_resp.headers().clone();
        let bytes = reqwest_resp.bytes().await?;
        if !status.is_success() {
            return Err(MatomoClientError::Status {
                status,
                body: crate::transport::body_snippet(&bytes),
            });
        }

        let mut resp = Response::builder().status(status).version(version);
        if let Some(h) = resp.headers_mut() {
            *h = headers;
        }
        Ok(resp.body(bytes)?)
    }
}

#[derive(Default)]
#[must_use]
pub struct ClientBuilder {
    base_url: Option<String>,
    auth: Option<Auth>,
    timeout: Option<Duration>,
    skip_preflight: bool,
    http: Option<::reqwest::Client>,
}

impl ClientBuilder {
    /// The Matomo instance base URL, e.g. `https://analytics.example.com/`.
    ///
    /// A plain `http://` base transmits `token_auth` in cleartext; use
    /// `https://` unless you fully trust the network path.
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    pub fn auth(mut self, auth: Auth) -> Self {
        self.auth = Some(auth);
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Supply a pre-configured `reqwest::Client` (custom TLS, proxy, timeouts).
    ///
    /// A redirect-following client can replay the token-bearing POST body to
    /// another origin on a 307/308 redirect; prefer
    /// `redirect::Policy::none()`. The default client does not follow
    /// redirects.
    pub fn reqwest_client(mut self, http: ::reqwest::Client) -> Self {
        self.http = Some(http);
        self
    }

    /// Opt out of the lazy preflight checks.
    pub fn skip_preflight(mut self) -> Self {
        self.skip_preflight = true;
        self
    }

    /// # Errors
    ///
    /// Returns [`Error::Config`] when `base_url` or `auth` is missing or the
    /// base URL is invalid, and [`Error::Http`] when the default `reqwest`
    /// client cannot be constructed.
    pub fn build(self) -> Result<MatomoClient> {
        let raw = self
            .base_url
            .ok_or_else(|| Error::Config("base_url is required".to_string()))?;
        let auth = self
            .auth
            .ok_or_else(|| Error::Config("auth is required".to_string()))?;

        let mut base_url =
            Url::parse(&raw).map_err(|e| Error::Config(format!("invalid base_url: {e}")))?;
        if base_url.cannot_be_a_base() {
            return Err(Error::Config(
                "base_url must be a valid base URL".to_string(),
            ));
        }
        if base_url.query().is_some() || base_url.fragment().is_some() {
            return Err(Error::Config(
                "base_url must not carry a query or fragment".to_string(),
            ));
        }
        if !base_url.path().ends_with('/') {
            let path = format!("{}/", base_url.path());
            base_url.set_path(&path);
        }

        let http = match self.http {
            Some(http) => http,
            None => {
                // No redirects: a 307/308 would replay the token-bearing body
                // to another origin.
                ::reqwest::Client::builder()
                    .redirect(::reqwest::redirect::Policy::none())
                    .timeout(self.timeout.unwrap_or(Duration::from_secs(60)))
                    .build()
                    .map_err(Error::Http)?
            }
        };

        Ok(MatomoClient(Arc::new(Inner {
            http,
            base_url,
            auth,
            skip_preflight: self.skip_preflight,
            preflight: PreflightState::default(),
        })))
    }
}

impl MatomoClient {
    /// Convenience constructor with the default reqwest client.
    ///
    /// # Errors
    ///
    /// See [`ClientBuilder::build`].
    pub fn new(base_url: impl Into<String>, auth: Auth) -> Result<Self> {
        Self::builder().base_url(base_url).auth(auth).build()
    }

    /// Constructor that takes a pre-configured `reqwest::Client`.
    ///
    /// See [`ClientBuilder::reqwest_client`] for the redirect-policy caveat.
    ///
    /// # Errors
    ///
    /// See [`ClientBuilder::build`].
    pub fn with_reqwest_client(
        base_url: impl Into<String>,
        auth: Auth,
        http: ::reqwest::Client,
    ) -> Result<Self> {
        Self::builder()
            .base_url(base_url)
            .auth(auth)
            .reqwest_client(http)
            .build()
    }
}