tauri-plugin-centrifugo 0.1.2

Tauri plugin for Centrifugo real-time communication using tokio-centrifuge
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
[![npm version](https://img.shields.io/npm/v/tauri-plugin-centrifugo-api/latest?style=for-the-badge)](https://www.npmjs.com/package/tauri-plugin-centrifugo-api)
[![Crates.io](https://img.shields.io/crates/v/tauri-plugin-centrifugo?style=for-the-badge)](https://crates.io/crates/tauri-plugin-centrifugo)
[![Documentation](https://img.shields.io/badge/docs-docs.rs-blue?style=for-the-badge)](https://docs.rs/tauri-plugin-centrifugo/)
[![GitHub issues](https://img.shields.io/badge/github-issues-orange?style=for-the-badge)](https://github.com/s00d/tauri-plugin-centrifugo/issues)
[![GitHub stars](https://img.shields.io/badge/github-stars-yellow?style=for-the-badge)](https://github.com/s00d/tauri-plugin-centrifugo/stargazers)
[![Donate](https://img.shields.io/badge/Donate-Donationalerts-ff4081?style=for-the-badge)](https://www.donationalerts.com/r/s00d88)

# Tauri Plugin Centrifugo

A Tauri plugin for real-time communication with Centrifugo server using the `tokio-centrifuge` library.

## Features

- **Real-time Communication**: WebSocket-based communication with Centrifugo
- **JSON & Protobuf Support**: Choose between JSON and Protobuf protocols
- **Event-driven Architecture**: Comprehensive event system for connection state and messages
- **Channel Management**: Subscribe/unsubscribe to channels dynamically
- **Authentication**: JWT token support for secure connections
- **Cross-platform**: Works on desktop and mobile platforms

## Installation

### Automatic Installation (Recommended)

Use the Tauri CLI to automatically install both the Rust and JavaScript parts of the plugin:

```bash
# npm
npm run tauri add centrifugo

# yarn  
yarn run tauri add centrifugo

# pnpm
pnpm tauri add centrifugo

# deno
deno task tauri add centrifugo

# bun
bun tauri add centrifugo

# cargo
cargo tauri add centrifugo
```

### Manual Installation

#### Backend (Rust)

Add the plugin using cargo:

```bash
cd ./src-tauri
cargo add tauri-plugin-centrifugo
```

#### Frontend (JavaScript/TypeScript)

Install the JavaScript API:

```bash
npm install tauri-plugin-centrifugo-api
# or
pnpm add tauri-plugin-centrifugo-api
```

## Platform Compatibility

| Platform | Supported |
| -------- | --------- |
| Linux    ||
| Windows  ||
| macOS    ||
| Android  ||
| iOS      ||

## Usage

### Backend Setup

Initialize the plugin in your Tauri app:

```rust
fn main() {
    tauri::Builder::default()
        .plugin(tauri_plugin_centrifugo::init;())
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
```

### Frontend API

#### Basic Connection

```typescript
import { connect, disconnect, isConnected } from 'tauri-plugin-centrifugo-api'

// Connect to Centrifugo server
await connect({
  url: 'ws://localhost:8000/connection/websocket',
  token: 'your-jwt-token', // optional
  name: 'client-name',
  channels: ['channel1', 'channel2'],
  useProtobuf: false,
  readTimeout: 5000
})

// Check connection status
const connected = await isConnected()

// Disconnect
await disconnect()
```

#### Publishing Messages

```typescript
import { helpers } from 'tauri-plugin-centrifugo-api'

// Publish JSON message
await helpers.publishJson('channel-name', {
  message: 'Hello World',
  timestamp: Date.now()
})

// Publish raw data (base64 encoded)
await publish('channel-name', 'base64-encoded-data')
```

#### RPC Calls

```typescript
import { helpers } from 'tauri-plugin-centrifugo-api'

// Execute RPC with JSON data
const result = await helpers.rpcJson('method-name', {
  userId: 123,
  action: 'getInfo'
})

// Execute RPC with raw data
const result = await rpc('method-name', 'base64-encoded-data')
```

#### Event Listeners

```typescript
import { 
  onConnecting, 
  onConnected, 
  onDisconnected, 
  onPublication,
  onSubscribed,
  onUnsubscribed 
} from 'tauri-plugin-centrifugo-api'

// Listen to connection events
const unlistenConnecting = await onConnecting((eventData) => {
  console.log('Connecting...', eventData.payload)
})

const unlistenConnected = await onConnected((eventData) => {
  console.log('Connected!', eventData.payload)
})

const unlistenDisconnected = await onDisconnected((eventData) => {
  console.log('Disconnected:', eventData.payload)
})

// Listen to publications
const unlistenPublication = await onPublication((eventData) => {
  const { channel, data } = eventData.payload
  console.log(`Message on ${channel}:`, data)
})

// Listen to subscription events
const unlistenSubscribed = await onSubscribed((eventData) => {
  console.log('Subscribed to:', eventData.payload.channel)
})

const unlistenUnsubscribed = await onUnsubscribed((eventData) => {
  console.log('Unsubscribed from:', eventData.payload.channel)
})

// Clean up listeners
unlistenConnecting()
unlistenConnected()
unlistenDisconnected()
unlistenPublication()
unlistenSubscribed()
unlistenUnsubscribed()
```

#### Channel Management

```typescript
import { 
  addSubscription, 
  removeSubscription, 
  getSubscriptions 
} from 'tauri-plugin-centrifugo-api'

// Add new subscription
await addSubscription('new-channel')

// Remove subscription
await removeSubscription('channel-name')

// Get all subscriptions
const subscriptions = await getSubscriptions()
```

#### Utility Functions

```typescript
import { utils } from 'tauri-plugin-centrifugo-api'

// Encode data to base64
const encoded = utils.encode('Hello World')

// Decode base64 data
const decoded = utils.decode('SGVsbG8gV29ybGQ=')

// Encode JSON to base64
const jsonEncoded = utils.encodeJson({ message: 'Hello' })

// Decode base64 JSON
const jsonDecoded = utils.decodeJson(jsonEncoded)
```

### Backend Commands

You can also call Centrifugo commands directly from your Rust backend:

```rust
use tauri_plugin_centrifugo::{models::StartConfig, commands::connect};

#[tauri::command]
async fn start_backend_sockets(window: tauri::Window) -> Result<String, String> {
    let config = StartConfig {
        url: "ws://localhost:8000/connection/websocket".to_string(),
        token: None,
        name: Some("backend-client".to_string()),
        version: Some("1.0.0".to_string()),
        channels: vec!["backend".to_string()],
        use_protobuf: false,
        read_timeout: Some(5000),
    };
    
    match connect(window, config).await {
        Ok(_) => Ok("Backend sockets started successfully".to_string()),
        Err(e) => Err(format!("Failed to start backend sockets: {}", e))
    }
}

// Register the command
.invoke_handler(tauri::generate_handler![start_backend_sockets])
```

Then call it from frontend:

```typescript
import { invoke } from '@tauri-apps/api/core'

const result = await invoke<string>('start_backend_sockets')
console.log(result) // "Backend sockets started successfully"
```

## API Reference

### Core Functions

| Function | Description | Parameters | Returns |
|----------|-------------|------------|---------|
| `connect` | Establish connection to Centrifugo | `StartConfig` | `Promise<void>` |
| `disconnect` | Close connection | - | `Promise<void>` |
| `setToken` | Set authentication token | `string` | `Promise<void>` |
| `publish` | Publish message to channel | `channel: string, data: string` | `Promise<void>` |
| `rpc` | Execute RPC call | `method: string, data: string` | `Promise<any>` |

### Helper Functions

| Function | Description | Parameters | Returns |
|----------|-------------|------------|---------|
| `helpers.publishJson` | Publish JSON data | `channel: string, data: any` | `Promise<void>` |
| `helpers.rpcJson` | Execute RPC with JSON | `method: string, data: any` | `Promise<any>` |
| `helpers.subscribeToChannel` | Subscribe to channel with message listener | `channel: string, callback: Function` | `Promise<UnlistenFn>` |
| `helpers.subscribeToChannels` | Subscribe to multiple channels | `channels: string[], callback: Function` | `Promise<UnlistenFn[]>` |
| `helpers.waitForConnection` | Wait for connection with timeout | `timeout?: number` | `Promise<boolean>` |
| `helpers.getConnectionStatus` | Get connection status with retry | `retries?: number` | `Promise<string>` |

### Event Listeners

| Function | Description | Callback Parameter |
|----------|-------------|-------------------|
| `onConnecting` | Connection attempt started | `TauriEventWrapper<ConnectionStatus>` |
| `onConnected` | Connection established | `TauriEventWrapper<ConnectionStatus>` |
| `onDisconnected` | Connection closed | `TauriEventWrapper<ConnectionStatus>` |
| `onError` | Connection error | `TauriEventWrapper<ErrorData>` |
| `onSubscribed` | Channel subscription successful | `TauriEventWrapper<ChannelStatus>` |
| `onUnsubscribed` | Channel unsubscription successful | `TauriEventWrapper<ChannelStatus>` |
| `onSubscribing` | Channel subscription attempt | `TauriEventWrapper<ChannelStatus>` |
| `onPublication` | Message received on channel | `TauriEventWrapper<PublicationData>` |
| `onMessage` | Decoded message with channel info | `{ channel: string, data: any }` |
| `onChannelMessage` | Decoded message for specific channel | `any` |
| `onAnyMessage` | Decoded message with timestamp | `{ channel: string, data: any, timestamp: number }` |

### Utility Functions

| Function | Description | Parameters | Returns |
|----------|-------------|------------|---------|
| `utils.encode` | Encode string to base64 | `string` | `string` |
| `utils.decode` | Decode base64 to string | `string` | `string` |
| `utils.encodeJson` | Encode object to base64 | `any` | `string` |
| `utils.decodeJson` | Decode base64 to object | `string` | `any` |

### Status Functions

| Function | Description | Returns |
|----------|-------------|---------|
| `isConnected` | Check connection status | `Promise<boolean>` |
| `getConnectionState` | Get detailed connection state | `Promise<string>` |
| `getSubscriptions` | Get current subscriptions | `Promise<Record<string, boolean>>` |

### Advanced Functions (NotImplemented)

| Function | Description | Status |
|----------|-------------|---------|
| `presence` | Get presence information for channel | `NotImplemented` |
| `presenceStats` | Get presence statistics for channel | `NotImplemented` |
| `history` | Get message history for channel | `NotImplemented` |
| `send` | Send message to server | `NotImplemented` |
| `refresh` | Refresh authentication token | `NotImplemented` |
| `subRefresh` | Refresh subscription token | `NotImplemented` |
| `ping` | Ping server | `NotImplemented` |

## Configuration

### StartConfig

```typescript
interface StartConfig {
  url: string                    // WebSocket URL
  token?: string                 // JWT authentication token
  name?: string                  // Client name
  version?: string               // Client version
  channels: string[]             // Channels to subscribe to
  useProtobuf: boolean           // Use Protobuf protocol
  readTimeout?: number           // Read timeout in milliseconds
}
```

### Request Interfaces

```typescript
interface PublishRequest {
  channel: string
  data: string                   // base64 encoded data
}

interface RpcRequest {
  method: string
  data: string                   // base64 encoded data
}

interface PresenceRequest {
  channel: string
}

interface PresenceStatsRequest {
  channel: string
}

interface HistoryRequest {
  channel: string
  limit?: number
  since?: string
  reverse?: boolean
}

interface SendRequest {
  data: string                   // base64 encoded data
}

interface RefreshRequest {
  token: string
}

interface SubRefreshRequest {
  channel: string
  token: string
}
```

### Response Interfaces

```typescript
interface PublicationData {
  channel: string
  data: string                   // base64 encoded data
}

interface ConnectionStatus {
  ts: number
}

interface ChannelStatus {
  channel: string
}

interface ErrorData {
  error: string
}

interface RpcResponse {
  method: string
  data: string                   // base64 encoded data
  timestamp: number
}

interface PresenceResponse {
  channel: string
  clients: string[]
  timestamp: number
}

interface PresenceStatsResponse {
  channel: string
  numClients: number
  numUsers: number
  timestamp: number
}

interface HistoryResponse {
  channel: string
  publications: PublicationData[]
  timestamp: number
}

interface PingResponse {
  timestamp: number
}
```

### Event Data Structure

All events use the `TauriEventWrapper` structure:

```typescript
interface TauriEventWrapper<T> {
  event: string
  payload: T
  id: number
}
```

## Advanced Usage Examples

### Message Handling with Decoded Data

```typescript
import { onMessage, onChannelMessage, onAnyMessage } from 'tauri-plugin-centrifugo-api'

// Listen to all messages with automatic JSON decoding
const unlistenMessages = await onMessage(({ channel, data }) => {
  console.log(`Message on ${channel}:`, data)
})

// Listen to messages on specific channel
const unlistenChannel = await onChannelMessage('chat', (data) => {
  console.log('Chat message:', data)
})

// Listen to all messages with timestamp
const unlistenAny = await onAnyMessage(({ channel, data, timestamp }) => {
  console.log(`[${new Date(timestamp).toISOString()}] ${channel}:`, data)
})
```

### Advanced Channel Management

```typescript
import { helpers } from 'tauri-plugin-centrifugo-api'

// Subscribe to multiple channels with unified callback
const unlisteners = await helpers.subscribeToChannels(['news', 'updates'], ({ channel, data }) => {
  console.log(`${channel}:`, data)
})

// Wait for connection before proceeding
const connected = await helpers.waitForConnection(15000)
if (connected) {
  console.log('Ready to publish messages')
} else {
  console.log('Connection timeout')
}

// Get connection status with retry
const status = await helpers.getConnectionStatus(5)
console.log('Connection status:', status)
```

### Error Handling and Retry Logic

```typescript
import { connect, isConnected, helpers } from 'tauri-plugin-centrifugo-api'

async function connectWithRetry(maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`Connection attempt ${attempt}/${maxRetries}`)
      
      await connect({
        url: 'ws://localhost:8000/connection/websocket',
        channels: ['test'],
        useProtobuf: false
      })
      
      // Wait for connection to stabilize
      const connected = await helpers.waitForConnection(5000)
      if (connected) {
        console.log('Successfully connected!')
        return true
      }
      
    } catch (error) {
      console.error(`Attempt ${attempt} failed:`, error)
      
      if (attempt === maxRetries) {
        throw new Error(`Failed to connect after ${maxRetries} attempts`)
      }
      
      // Wait before retry
      await new Promise(resolve => setTimeout(resolve, 1000 * attempt))
    }
  }
  
  return false
}
```

## Example Application

The repository includes a complete Svelte example application demonstrating all plugin features:

- Connection management
- Message publishing
- RPC calls
- Event handling
- Channel subscriptions
- Backend command integration

To run the example:

```bash
cd examples/tauri-app
pnpm install
pnpm tauri dev
```

## Development

### Building

```bash
# Build Rust plugin
cargo build

# Build JavaScript API
cd guest-js
pnpm build

# Build example app
cd examples/tauri-app
pnpm tauri build
```

### Testing

```bash
# Test Rust code
cargo test

# Test example app
cd examples/tauri-app
pnpm tauri dev
```

## Dependencies

- **Rust**: tauri 2.6.2+, tokio-centrifugo, serde, thiserror
- **JavaScript**: @tauri-apps/api >=2.0.0-beta.6
- **Build Tools**: rollup, typescript


## Permissions

By default all potentially dangerous plugin commands and scopes are blocked and cannot be accessed. You must modify the permissions in your `capabilities` configuration to enable these.

See the [Capabilities Overview](https://v2.tauri.app/security/capabilities/) for more information and the [step by step guide](https://v2.tauri.app/learn/security/using-plugin-permissions/) to use plugin permissions.

```json title="src-tauri/capabilities/default.json" ins={4}
{
  "permissions": [
    "...",
    "centrifugo:default"
  ]
}
```

## License

MIT License - see LICENSE file for details.

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## Support

For issues and questions:
- Create an issue on GitHub
- Check the example application
- Review the API documentation
# tauri-plugin-centrifugo