pushers 1.5.0

A Rust client for interacting with the Pusher HTTP API
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
use crate::{Channel, Pusher, PusherError, Result};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use serde::{Deserialize, Serialize};
use sonic_rs::{Value, json};
use std::collections::HashMap;
use std::fmt;

#[cfg(all(feature = "encryption", feature = "sodiumoxide"))]
use std::sync::Once;

#[cfg(all(feature = "encryption", feature = "sodiumoxide"))]
static SODIUM_INIT: Once = Once::new();

/// Initialize sodiumoxide once
#[cfg(all(feature = "encryption", feature = "sodiumoxide"))]
fn init_sodium() -> Result<()> {
    SODIUM_INIT.call_once(|| {
        sodiumoxide::init().expect("Failed to initialize sodiumoxide");
    });
    Ok(())
}

/// Event data that can be either a string or JSON
#[derive(Debug, Clone, PartialEq)]
pub enum EventData {
    String(String),
    Json(Value),
}

impl EventData {
    /// Creates event data from a string
    pub fn from_string(s: impl Into<String>) -> Self {
        EventData::String(s.into())
    }

    /// Creates event data from a JSON value
    pub fn from_json(value: Value) -> Self {
        EventData::Json(value)
    }

    /// Converts the event data to a string for transmission
    pub fn to_string(&self) -> String {
        match self {
            EventData::String(s) => s.clone(),
            EventData::Json(v) => sonic_rs::to_string(v).unwrap_or_default(),
        }
    }

    /// Gets the event data as a JSON value
    pub fn as_json(&self) -> Result<Value> {
        match self {
            EventData::String(s) => sonic_rs::from_str(s).map_err(|e| PusherError::Json(e)),
            EventData::Json(v) => Ok(v.clone()),
        }
    }
}

impl fmt::Display for EventData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}

impl From<String> for EventData {
    fn from(s: String) -> Self {
        EventData::String(s)
    }
}

impl From<&str> for EventData {
    fn from(s: &str) -> Self {
        EventData::String(s.to_string())
    }
}

impl From<Value> for EventData {
    fn from(v: Value) -> Self {
        EventData::Json(v)
    }
}

/// Event data for triggering
#[derive(Debug, Serialize)]
pub struct Event {
    pub name: String,
    pub data: String,
    pub channels: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub socket_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<HashMap<String, String>>,
}

/// Batch event data
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchEvent {
    pub name: String,
    pub channel: String,
    pub data: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub socket_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<HashMap<String, String>>,
}

impl BatchEvent {
    /// Creates a new batch event with EventData
    pub fn new(
        name: impl Into<String>,
        channel: impl Into<String>,
        data: impl Into<EventData>,
    ) -> Self {
        Self {
            name: name.into(),
            channel: channel.into(),
            data: data.into().to_string(),
            socket_id: None,
            info: None,
            tags: None,
        }
    }

    /// Sets the socket ID to exclude
    pub fn with_socket_id(mut self, socket_id: impl Into<String>) -> Self {
        self.socket_id = Some(socket_id.into());
        self
    }

    /// Sets the info parameter
    pub fn with_info(mut self, info: impl Into<String>) -> Self {
        self.info = Some(info.into());
        self
    }

    /// Sets the tags for tag filtering
    pub fn with_tags(mut self, tags: HashMap<String, String>) -> Self {
        self.tags = Some(tags);
        self
    }
}

/// Parameters for triggering events
#[derive(Debug, Clone, Default)]
pub struct TriggerParams {
    pub socket_id: Option<String>,
    pub info: Option<String>,
    pub tags: Option<HashMap<String, String>>,
}

impl TriggerParams {
    /// Creates a new TriggerParams builder
    pub fn builder() -> TriggerParamsBuilder {
        TriggerParamsBuilder::default()
    }
}

/// Builder for TriggerParams
#[derive(Debug, Default)]
pub struct TriggerParamsBuilder {
    socket_id: Option<String>,
    info: Option<String>,
    tags: Option<HashMap<String, String>>,
}

impl TriggerParamsBuilder {
    /// Sets the socket ID to exclude
    pub fn socket_id(mut self, socket_id: impl Into<String>) -> Self {
        self.socket_id = Some(socket_id.into());
        self
    }

    /// Sets the info parameter
    pub fn info(mut self, info: impl Into<String>) -> Self {
        self.info = Some(info.into());
        self
    }

    /// Sets the tags for tag filtering
    pub fn tags(mut self, tags: HashMap<String, String>) -> Self {
        self.tags = Some(tags);
        self
    }

    /// Builds the TriggerParams
    pub fn build(self) -> TriggerParams {
        TriggerParams {
            socket_id: self.socket_id,
            info: self.info,
            tags: self.tags,
        }
    }
}

/// Encrypts data for encrypted channels
#[cfg(feature = "encryption")]
fn encrypt(pusher: &Pusher, channel: &str, data: &EventData) -> Result<String> {
    #[cfg(feature = "sodiumoxide")]
    {
        encrypt_sodiumoxide(pusher, channel, data)
    }

    #[cfg(not(feature = "sodiumoxide"))]
    {
        encrypt_pure_rust(pusher, channel, data)
    }
}

/// Encrypts data using sodiumoxide
#[cfg(all(feature = "encryption", feature = "sodiumoxide"))]
fn encrypt_sodiumoxide(pusher: &Pusher, channel: &str, data: &EventData) -> Result<String> {
    init_sodium()?;

    // Ensure master key is present
    let _master_key =
        pusher
            .config()
            .encryption_master_key()
            .ok_or_else(|| PusherError::Encryption {
                message: "Set encryptionMasterKey before triggering events on encrypted channels"
                    .to_string(),
            })?;

    // Generate a random nonce
    let nonce_bytes =
        sodiumoxide::randombytes::randombytes(sodiumoxide::crypto::secretbox::NONCEBYTES);
    let nonce =
        sodiumoxide::crypto::secretbox::Nonce::from_slice(&nonce_bytes).ok_or_else(|| {
            PusherError::Encryption {
                message: "Failed to create nonce from random bytes".to_string(),
            }
        })?;

    // Get channel shared secret
    let shared_secret_bytes = pusher.channel_shared_secret(channel)?;

    // Convert to cryptographic Key type
    let key =
        sodiumoxide::crypto::secretbox::Key::from_slice(&shared_secret_bytes).ok_or_else(|| {
            PusherError::Encryption {
                message: format!(
                    "Channel shared secret must be {} bytes long, but was {} bytes.",
                    sodiumoxide::crypto::secretbox::KEYBYTES,
                    shared_secret_bytes.len()
                ),
            }
        })?;

    // Get data as bytes
    let data_string = data.to_string();
    let data_bytes = data_string.as_bytes();

    // Encrypt the data
    let ciphertext = sodiumoxide::crypto::secretbox::seal(data_bytes, &nonce, &key);

    // Return encrypted payload as JSON string
    let encrypted_payload = json!({
        "nonce": BASE64.encode(nonce.as_ref()),
        "ciphertext": BASE64.encode(&ciphertext),
    });

    Ok(sonic_rs::to_string(&encrypted_payload)?)
}

/// Encrypts data using pure Rust crypto libraries
#[cfg(all(feature = "encryption", not(feature = "sodiumoxide")))]
fn encrypt_pure_rust(pusher: &Pusher, channel: &str, data: &EventData) -> Result<String> {
    use chacha20poly1305::{
        ChaCha20Poly1305, Nonce,
        aead::{Aead, AeadCore, KeyInit, OsRng},
    };

    // Ensure master key is present
    let _master_key =
        pusher
            .config()
            .encryption_master_key()
            .ok_or_else(|| PusherError::Encryption {
                message: "Set encryptionMasterKey before triggering events on encrypted channels"
                    .to_string(),
            })?;

    // Get channel shared secret
    let shared_secret_bytes = pusher.channel_shared_secret(channel)?;

    // Create cipher
    let cipher = ChaCha20Poly1305::new_from_slice(&shared_secret_bytes).map_err(|_| {
        PusherError::Encryption {
            message: "Failed to create cipher from shared secret".to_string(),
        }
    })?;

    // Generate random nonce
    let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);

    // Encrypt the data
    let data_string = data.to_string();
    let ciphertext = cipher
        .encrypt(&nonce, data_string.as_bytes())
        .map_err(|_| PusherError::Encryption {
            message: "Encryption failed".to_string(),
        })?;

    // Return encrypted payload as JSON string
    let encrypted_payload = json!({
        "nonce": BASE64.encode(&nonce),
        "ciphertext": BASE64.encode(&ciphertext),
    });

    Ok(sonic_rs::to_string(&encrypted_payload)?)
}

/// Stub function when encryption is disabled
#[cfg(not(feature = "encryption"))]
fn encrypt(_pusher: &Pusher, _channel: &str, _data: &EventData) -> Result<String> {
    Err(PusherError::Encryption {
        message: "Encryption support is not enabled. Enable the 'encryption' feature to use encrypted channels.".to_string(),
    })
}

/// Triggers an event on channels
pub async fn trigger<D: Into<EventData>>(
    pusher: &Pusher,
    channels: &[Channel],
    event_name: impl AsRef<str>,
    data: D,
    params: Option<&TriggerParams>,
) -> Result<reqwest::Response> {
    let data = data.into();
    let event_name = event_name.as_ref();

    // Validate event name
    if event_name.len() > 200 {
        return Err(PusherError::Validation {
            message: format!("Event name too long: '{}' (max 200 characters)", event_name),
        });
    }

    // Convert channels to strings
    let channel_strings: Vec<String> = channels.iter().map(|c| c.full_name()).collect();

    if channels.len() == 1 && channels[0].is_encrypted() {
        #[cfg(feature = "encryption")]
        {
            let encrypted_data = encrypt(pusher, &channel_strings[0], &data)?;

            let mut event = Event {
                name: event_name.to_string(),
                data: encrypted_data,
                channels: channel_strings,
                socket_id: None,
                info: None,
                tags: None,
            };

            if let Some(params) = params {
                event.socket_id = params.socket_id.clone();
                event.info = params.info.clone();
                event.tags = params.tags.clone();
            }

            let event_json = sonic_rs::to_value(&event)?;
            pusher.post("/events", &event_json).await
        }

        #[cfg(not(feature = "encryption"))]
        {
            Err(PusherError::Encryption {
                message: "Encryption support is not enabled. Enable the 'encryption' feature to use encrypted channels.".to_string(),
            })
        }
    } else {
        // Check for encrypted channels in multi-channel trigger
        for channel in channels {
            if channel.is_encrypted() {
                return Err(PusherError::Validation {
                    message:
                        "You cannot trigger to multiple channels when using encrypted channels"
                            .to_string(),
                });
            }
        }

        let mut event = Event {
            name: event_name.to_string(),
            data: data.to_string(),
            channels: channel_strings,
            socket_id: None,
            info: None,
            tags: None,
        };

        if let Some(params) = params {
            event.socket_id = params.socket_id.clone();
            event.info = params.info.clone();
            event.tags = params.tags.clone();
        }

        let event_json = sonic_rs::to_value(&event)?;
        pusher.post("/events", &event_json).await
    }
}

/// Triggers an event on channel names (backward compatibility)
pub async fn trigger_on_channels<D: Into<EventData>>(
    pusher: &Pusher,
    channels: &[String],
    event_name: impl AsRef<str>,
    data: D,
    params: Option<&TriggerParams>,
) -> Result<reqwest::Response> {
    let channels: Result<Vec<Channel>> = channels.iter().map(|c| Channel::from_string(c)).collect();
    let channels = channels?;
    trigger(pusher, &channels, event_name, data, params).await
}

/// Triggers a batch of events
pub async fn trigger_batch(
    pusher: &Pusher,
    mut batch: Vec<BatchEvent>,
) -> Result<reqwest::Response> {
    // Validate batch size
    if batch.is_empty() {
        return Err(PusherError::Validation {
            message: "Batch cannot be empty".to_string(),
        });
    }

    if batch.len() > 10 {
        return Err(PusherError::Validation {
            message: format!("Batch too large: {} events (max 10)", batch.len()),
        });
    }

    // Encrypt data for encrypted channels
    for event in &mut batch {
        let channel = Channel::from_string(&event.channel)?;
        if channel.is_encrypted() {
            #[cfg(feature = "encryption")]
            {
                let data = EventData::String(event.data.clone());
                event.data = encrypt(pusher, &event.channel, &data)?;
            }

            #[cfg(not(feature = "encryption"))]
            {
                return Err(PusherError::Encryption {
                    message: "Encryption support is not enabled. Enable the 'encryption' feature to use encrypted channels.".to_string(),
                });
            }
        }
    }

    let batch_payload = json!({ "batch": batch });
    pusher.post("/batch_events", &batch_payload).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use sonic_rs::json;

    #[test]
    fn test_event_data_conversions() {
        // Test string
        let data = EventData::from_string("hello");
        assert_eq!(data.to_string(), "hello");

        // Test JSON
        let json_data = json!({"key": "value"});
        let data = EventData::from_json(json_data.clone());
        assert_eq!(data.as_json().unwrap(), json_data);

        // Test From implementations
        let data: EventData = "test".into();
        assert!(matches!(data, EventData::String(_)));

        let data: EventData = json!({"test": 123}).into();
        assert!(matches!(data, EventData::Json(_)));
    }

    #[test]
    fn test_batch_event_builder() {
        let event = BatchEvent::new("test-event", "test-channel", "test-data")
            .with_socket_id("123.456")
            .with_info("test-info");

        assert_eq!(event.name, "test-event");
        assert_eq!(event.channel, "test-channel");
        assert_eq!(event.data, "test-data");
        assert_eq!(event.socket_id, Some("123.456".to_string()));
        assert_eq!(event.info, Some("test-info".to_string()));
    }

    #[test]
    fn test_batch_event_with_tags() {
        let mut tags = HashMap::new();
        tags.insert("symbol".to_string(), "BONK".to_string());
        tags.insert("price_usd".to_string(), "0.00001".to_string());

        let event =
            BatchEvent::new("test-event", "test-channel", "test-data").with_tags(tags.clone());

        assert_eq!(event.tags, Some(tags));
    }

    #[test]
    fn test_trigger_params_builder() {
        let params = TriggerParams::builder()
            .socket_id("123.456")
            .info("test-info")
            .build();

        assert_eq!(params.socket_id, Some("123.456".to_string()));
        assert_eq!(params.info, Some("test-info".to_string()));
    }

    #[test]
    fn test_trigger_params_builder_with_tags() {
        let mut tags = HashMap::new();
        tags.insert("event_type".to_string(), "goal".to_string());

        let params = TriggerParams::builder().tags(tags.clone()).build();

        assert_eq!(params.tags, Some(tags));
    }
}