acuity-index-api-rs 0.1.2

High-level Rust client for the acuity-index WebSocket 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
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# API

## Overview

`acuity-index-api-rs` is a high-level async Rust client for the `acuity-index` WebSocket API.

It wraps the JSON-over-WebSocket protocol exposed by `acuity-index` and provides typed request helpers for common operations:

- fetching indexer status
- fetching pallet/event variants
- fetching indexed events by key
- fetching database size on disk
- subscribing to status updates
- subscribing to event notifications

By default, `acuity-index` serves WebSocket traffic on `ws://127.0.0.1:8172`.

## Runtime Model

This crate is Tokio-based.

- transport: `tokio-tungstenite`
- async runtime: `tokio`
- encoding: `serde` + `serde_json`

`IndexerClient` owns a WebSocket connection and a background reader task.

- outgoing requests are assigned monotonically increasing numeric ids
- responses are matched back to the originating request
- unsolicited notifications are routed to subscription receivers

## Public Types

The crate exports these main public types from `src/lib.rs`:

- `IndexerClient`
- `StatusSubscription`
- `EventSubscription`
- `IndexerApiError`
- `ServerError`
- `Key`
- `CustomKey`
- `CustomValue`
- `Bytes32`
- `U64Text`
- `U128Text`
- `Span`
- `EventRef`
- `DecodedEvent`
- `StoredEvent`
- `EventMatch`
- `EventsResponse`
- `EventNotification`
- `StatusUpdate`
- `PalletMeta`
- `EventMeta`
- `SubscriptionTarget`

## Connecting

Create a client with `IndexerClient::connect`:

```rust
use acuity_index_api_rs::IndexerClient;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = IndexerClient::connect("ws://127.0.0.1:8172").await?;
    let spans = client.status().await?;
    println!("{spans:?}");
    Ok(())
}
```

Signature:

```rust
pub async fn connect(url: &str) -> Result<IndexerClient, IndexerApiError>
```

Behavior:

- opens a WebSocket connection to the given URL
- starts an internal background reader task
- returns a cloneable `IndexerClient`
- intended to be reused for both one-shot requests and subscriptions on the same connection

### `close`

Closes the underlying WebSocket connection.

Signature:

```rust
pub async fn close(&self) -> Result<(), IndexerApiError>
```

Behavior:

- sends a WebSocket close frame on the shared connection
- causes the background reader task to observe connection shutdown and terminate
- any pending requests or active subscriptions on that client connection will complete with their normal connection-closure errors

Operational notes for newer `acuity-index` servers:

- a connection attempt can fail before the WebSocket session is established if the server is overloaded
- overload rejection may surface as an HTTP `503 Service Unavailable` during `connect`
- idle connections may be closed by the server after prolonged inactivity

## Server Limits

Current `acuity-index` servers may enforce these connection and request limits:

- max WebSocket message size: `256 KiB`
- max WebSocket frame size: `64 KiB`
- max subscriptions per connection: `128`
- idle timeout: `300s`
- max custom key name length: `128` bytes
- max custom string key length: `1024` bytes

These limits are enforced by the server, not by this client crate.

Practical implications:

- `IndexerClient::connect(...)` can fail if the server rejects the upgrade under load
- oversized custom keys used with `get_events(...)` or `subscribe_events(...)` can be rejected by the server
- a connection with no inbound or outbound traffic can be closed by the server when the idle timeout is reached
- a connection that exceeds the server subscription cap can receive a structured request error

## One-Shot Requests

### `status`

Fetches the indexer's current indexed block spans.

Signature:

```rust
pub async fn status(&self) -> Result<Vec<Span>, IndexerApiError>
```

Return type:

- `Vec<Span>`

`Span`:

```rust
pub struct Span {
    pub start: u32,
    pub end: u32,
}
```

Example:

```rust
let spans = client.status().await?;
for span in spans {
    println!("{}..={}", span.start, span.end);
}
```

### `variants`

Fetches the chain metadata event variants currently known to the indexer.

Signature:

```rust
pub async fn variants(&self) -> Result<Vec<PalletMeta>, IndexerApiError>
```

Return type:

- `Vec<PalletMeta>`

`PalletMeta`:

```rust
pub struct PalletMeta {
    pub index: u8,
    pub name: String,
    pub events: Vec<EventMeta>,
}

pub struct EventMeta {
    pub index: u8,
    pub name: String,
}
```

Example:

```rust
let pallets = client.variants().await?;
for pallet in pallets {
    println!("{} ({})", pallet.name, pallet.index);
}
```

### `size_on_disk`

Fetches the total sled database size in bytes.

Signature:

```rust
pub async fn size_on_disk(&self) -> Result<u64, IndexerApiError>
```

Example:

```rust
let bytes = client.size_on_disk().await?;
println!("database size: {bytes} bytes");
```

### `get_events`

Custom keys support both scalar and flat composite values.

Scalar custom key example:

```json
{
  "id": 3,
  "type": "GetEvents",
  "key": {
    "type": "Custom",
    "value": {
      "name": "ref_index",
      "kind": "u32",
      "value": 42
    }
  }
}
```

Composite custom keys use an ordered array of typed scalar values:

```json
{
  "id": 3,
  "type": "GetEvents",
  "key": {
    "type": "Custom",
    "value": {
      "name": "item_revision",
      "kind": "composite",
      "value": [
        {"kind": "bytes32", "value": "0xabc123..."},
        {"kind": "u32", "value": 7}
      ]
    }
  }
}
```

Composite values are flat only in this crate: each element must be a scalar typed value, not another composite.

Fetches indexed events for a given key.

Signature:

```rust
pub async fn get_events(
    &self,
    key: Key,
    limit: Option<u16>,
    before: Option<EventRef>,
) -> Result<EventsResponse, IndexerApiError>
```

Arguments:

- `key`: the index key to query
- `limit`: optional maximum number of events
- `before`: optional cursor for pagination

Return type:

```rust
pub struct EventsResponse {
    pub key: Key,
    pub events: Vec<EventRef>,
    pub decoded_events: Vec<DecodedEvent>,
}
```

`EventRef`:

```rust
pub struct EventRef {
    pub block_number: u32,
    pub event_index: u16,
}
```

`DecodedEvent`:

```rust
pub struct DecodedEvent {
    pub block_number: u32,
    pub event_index: u16,
    pub event: StoredEvent,
}

pub struct StoredEvent {
    pub spec_version: u32,
    pub pallet_name: String,
    pub event_name: String,
    pub pallet_index: u8,
    pub variant_index: u8,
    pub event_index: u16,
    pub fields: serde_json::Value,
}
```

Helpers:

```rust
impl DecodedEvent {
    pub fn pallet_name(&self) -> &str
    pub fn event_name(&self) -> &str
    pub fn variant(&self) -> (u8, u8)
    pub fn field(&self, name: &str) -> Option<&serde_json::Value>
}

impl StoredEvent {
    pub fn variant(&self) -> (u8, u8)
    pub fn field(&self, name: &str) -> Option<&serde_json::Value>
}
```

Correlated event view:

```rust
pub struct EventMatch {
    pub event_ref: EventRef,
    pub decoded_event: Option<DecodedEvent>,
}

impl EventsResponse {
    pub fn event_matches(&self) -> Vec<EventMatch>
}
```

Example:

```rust
use acuity_index_api_rs::{CustomKey, CustomValue, EventRef, Key};

let response = client
    .get_events(
        Key::Custom(CustomKey {
            name: "ref_index".into(),
            value: CustomValue::U32(42),
        }),
        Some(100),
        Some(EventRef {
            block_number: 500,
            event_index: 3,
        }),
    )
    .await?;

println!("{} raw event refs", response.events.len());
println!("{} decoded events", response.decoded_events.len());

for event_match in response.event_matches() {
    if let Some(decoded) = event_match.decoded_event {
        println!("{}::{}", decoded.pallet_name(), decoded.event_name());
    }
}
```

## Subscriptions

### `subscribe_status`

Subscribes to ongoing indexer status updates.

Signature:

```rust
pub async fn subscribe_status(&self) -> Result<StatusSubscription, IndexerApiError>
```

`StatusSubscription` exposes:

```rust
pub async fn next(&mut self) -> Option<Result<StatusUpdate, IndexerApiError>>
pub async fn unsubscribe(self) -> Result<(), IndexerApiError>
```

Notes:

- dropping a `StatusSubscription` removes only that local receiver
- `unsubscribe()` also sends `UnsubscribeStatus` to the server
- `IndexerClient::unsubscribe_status()` removes all local status subscribers for that client connection and unsubscribes the shared server-side status subscription
- if the shared connection is already at the server's per-connection subscription cap, `subscribe_status()` can fail with `IndexerApiError::Server { code, .. }` where `code` is `"subscription_limit"`

`StatusUpdate`:

```rust
pub struct StatusUpdate {
    pub spans: Vec<Span>,
}
```

Example:

```rust
let mut subscription = client.subscribe_status().await?;

while let Some(update) = subscription.next().await {
    match update {
        Ok(update) => println!("status update: {:?}", update.spans),
        Err(error) => {
            eprintln!("subscription failed: {error}");
            break;
        }
    }
}
```

### `unsubscribe_status`

Cancels the status subscription on the server and clears local status subscribers.

Signature:

```rust
pub async fn unsubscribe_status(&self) -> Result<(), IndexerApiError>
```

### `subscribe_events`

Subscribes to matching indexed events for a key.

Signature:

```rust
pub async fn subscribe_events(&self, key: Key) -> Result<EventSubscription, IndexerApiError>
```

`EventSubscription` exposes:

```rust
pub async fn next(&mut self) -> Option<Result<EventNotification, IndexerApiError>>
pub async fn unsubscribe(self) -> Result<(), IndexerApiError>
```

Notes:

- dropping an `EventSubscription` removes only that local receiver
- notifications are delivered only to local subscribers whose `Key` matches the incoming notification key
- `unsubscribe()` also sends `UnsubscribeEvents` for that key to the server
- `IndexerClient::unsubscribe_events(key)` removes all local subscribers for that key and unsubscribes that key on the server for the shared connection
- oversized custom key names or string values can be rejected by the server before the subscription is registered
- if the shared connection is already at the server's per-connection subscription cap, `subscribe_events(...)` can fail with `IndexerApiError::Server { code, .. }` where `code` is `"subscription_limit"`

`EventNotification`:

```rust
pub struct EventNotification {
    pub key: Key,
    pub event: EventRef,
    pub decoded_event: Option<DecodedEvent>,
}
```

Example:

```rust
use acuity_index_api_rs::{CustomKey, CustomValue, Key};

let mut subscription = client
    .subscribe_events(Key::Custom(CustomKey {
        name: "item_id".into(),
        value: CustomValue::Bytes32(acuity_index_api_rs::Bytes32([0x11; 32])),
    }))
    .await?;

while let Some(notification) = subscription.next().await {
    match notification {
        Ok(notification) => println!("event at #{}:{}", notification.event.block_number, notification.event.event_index),
        Err(error) => {
            eprintln!("event subscription failed: {error}");
            break;
        }
    }
}
```

### `unsubscribe_events`

Cancels the event subscription on the server and clears local event subscribers.

Signature:

```rust
pub async fn unsubscribe_events(&self, key: Key) -> Result<(), IndexerApiError>
```

## Key Types

Queries and event subscriptions use `Key`.

```rust
pub enum Key {
    Variant(u8, u8),
    Custom(CustomKey),
}
```

### `Variant`

Matches a pallet event variant directly by `(pallet_index, variant_index)`.

Example:

```rust
let key = acuity_index_api_rs::Key::Variant(42, 0);
```

### `Custom`

Matches a custom named key value.

```rust
pub struct CustomKey {
    pub name: String,
    pub value: CustomValue,
}
```

`CustomValue` supports:

```rust
pub enum CustomValue {
    Bytes32(Bytes32),
    U32(u32),
    U64(U64Text),
    U128(U128Text),
    String(String),
    Bool(bool),
}
```

Examples:

```rust
use acuity_index_api_rs::{Bytes32, CustomKey, CustomValue, Key, U128Text, U64Text};

let bytes32_key = Key::Custom(CustomKey {
    name: "item_id".into(),
    value: CustomValue::Bytes32(Bytes32([0x11; 32])),
});

let u32_key = Key::Custom(CustomKey {
    name: "ref_index".into(),
    value: CustomValue::U32(42),
});

let u64_key = Key::Custom(CustomKey {
    name: "big_id".into(),
    value: CustomValue::U64(U64Text(42)),
});

let u128_key = Key::Custom(CustomKey {
    name: "huge_id".into(),
    value: CustomValue::U128(U128Text(42)),
});

let string_key = Key::Custom(CustomKey {
    name: "slug".into(),
    value: CustomValue::String("hello-world".into()),
});

let bool_key = Key::Custom(CustomKey {
    name: "published".into(),
    value: CustomValue::Bool(true),
});
```

## Error Handling

All public async methods return `Result<_, IndexerApiError>`.

```rust
pub enum IndexerApiError {
    Url(url::ParseError),
    WebSocket(tokio_tungstenite::tungstenite::Error),
    Json(serde_json::Error),
    RequestCancelled { request_id: u64 },
    ResponseChannelClosed { request_id: u64 },
    Server { code: String, message: String },
    StatusSubscriptionTerminated { reason: String, message: String },
    EventSubscriptionTerminated { reason: String, message: String },
    UnexpectedResponseType { request_id: u64, message_type: String },
    NonUtf8Binary,
    ConnectionClosed,
    BackgroundTaskEnded,
}
```

### Common cases

- `Server { .. }`
  - the indexer returned a structured protocol error
  - one current example is `code == "subscription_limit"` when the server rejects a subscription beyond its per-connection cap
- `UnexpectedResponseType { .. }`
  - the server replied to a request with a different response type than expected
- `StatusSubscriptionTerminated { .. }`
  - the server terminated the status subscription
- `EventSubscriptionTerminated { .. }`
  - the server terminated the event subscription
- `ConnectionClosed`
  - the socket closed while waiting for traffic, including server-side idle timeout or normal close handling
- `WebSocket(..)`
  - the initial connection or a later protocol operation failed at the WebSocket layer, including upgrade rejection or close/error conditions surfaced by tungstenite
- `ResponseChannelClosed { .. }`
  - the client-side waiter was dropped before a response arrived
- `RequestCancelled { .. }`
  - pending request was cancelled because the background connection ended

Example:

```rust
match client.status().await {
    Ok(spans) => println!("{spans:?}"),
    Err(error) => eprintln!("status request failed: {error}"),
}
```

## Protocol Mapping

This crate is a high-level wrapper over the underlying `acuity-index` request types:

- `status()` -> `Status`
- `variants()` -> `Variants`
- `size_on_disk()` -> `SizeOnDisk`
- `get_events(...)` -> `GetEvents`
- `subscribe_status()` -> `SubscribeStatus`
- `unsubscribe_status()` -> `UnsubscribeStatus`
- `subscribe_events(key)` -> `SubscribeEvents`
- `unsubscribe_events(key)` -> `UnsubscribeEvents`

Incoming protocol messages are interpreted as follows:

- request responses with matching `id` complete the waiting request future
- `status` notifications are routed to `StatusSubscription`
- `eventNotification` notifications are routed to `EventSubscription`
- `subscriptionTerminated` is surfaced as subscription errors
- `error` with a matching `id` becomes `IndexerApiError::Server`
- request-scoped server limit errors such as `subscription_limit` are surfaced through `IndexerApiError::Server`

## Current Notes

The crate intentionally exposes a high-level API only.

- it does not expose raw request/response wire enums publicly
- it assumes Tokio and `tokio-tungstenite`

## Testing

The crate currently includes unit tests for:

- request serialization
- payload deserialization
- scalar conversions
- notification routing
- error propagation

Run them with:

```bash
cargo test
```