tigerbeetle-client 0.16.67

TigerBeetle client for Rust — pre-built static library for all supported platforms
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
<!-- This file is generated by [/src/scripts/client_readmes.zig](/src/scripts/client_readmes.zig). -->
# tigerbeetle-rust

The TigerBeetle client for Rust.

[![crates.io](https://img.shields.io/crates/v/tigerbeetle)](https://crates.io/crates/tigerbeetle)
[![docs.rs](https://img.shields.io/docsrs/tigerbeetle)](https://docs.rs/tigerbeetle)

## Prerequisites

Linux >= 5.6 is the only production environment we
support. But for ease of development we also support macOS and Windows.
* Rust 1.68+

## Setup

First, create a directory for your project and `cd` into the directory.

Then create `Cargo.toml` and copy this into it:

```toml
[package]
name = "tigerbeetle-test"
version = "0.1.0"
edition = "2024"

[dependencies]
tigerbeetle.path = "../.."
futures = "0.3"
```

Now, create `src/main.rs` and copy this into it:

```rust
use tigerbeetle as tb;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    futures::executor::block_on(main_async())
}

async fn main_async() -> Result<(), Box<dyn std::error::Error>> {
    println!("hello world");
}
```

Finally, build and run:

```console
cargo run
```

Now that all prerequisites and dependencies are correctly set
up, let's dig into using TigerBeetle.

## Sample projects

This document is primarily a reference guide to
the client. Below are various sample projects demonstrating
features of TigerBeetle.

* [Basic]/src/clients/rust/samples/basic/: Create two accounts and transfer an amount between them.
* [Two-Phase Transfer]/src/clients/rust/samples/two-phase/: Create two accounts and start a pending transfer between
them, then post the transfer.
* [Many Two-Phase Transfers]/src/clients/rust/samples/two-phase-many/: Create two accounts and start a number of pending transfers
between them, posting and voiding alternating transfers.
## Creating a Client

A client is created with a cluster ID and replica
addresses for all replicas in the cluster. The cluster
ID and replica addresses are both chosen by the system that
starts the TigerBeetle cluster.

Clients are thread-safe and a single instance should be shared
between multiple concurrent tasks. This allows events to be 
[automatically batched](https://docs.tigerbeetle.com/coding/requests/#batching-events).

Multiple clients are useful when connecting to more than
one TigerBeetle cluster.

In this example the cluster ID is `0` and there is one
replica. The address is read from the `TB_ADDRESS`
environment variable and defaults to port `3000`.

```rust
let cluster_id = 0;
let replica_address = std::env::var("TB_ADDRESS")
    .ok()
    .unwrap_or_else(|| String::from("3000"));
let client = tb::Client::new(cluster_id, &replica_address)?;
```

The following are valid addresses:
* `3000` (interpreted as `127.0.0.1:3000`)
* `127.0.0.1:3000` (interpreted as `127.0.0.1:3000`)
* `127.0.0.1` (interpreted as `127.0.0.1:3001`, `3001` is the default port)

## Creating Accounts

See details for account fields in the [Accounts
reference](https://docs.tigerbeetle.com/reference/account).

```rust
let account_errors = client
    .create_accounts(&[tb::Account {
        id: tb::id(),
        ledger: 1,
        code: 718,
        ..Default::default()
    }])
    .await?;
// Error handling omitted.
```

See details for the recommended ID scheme in
[time-based identifiers](https://docs.tigerbeetle.com/coding/data-modeling#tigerbeetle-time-based-identifiers-recommended).

### Account Flags

The account flags value is a bitfield. See details for
these flags in the [Accounts
reference](https://docs.tigerbeetle.com/reference/account#flags).

To toggle behavior for an account, use the `AccountFlags` bitflags.
You can combine multiple flags using the `|` operator. Here are a
few examples:

* `AccountFlags::Linked`
* `AccountFlags::DebitsMustNotExceedCredits`
* `AccountFlags::CreditsMustNotExceedDebits`
* `AccountFlags::History`
* `AccountFlags::Linked | AccountFlags::History`

For example, to link two accounts where the first account
additionally has the `debits_must_not_exceed_credits` constraint:

```rust
let account0 = tb::Account {
    id: 100,
    ledger: 1,
    code: 718,
    flags: tb::AccountFlags::DebitsMustNotExceedCredits | tb::AccountFlags::Linked,
    ..Default::default()
};
let account1 = tb::Account {
    id: 101,
    ledger: 1,
    code: 718,
    flags: tb::AccountFlags::History,
    ..Default::default()
};

let account_errors = client.create_accounts(&[account0, account1]).await?;
// Error handling omitted.
```

### Response and Errors

The response is an empty array if all accounts were
created successfully. If the response is non-empty, each
object in the response array contains error information
for an account that failed. The error object contains an
error code and the index of the account in the request
batch.

See all error conditions in the [create_accounts
reference](https://docs.tigerbeetle.com/reference/requests/create_accounts).

```rust
let account0 = tb::Account {
    id: 102,
    ledger: 1,
    code: 718,
    ..Default::default()
};
let account1 = tb::Account {
    id: 103,
    ledger: 1,
    code: 718,
    ..Default::default()
};
let account2 = tb::Account {
    id: 104,
    ledger: 1,
    code: 718,
    ..Default::default()
};

let account_errors = client
    .create_accounts(&[account0, account1, account2])
    .await?;

assert!(account_errors.len() <= 3);

for err in account_errors {
    match err.result {
        tb::CreateAccountResult::Exists => {
            println!("Batch account at {} already exists.", err.index);
        }
        _ => {
            eprintln!(
                "Batch account at {} failed to create: {:?}",
                err.index, err.result
            );
        }
    }
}
```

To handle errors, iterate over the `Vec<CreateAccountsResult>` returned
from `client.create_accounts()`. Each result contains an `index` field
to map back to the input account and a `result` field with the
`CreateAccountResult` enum.

## Account Lookup

Account lookup is batched, like account creation. Pass
in all IDs to fetch. The account for each matched ID is returned.

If no account matches an ID, no object is returned for
that account. So the order of accounts in the response is
not necessarily the same as the order of IDs in the
request. You can refer to the ID field in the response to
distinguish accounts.

```rust
let accounts = client.lookup_accounts(&[100, 101]).await?;
```

## Create Transfers

This creates a journal entry between two accounts.

See details for transfer fields in the [Transfers
reference](https://docs.tigerbeetle.com/reference/transfer).

```rust
let transfers = vec![tb::Transfer {
    id: tb::id(),
    debit_account_id: 101,
    credit_account_id: 102,
    amount: 10,
    ledger: 1,
    code: 1,
    ..Default::default()
}];

let transfer_errors = client.create_transfers(&transfers).await?;
// Error handling omitted.
```

See details for the recommended ID scheme in
[time-based identifiers](https://docs.tigerbeetle.com/coding/data-modeling#tigerbeetle-time-based-identifiers-recommended).

### Response and Errors

The response is an empty array if all transfers were created
successfully. If the response is non-empty, each object in the
response array contains error information for a transfer that
failed. The error object contains an error code and the index of the
transfer in the request batch.

See all error conditions in the [create_transfers
reference](https://docs.tigerbeetle.com/reference/requests/create_transfers).

```rust
let transfers = vec![
    tb::Transfer {
        id: 1,
        debit_account_id: 101,
        credit_account_id: 102,
        amount: 10,
        ledger: 1,
        code: 1,
        ..Default::default()
    },
    tb::Transfer {
        id: 2,
        debit_account_id: 101,
        credit_account_id: 102,
        amount: 10,
        ledger: 1,
        code: 1,
        ..Default::default()
    },
    tb::Transfer {
        id: 3,
        debit_account_id: 101,
        credit_account_id: 102,
        amount: 10,
        ledger: 1,
        code: 1,
        ..Default::default()
    },
];

let transfer_errors = client.create_transfers(&transfers).await?;

for err in transfer_errors {
    match err.result {
        tb::CreateTransferResult::Exists => {
            println!("Batch transfer at {} already exists.", err.index);
        }
        _ => {
            eprintln!(
                "Batch transfer at {} failed to create: {:?}",
                err.index, err.result
            );
        }
    }
}
```

To handle transfer errors, iterate over the `Vec<CreateTransfersResult>`
returned from `client.create_transfers()`. Each result contains an
`index` field to map back to the input transfer and a `result` field
with the `CreateTransferResult` enum.

## Batching

TigerBeetle performance is maximized when you batch
API requests.
A client instance shared across multiple threads/tasks can automatically
batch concurrent requests, but the application must still send as many events
as possible in a single call.
For example, if you insert 1 million transfers sequentially, one at a time,
the insert rate will be a *fraction* of the potential, because the client will
wait for a reply between each one.

```rust
let batch: Vec<tb::Transfer> = vec![];
for transfer in &batch {
    let transfer_errors = client.create_transfers(&[*transfer]).await?;
    // Error handling omitted.
}
```

Instead, **always batch as much as you can**.
The maximum batch size is set in the TigerBeetle server. The default is 8189.

```rust
let transfers: Vec<tb::Transfer> = vec![];
const BATCH_SIZE: usize = 8189;
for batch in transfers.chunks(BATCH_SIZE) {
    let transfer_errors = client.create_transfers(batch).await?;
    // Error handling omitted.
}
```

### Queues and Workers

If you are making requests to TigerBeetle from workers
pulling jobs from a queue, you can batch requests to
TigerBeetle by having the worker act on multiple jobs from
the queue at once rather than one at a time. i.e. pulling
multiple jobs from the queue rather than just one.

## Transfer Flags

The transfer `flags` value is a bitfield. See details for these flags in
the [Transfers
reference](https://docs.tigerbeetle.com/reference/transfer#flags).

To toggle behavior for a transfer, use the `TransferFlags` bitflags.
You can combine multiple flags using the `|` operator. Here are a
few examples:

* `TransferFlags::Linked`
* `TransferFlags::Pending`
* `TransferFlags::PostPendingTransfer`
* `TransferFlags::VoidPendingTransfer`
* `TransferFlags::Linked | TransferFlags::Pending`

For example, to link `transfer0` and `transfer1`:

```rust
let transfer0 = tb::Transfer {
    id: 4,
    debit_account_id: 101,
    credit_account_id: 102,
    amount: 10,
    ledger: 1,
    code: 1,
    flags: tb::TransferFlags::Linked,
    ..Default::default()
};
let transfer1 = tb::Transfer {
    id: 5,
    debit_account_id: 101,
    credit_account_id: 102,
    amount: 10,
    ledger: 1,
    code: 1,
    ..Default::default()
};

let transfer_errors = client.create_transfers(&[transfer0, transfer1]).await?;
// Error handling omitted.
```

### Two-Phase Transfers

Two-phase transfers are supported natively by toggling the appropriate
flag. TigerBeetle will then adjust the `credits_pending` and
`debits_pending` fields of the appropriate accounts. A corresponding
post pending transfer then needs to be sent to post or void the
transfer.

#### Post a Pending Transfer

With `flags` set to `post_pending_transfer`,
TigerBeetle will post the transfer. TigerBeetle will atomically roll
back the changes to `debits_pending` and `credits_pending` of the
appropriate accounts and apply them to the `debits_posted` and
`credits_posted` balances.

```rust
let transfer0 = tb::Transfer {
    id: 6,
    debit_account_id: 101,
    credit_account_id: 102,
    amount: 10,
    ledger: 1,
    code: 1,
    ..Default::default()
};

let transfer_errors = client.create_transfers(&[transfer0]).await?;
// Error handling omitted.

let transfer1 = tb::Transfer {
    id: 7,
    amount: u128::MAX,
    pending_id: 6,
    flags: tb::TransferFlags::PostPendingTransfer,
    ..Default::default()
};

let transfer_errors = client.create_transfers(&[transfer1]).await?;
// Error handling omitted.
```

#### Void a Pending Transfer

In contrast, with `flags` set to `void_pending_transfer`,
TigerBeetle will void the transfer. TigerBeetle will roll
back the changes to `debits_pending` and `credits_pending` of the
appropriate accounts and **not** apply them to the `debits_posted` and
`credits_posted` balances.

```rust
let transfer0 = tb::Transfer {
    id: 8,
    debit_account_id: 101,
    credit_account_id: 102,
    amount: 10,
    ledger: 1,
    code: 1,
    ..Default::default()
};

let transfer_errors = client.create_transfers(&[transfer0]).await?;
// Error handling omitted.

let transfer1 = tb::Transfer {
    id: 9,
    amount: 0,
    pending_id: 8,
    flags: tb::TransferFlags::VoidPendingTransfer,
    ..Default::default()
};

let transfer_errors = client.create_transfers(&[transfer1]).await?;
// Error handling omitted.
```

## Transfer Lookup

NOTE: While transfer lookup exists, it is not a flexible query API. We
are developing query APIs and there will be new methods for querying
transfers in the future.

Transfer lookup is batched, like transfer creation. Pass in all `id`s to
fetch, and matched transfers are returned.

If no transfer matches an `id`, no object is returned for that
transfer. So the order of transfers in the response is not necessarily
the same as the order of `id`s in the request. You can refer to the
`id` field in the response to distinguish transfers.

```rust
let transfers = client.lookup_transfers(&[1, 2]).await?;
```

## Get Account Transfers

NOTE: This is a preview API that is subject to breaking changes once we have
a stable querying API.

Fetches the transfers involving a given account, allowing basic filter and pagination
capabilities.

The transfers in the response are sorted by `timestamp` in chronological or
reverse-chronological order.

```rust
let filter = tb::AccountFilter {
    account_id: 2,
    user_data_128: 0,
    user_data_64: 0,
    user_data_32: 0,
    code: 0,
    reserved: Default::default(),
    timestamp_min: 0,
    timestamp_max: 0,
    limit: 10,
    flags: tb::AccountFilterFlags::Debits
        | tb::AccountFilterFlags::Credits
        | tb::AccountFilterFlags::Reversed,
};

let transfers = client.get_account_transfers(filter).await?;
```

## Get Account Balances

NOTE: This is a preview API that is subject to breaking changes once we have
a stable querying API.

Fetches the point-in-time balances of a given account, allowing basic filter and
pagination capabilities.

Only accounts created with the flag
[`history`](https://docs.tigerbeetle.com/reference/account#flagshistory) set retain
[historical balances](https://docs.tigerbeetle.com/reference/requests/get_account_balances).

The balances in the response are sorted by `timestamp` in chronological or
reverse-chronological order.

```rust
let filter = tb::AccountFilter {
    account_id: 2,
    user_data_128: 0,
    user_data_64: 0,
    user_data_32: 0,
    code: 0,
    reserved: Default::default(),
    timestamp_min: 0,
    timestamp_max: 0,
    limit: 10,
    flags: tb::AccountFilterFlags::Debits
        | tb::AccountFilterFlags::Credits
        | tb::AccountFilterFlags::Reversed,
};

let account_balances = client.get_account_balances(filter).await?;
```

## Query Accounts

NOTE: This is a preview API that is subject to breaking changes once we have
a stable querying API.

Query accounts by the intersection of some fields and by timestamp range.

The accounts in the response are sorted by `timestamp` in chronological or
reverse-chronological order.

```rust
let filter = tb::QueryFilter {
    user_data_128: 1000,
    user_data_64: 100,
    user_data_32: 10,
    code: 1,
    ledger: 0,
    reserved: Default::default(),
    timestamp_min: 0,
    timestamp_max: 0,
    limit: 10,
    flags: tb::QueryFilterFlags::Reversed,
};

let accounts = client.query_accounts(filter).await?;
```

## Query Transfers

NOTE: This is a preview API that is subject to breaking changes once we have
a stable querying API.

Query transfers by the intersection of some fields and by timestamp range.

The transfers in the response are sorted by `timestamp` in chronological or
reverse-chronological order.

```rust
let filter = tb::QueryFilter {
    user_data_128: 1000,
    user_data_64: 100,
    user_data_32: 10,
    code: 1,
    ledger: 0,
    reserved: Default::default(),
    timestamp_min: 0,
    timestamp_max: 0,
    limit: 10,
    flags: tb::QueryFilterFlags::Reversed,
};

let transfers = client.query_transfers(filter).await?;
```

## Linked Events

When the `linked` flag is specified for an account when creating accounts or
a transfer when creating transfers, it links that event with the next event in the
batch, to create a chain of events, of arbitrary length, which all
succeed or fail together. The tail of a chain is denoted by the first
event without this flag. The last event in a batch may therefore never
have the `linked` flag set as this would leave a chain
open-ended. Multiple chains or individual events may coexist within a
batch to succeed or fail independently.

Events within a chain are executed within order, or are rolled back on
error, so that the effect of each event in the chain is visible to the
next, and so that the chain is either visible or invisible as a unit
to subsequent events after the chain. The event that was the first to
break the chain will have a unique error result. Other events in the
chain will have their error result set to `linked_event_failed`.

```rust
let mut batch = vec![];
let linked_flag = tb::TransferFlags::Linked;

// An individual transfer (successful):
batch.push(tb::Transfer {
    id: 1,
    ..Default::default()
});

// A chain of 4 transfers (the last transfer in the chain closes the chain with linked=false):
batch.push(tb::Transfer {
    id: 2,
    flags: linked_flag,
    ..Default::default()
});
batch.push(tb::Transfer {
    id: 3,
    flags: linked_flag,
    ..Default::default()
});
batch.push(tb::Transfer {
    id: 2,
    flags: linked_flag,
    ..Default::default()
});
batch.push(tb::Transfer {
    id: 4,
    ..Default::default()
});

// An individual transfer (successful):
// This should not see any effect from the failed chain above.
batch.push(tb::Transfer {
    id: 2,
    ..Default::default()
});

// A chain of 2 transfers (the first transfer fails the chain):
batch.push(tb::Transfer {
    id: 2,
    flags: linked_flag,
    ..Default::default()
});
batch.push(tb::Transfer {
    id: 3,
    ..Default::default()
});

// A chain of 2 transfers (successful):
batch.push(tb::Transfer {
    id: 3,
    flags: linked_flag,
    ..Default::default()
});
batch.push(tb::Transfer {
    id: 4,
    ..Default::default()
});

let transfer_errors = client.create_transfers(&batch).await?;
// Error handling omitted.
```

## Imported Events

When the `imported` flag is specified for an account when creating accounts or
a transfer when creating transfers, it allows importing historical events with
a user-defined timestamp.

The entire batch of events must be set with the flag `imported`.

It's recommended to submit the whole batch as a `linked` chain of events, ensuring that
if any event fails, none of them are committed, preserving the last timestamp unchanged.
This approach gives the application a chance to correct failed imported events, re-submitting
the batch again with the same user-defined timestamps.

```rust
// External source of time.
let mut historical_timestamp: u64 = 0;
let historical_accounts: Vec<tb::Account> = vec![]; // Loaded from an external source.
let historical_transfers: Vec<tb::Transfer> = vec![]; // Loaded from an external source.

// First, load and import all accounts with their timestamps from the historical source.
let mut accounts_batch = vec![];
for (index, mut account) in historical_accounts.into_iter().enumerate() {
    // Set a unique and strictly increasing timestamp.
    historical_timestamp += 1;
    account.timestamp = historical_timestamp;

    account.flags = if index < accounts_batch.len() - 1 {
        tb::AccountFlags::Imported | tb::AccountFlags::Linked
    } else {
        tb::AccountFlags::Imported
    };

    accounts_batch.push(account);
}

let account_errors = client.create_accounts(&accounts_batch).await?;
// Error handling omitted.

// Then, load and import all transfers with their timestamps from the historical source.
let mut transfers_batch = vec![];
for (index, mut transfer) in historical_transfers.into_iter().enumerate() {
    // Set a unique and strictly increasing timestamp.
    historical_timestamp += 1;
    transfer.timestamp = historical_timestamp;

    transfer.flags = if index < transfers_batch.len() - 1 {
        tb::TransferFlags::Imported | tb::TransferFlags::Linked
    } else {
        tb::TransferFlags::Imported
    };

    transfers_batch.push(transfer);
}

let transfer_errors = client.create_transfers(&transfers_batch).await?;
// Error handling omitted.
// Since it is a linked chain, in case of any error the entire batch is rolled back and can be retried
// with the same historical timestamps without regressing the cluster timestamp.
```