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
use std::pin::Pin;
use std::task::{Context, Poll};

use futures_core::Stream;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::endpoints::{
    ActionsGetDownloads, ActionsGetOutlinks, ActionsGetPageTitles, ActionsGetPageUrls,
    LiveGetLastVisitsDetails, ReferrersGetAll, ReferrersGetReferrerType, VisitsSummaryGet,
};
use crate::error::{Error, Result};
use crate::models::{
    ActionPage, Download, Outlink, ReferrerAll, ReferrerType, Visit, VisitsSummary,
};
use crate::params::{IdSite, Limit, Period, Segment};
use crate::request::Params;
use crate::reqwest::MatomoClient;

/// Handle for the `VisitsSummary` module.
#[derive(Clone, Copy)]
pub struct VisitsSummaryHandle<'a> {
    client: &'a MatomoClient,
}

impl<'a> VisitsSummaryHandle<'a> {
    pub(crate) fn new(client: &'a MatomoClient) -> Self {
        VisitsSummaryHandle { client }
    }

    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or undecodable
    /// responses.
    pub async fn get(
        &self,
        id_site: impl Into<IdSite>,
        period: Period,
        segment: Option<Segment>,
    ) -> Result<VisitsSummary> {
        self.client
            .query(VisitsSummaryGet {
                id_site: id_site.into(),
                period,
                segment,
            })
            .await
    }
}

/// Handle for the `Actions` module.
#[derive(Clone, Copy)]
pub struct ActionsHandle<'a> {
    client: &'a MatomoClient,
}

impl<'a> ActionsHandle<'a> {
    pub(crate) fn new(client: &'a MatomoClient) -> Self {
        ActionsHandle { client }
    }

    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or undecodable
    /// responses.
    pub async fn get_page_urls(
        &self,
        id_site: impl Into<IdSite>,
        period: Period,
        segment: Option<Segment>,
    ) -> Result<Vec<ActionPage>> {
        self.client
            .query(ActionsGetPageUrls {
                id_site: id_site.into(),
                period,
                segment,
            })
            .await
    }

    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or undecodable
    /// responses.
    pub async fn get_page_titles(
        &self,
        id_site: impl Into<IdSite>,
        period: Period,
        segment: Option<Segment>,
    ) -> Result<Vec<ActionPage>> {
        self.client
            .query(ActionsGetPageTitles {
                id_site: id_site.into(),
                period,
                segment,
            })
            .await
    }

    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or undecodable
    /// responses.
    pub async fn get_downloads(
        &self,
        id_site: impl Into<IdSite>,
        period: Period,
        segment: Option<Segment>,
    ) -> Result<Vec<Download>> {
        self.client
            .query(ActionsGetDownloads {
                id_site: id_site.into(),
                period,
                segment,
            })
            .await
    }

    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or undecodable
    /// responses.
    pub async fn get_outlinks(
        &self,
        id_site: impl Into<IdSite>,
        period: Period,
        segment: Option<Segment>,
    ) -> Result<Vec<Outlink>> {
        self.client
            .query(ActionsGetOutlinks {
                id_site: id_site.into(),
                period,
                segment,
            })
            .await
    }
}

/// Handle for the `Referrers` module.
#[derive(Clone, Copy)]
pub struct ReferrersHandle<'a> {
    client: &'a MatomoClient,
}

impl<'a> ReferrersHandle<'a> {
    pub(crate) fn new(client: &'a MatomoClient) -> Self {
        ReferrersHandle { client }
    }

    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or undecodable
    /// responses.
    pub async fn get_referrer_type(
        &self,
        id_site: impl Into<IdSite>,
        period: Period,
        segment: Option<Segment>,
    ) -> Result<Vec<ReferrerType>> {
        self.client
            .query(ReferrersGetReferrerType {
                id_site: id_site.into(),
                period,
                segment,
            })
            .await
    }

    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or undecodable
    /// responses.
    pub async fn get_all(
        &self,
        id_site: impl Into<IdSite>,
        period: Period,
        segment: Option<Segment>,
    ) -> Result<Vec<ReferrerAll>> {
        self.client
            .query(ReferrersGetAll {
                id_site: id_site.into(),
                period,
                segment,
            })
            .await
    }
}

/// Handle for the `API` module.
#[derive(Clone, Copy)]
pub struct ApiHandle<'a> {
    client: &'a MatomoClient,
}

impl<'a> ApiHandle<'a> {
    pub(crate) fn new(client: &'a MatomoClient) -> Self {
        ApiHandle { client }
    }

    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or a response
    /// without a string `value` field.
    pub async fn version(&self) -> Result<String> {
        #[derive(Deserialize)]
        struct VersionValue {
            value: String,
        }
        let value = self
            .client
            .call("API.getMatomoVersion", &Params::new())
            .await?;
        let v: VersionValue = serde_json::from_value(value).map_err(|source| Error::Decode {
            source,
            method: "API.getMatomoVersion",
        })?;
        Ok(v.value)
    }

    /// Raw report metadata as a JSON value.
    ///
    /// # Errors
    ///
    /// Fails on transport errors or Matomo API error envelopes.
    pub async fn report_metadata(&self) -> Result<Value> {
        self.client
            .call("API.getReportMetadata", &Params::new())
            .await
    }

    /// Compose multiple calls into a single `API.getBulkRequest`.
    ///
    /// # Errors
    ///
    /// Fails on transport errors or Matomo API error envelopes.
    pub async fn bulk_request(&self, calls: &[(&str, Params)]) -> Result<Value> {
        let mut params = Params::new();
        for (i, (method, p)) in calls.iter().enumerate() {
            params = params.set(format!("urls[{i}]"), p.to_bulk_query(method));
        }
        self.client.call("API.getBulkRequest", &params).await
    }
}

/// Handle for the `Live` module.
#[derive(Clone, Copy)]
pub struct LiveHandle<'a> {
    client: &'a MatomoClient,
}

/// Serializable paging context for resuming a `Live.getLastVisitsDetails`
/// export across restarts.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Cursor {
    pub id_site: u32,
    pub period: String,
    pub date: String,
    pub segment: Option<String>,
    pub page_size: u32,
    pub offset: u32,
}

impl Cursor {
    /// Build the initial cursor for a paged export. Rejects `Limit::All`, which
    /// has no termination guarantee in the paging path.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] for `Limit::All`.
    pub fn new(
        id_site: u32,
        period: Period,
        page_size: Limit,
        segment: Option<Segment>,
    ) -> Result<Self> {
        if page_size.is_all() {
            return Err(Error::Config(
                "Limit::All cannot be used for paging; it breaks termination".to_string(),
            ));
        }
        let page_size = match page_size {
            Limit::Count(n) => n.get(),
            Limit::All => unreachable!(),
        };
        let (period, date) = period.to_params();
        Ok(Cursor {
            id_site,
            period: period.to_string(),
            date,
            segment: segment.map(|s| s.as_str().to_owned()),
            page_size,
            offset: 0,
        })
    }

    fn to_params(&self) -> Params {
        let mut params = Params::new()
            .id_site(IdSite::Single(self.id_site))
            .set("period", self.period.clone())
            .set("date", self.date.clone())
            .set("filter_limit", self.page_size.to_string())
            .offset(self.offset);
        if let Some(s) = &self.segment {
            params = params.set("segment", s.clone());
        }
        params
    }
}

impl<'a> LiveHandle<'a> {
    pub(crate) fn new(client: &'a MatomoClient) -> Self {
        LiveHandle { client }
    }

    /// Fetch one page. An empty page is the authoritative terminator (returns a
    /// `None` next cursor); a short non-empty page is NOT.
    ///
    /// Offset-based paging drifts when new visits arrive mid-export
    /// (duplicates or skips); use a closed historical date range for
    /// consistent exports.
    ///
    /// # Errors
    ///
    /// Fails on transport errors, Matomo API error envelopes, or undecodable
    /// responses; [`Error::Config`] if the paging offset would overflow.
    pub async fn next_page(&self, cursor: &Cursor) -> Result<(Vec<Visit>, Option<Cursor>)> {
        let visits: Vec<Visit> = self
            .client
            .query(LiveGetLastVisitsDetails {
                params: cursor.to_params(),
            })
            .await?;

        if visits.is_empty() {
            return Ok((visits, None));
        }
        let offset = cursor
            .offset
            .checked_add(cursor.page_size)
            .ok_or_else(|| Error::Config("paging offset overflowed u32".to_string()))?;
        let next = Cursor {
            offset,
            ..cursor.clone()
        };
        Ok((visits, Some(next)))
    }

    /// Build a `VisitStream` over a paged export. Owns an `Arc`-cloned client so
    /// the stream is `'static + Send` and can be spawned.
    ///
    /// The stream ends on the first error and does not expose the cursor;
    /// resumable exports should use [`Self::next_page`] with a persisted
    /// [`Cursor`]. Offset-based paging drifts when new visits arrive
    /// mid-export; prefer a closed historical date range.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] for `Limit::All`.
    pub fn stream(
        &self,
        id_site: u32,
        period: Period,
        page_size: Limit,
        segment: Option<Segment>,
    ) -> Result<VisitStream> {
        let cursor = Cursor::new(id_site, period, page_size, segment)?;
        Ok(VisitStream::new(self.client.clone(), cursor))
    }
}

struct StreamState {
    client: MatomoClient,
    cursor: Option<Cursor>,
    buffer: std::collections::VecDeque<Visit>,
}

/// A `Stream` of visits backed by the resumable pager. On the first error the
/// stream ends.
pub struct VisitStream(Pin<Box<dyn Stream<Item = Result<Visit>> + Send>>);

impl VisitStream {
    fn new(client: MatomoClient, cursor: Cursor) -> Self {
        let state = StreamState {
            client,
            cursor: Some(cursor),
            buffer: std::collections::VecDeque::new(),
        };
        let stream = futures_util::stream::try_unfold(state, |mut state| async move {
            loop {
                if let Some(visit) = state.buffer.pop_front() {
                    return Ok(Some((visit, state)));
                }
                let Some(cursor) = state.cursor.take() else {
                    return Ok(None);
                };
                let (visits, next) = state.client.live().next_page(&cursor).await?;
                state.cursor = next;
                if visits.is_empty() {
                    return Ok(None);
                }
                state.buffer.extend(visits);
            }
        });
        VisitStream(Box::pin(stream))
    }
}

impl Stream for VisitStream {
    type Item = Result<Visit>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.0.as_mut().poll_next(cx)
    }
}