Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/tigerbeetle/src/clients/node/samples | repos/tigerbeetle/src/clients/node/samples/walkthrough/package.json | {
"dependencies": {
"tigerbeetle-node": "file:../../"
}
}
|
0 | repos/tigerbeetle/src/clients/node/samples | repos/tigerbeetle/src/clients/node/samples/walkthrough/package-lock.json | {
"name": "walkthrough",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"tigerbeetle-node": "file:../../"
}
},
"../..": {
"name": "tigerbeetle-node",
"version": "0.12.0",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^14.14.41",
"node-api-headers": "^0.0.2",
"typescript": "^4.0.2"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/tigerbeetle-node": {
"resolved": "../..",
"link": true
}
}
}
|
0 | repos/tigerbeetle/src/clients/node/samples | repos/tigerbeetle/src/clients/node/samples/walkthrough/README.md | Code from the [top-level README.md](../../README.md) collected into a single runnable project.
|
0 | repos/tigerbeetle/src/clients/node/samples | repos/tigerbeetle/src/clients/node/samples/walkthrough/main.js | // section:imports
const { createClient } = require("tigerbeetle-node");
console.log("Import ok!");
// endsection:imports
const {
AccountFlags,
TransferFlags,
CreateTransferError,
CreateAccountError,
AccountFilterFlags,
amount_max,
} = require("tigerbeetle-node");
async function main() {
// section:client
const client = createClient({
cluster_id: 0n,
replica_addresses: [process.env.TB_ADDRESS || "3000"],
});
// endsection:client
// section:create-accounts
let account = {
id: 137n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 718,
flags: 0,
timestamp: 0n,
};
let accountErrors = await client.createAccounts([account]);
// endsection:create-accounts
// section:account-flags
let account0 = {
id: 100n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
timestamp: 0n,
flags: 0,
};
let account1 = {
id: 101n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
timestamp: 0n,
flags: 0,
};
account0.flags = AccountFlags.linked |
AccountFlags.debits_must_not_exceed_credits;
accountErrors = await client.createAccounts([account0, account1]);
// endsection:account-flags
// section:create-accounts-errors
let account2 = {
id: 102n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
timestamp: 0n,
flags: 0,
};
let account3 = {
id: 103n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
timestamp: 0n,
flags: 0,
};
let account4 = {
id: 104n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
timestamp: 0n,
flags: 0,
};
accountErrors = await client.createAccounts([account2, account3, account4]);
for (const error of accountErrors) {
switch (error.result) {
case CreateAccountError.exists:
console.error(`Batch account at ${error.index} already exists.`);
break;
default:
console.error(
`Batch account at ${error.index} failed to create: ${
CreateAccountError[error.result]
}.`,
);
}
}
// endsection:create-accounts-errors
// section:lookup-accounts
const accounts = await client.lookupAccounts([137n, 138n]);
console.log(accounts);
/*
* [{
* id: 137n,
* debits_pending: 0n,
* debits_posted: 0n,
* credits_pending: 0n,
* credits_posted: 0n,
* user_data_128: 0n,
* user_data_64: 0n,
* user_data_32: 0,
* reserved: 0,
* ledger: 1,
* code: 718,
* flags: 0,
* timestamp: 1623062009212508993n,
* }]
*/
// endsection:lookup-accounts
// section:create-transfers
let transfers = [{
id: 1n,
debit_account_id: 102n,
credit_account_id: 103n,
amount: 10n,
pending_id: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 720,
flags: 0,
timestamp: 0n,
}];
let transferErrors = await client.createTransfers(transfers);
// endsection:create-transfers
// section:create-transfers-errors
for (const error of transferErrors) {
switch (error.result) {
case CreateTransferError.exists:
console.error(`Batch transfer at ${error.index} already exists.`);
break;
default:
console.error(
`Batch transfer at ${error.index} failed to create: ${
CreateTransferError[error.result]
}.`,
);
}
}
// endsection:create-transfers-errors
// section:no-batch
for (let i = 0; i < transfers.len; i++) {
const transferErrors = await client.createTransfers(transfers[i]);
// Error handling omitted.
}
// endsection:no-batch
// section:batch
const BATCH_SIZE = 8190;
for (let i = 0; i < transfers.length; i += BATCH_SIZE) {
const transferErrors = await client.createTransfers(
transfers.slice(i, Math.min(transfers.length, BATCH_SIZE)),
);
// Error handling omitted.
}
// endsection:batch
// section:transfer-flags-link
let transfer0 = {
id: 2n,
debit_account_id: 102n,
credit_account_id: 103n,
amount: 10n,
pending_id: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 720,
flags: 0,
timestamp: 0n,
};
let transfer1 = {
id: 3n,
debit_account_id: 102n,
credit_account_id: 103n,
amount: 10n,
pending_id: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 720,
flags: 0,
timestamp: 0n,
};
transfer0.flags = TransferFlags.linked;
// Create the transfer
transferErrors = await client.createTransfers([transfer0, transfer1]);
// endsection:transfer-flags-link
// section:transfer-flags-post
let transfer2 = {
id: 4n,
debit_account_id: 102n,
credit_account_id: 103n,
amount: 10n,
pending_id: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 720,
flags: TransferFlags.pending,
timestamp: 0n,
};
transferErrors = await client.createTransfers([transfer2]);
let transfer3 = {
id: 5n,
debit_account_id: 102n,
credit_account_id: 103n,
// Post the entire pending amount.
amount: amount_max,
pending_id: 4n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 720,
flags: TransferFlags.post_pending_transfer,
timestamp: 0n,
};
transferErrors = await client.createTransfers([transfer3]);
// endsection:transfer-flags-post
// section:transfer-flags-void
let transfer4 = {
id: 4n,
debit_account_id: 102n,
credit_account_id: 103n,
amount: 10n,
pending_id: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 720,
flags: TransferFlags.pending,
timestamp: 0n,
};
transferErrors = await client.createTransfers([transfer4]);
let transfer5 = {
id: 7n,
debit_account_id: 102n,
credit_account_id: 103n,
amount: 10n,
pending_id: 6n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 720,
flags: TransferFlags.void_pending_transfer,
timestamp: 0n,
};
transferErrors = await client.createTransfers([transfer5]);
// endsection:transfer-flags-void
// section:lookup-transfers
transfers = await client.lookupTransfers([1n, 2n]);
console.log(transfers);
/*
* [{
* id: 1n,
* debit_account_id: 102n,
* credit_account_id: 103n,
* amount: 10n,
* pending_id: 0n,
* user_data_128: 0n,
* user_data_64: 0n,
* user_data_32: 0,
* timeout: 0,
* ledger: 1,
* code: 720,
* flags: 0,
* timestamp: 1623062009212508993n,
* }]
*/
// endsection:lookup-transfers
// section:get-account-transfers
let filter = {
account_id: 2n,
timestamp_min: 0n, // No filter by Timestamp.
timestamp_max: 0n, // No filter by Timestamp.
limit: 10, // Limit to ten balances at most.
flags: AccountFilterFlags.debits | // Include transfer from the debit side.
AccountFilterFlags.credits | // Include transfer from the credit side.
AccountFilterFlags.reversed, // Sort by timestamp in reverse-chronological order.
};
const account_transfers = await client.getAccountTransfers(filter);
// endsection:get-account-transfers
// section:get-account-balances
filter = {
account_id: 2n,
timestamp_min: 0n, // No filter by Timestamp.
timestamp_max: 0n, // No filter by Timestamp.
limit: 10, // Limit to ten balances at most.
flags: AccountFilterFlags.debits | // Include transfer from the debit side.
AccountFilterFlags.credits | // Include transfer from the credit side.
AccountFilterFlags.reversed, // Sort by timestamp in reverse-chronological order.
};
const account_balances = await client.getAccountBalances(filter);
// endsection:get-account-balances
// section:query-accounts
var query_filter = {
user_data_128: 1000n, // Filter by UserData.
user_data_64: 100n,
user_data_32: 10,
code: 1, // Filter by Code.
ledger: 0, // No filter by Ledger.
timestamp_min: 0n, // No filter by Timestamp.
timestamp_max: 0n, // No filter by Timestamp.
limit: 10, // Limit to ten balances at most.
flags: AccountFilterFlags.debits | // Include transfer from the debit side.
AccountFilterFlags.credits | // Include transfer from the credit side.
AccountFilterFlags.reversed, // Sort by timestamp in reverse-chronological order.
};
const query_accounts = await client.queryAccounts(query_filter);
// endsection:query-accounts
// section:query-transfers
query_filter = {
user_data_128: 1000n, // Filter by UserData.
user_data_64: 100n,
user_data_32: 10,
code: 1, // Filter by Code.
ledger: 0, // No filter by Ledger.
timestamp_min: 0n, // No filter by Timestamp.
timestamp_max: 0n, // No filter by Timestamp.
limit: 10, // Limit to ten balances at most.
flags: AccountFilterFlags.debits | // Include transfer from the debit side.
AccountFilterFlags.credits | // Include transfer from the credit side.
AccountFilterFlags.reversed, // Sort by timestamp in reverse-chronological order.
};
const query_transfers = await client.queryTransfers(query_filter);
// endsection:query-transfers
try {
// section:linked-events
const batch = [];
let linkedFlag = 0;
linkedFlag |= TransferFlags.linked;
// An individual transfer (successful):
batch.push({ id: 1n /* , ... */ });
// A chain of 4 transfers (the last transfer in the chain closes the chain with linked=false):
batch.push({ id: 2n, /* ..., */ flags: linkedFlag }); // Commit/rollback.
batch.push({ id: 3n, /* ..., */ flags: linkedFlag }); // Commit/rollback.
batch.push({ id: 2n, /* ..., */ flags: linkedFlag }); // Fail with exists
batch.push({ id: 4n, /* ..., */ flags: 0 }); // Fail without committing.
// An individual transfer (successful):
// This should not see any effect from the failed chain above.
batch.push({ id: 2n, /* ..., */ flags: 0 });
// A chain of 2 transfers (the first transfer fails the chain):
batch.push({ id: 2n, /* ..., */ flags: linkedFlag });
batch.push({ id: 3n, /* ..., */ flags: 0 });
// A chain of 2 transfers (successful):
batch.push({ id: 3n, /* ..., */ flags: linkedFlag });
batch.push({ id: 4n, /* ..., */ flags: 0 });
const errors = await client.createTransfers(batch);
/**
* console.log(errors);
* [
* { index: 1, error: 1 }, // linked_event_failed
* { index: 2, error: 1 }, // linked_event_failed
* { index: 3, error: 25 }, // exists
* { index: 4, error: 1 }, // linked_event_failed
*
* { index: 6, error: 17 }, // exists_with_different_flags
* { index: 7, error: 1 }, // linked_event_failed
* ]
*/
// endsection:linked-events
// External source of time.
let historicalTimestamp = 0n
const historicalAccounts = [];
const historicalTransfers = [];
// section:imported-events
// First, load and import all accounts with their timestamps from the historical source.
const accountsBatch = [];
for (let index = 0; i < historicalAccounts.length; i++) {
let account = historicalAccounts[i];
// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
account.timestamp = historicalTimestamp;
// Set the account as `imported`.
account.flags = AccountFlags.imported;
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalAccounts.length - 1) {
account.flags |= AccountFlags.linked;
}
accountsBatch.push(account);
}
accountErrors = await client.createAccounts(accountsBatch);
// Error handling omitted.
// Then, load and import all transfers with their timestamps from the historical source.
const transfersBatch = [];
for (let index = 0; i < historicalTransfers.length; i++) {
let transfer = historicalTransfers[i];
// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
transfer.timestamp = historicalTimestamp;
// Set the account as `imported`.
transfer.flags = TransferFlags.imported;
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalTransfers.length - 1) {
transfer.flags |= TransferFlags.linked;
}
transfersBatch.push(transfer);
}
transferErrors = await client.createAccounts(transfersBatch);
// 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.
// endsection:imported-events
} catch (exception) {
// This currently throws because the batch is actually invalid (most of fields are
// undefined). Ideally, we prepare a correct batch here while keeping the syntax compact,
// for the example, but for the time being lets prioritize a readable example and just
// swallow the error.
}
}
main()
.then(() => process.exit(0))
.catch((e) => {
console.error(e);
process.exit(1);
});
|
0 | repos/tigerbeetle/src/clients/node/samples | repos/tigerbeetle/src/clients/node/samples/two-phase/package.json | {
"dependencies": {
"tigerbeetle-node": "file:../../"
}
}
|
0 | repos/tigerbeetle/src/clients/node/samples | repos/tigerbeetle/src/clients/node/samples/two-phase/package-lock.json | {
"name": "two-phase",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"tigerbeetle-node": "file:../../"
}
},
"../..": {
"name": "tigerbeetle-node",
"version": "0.12.0",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^14.14.41",
"node-api-headers": "^0.0.2",
"typescript": "^4.0.2"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/tigerbeetle-node": {
"resolved": "../..",
"link": true
}
}
}
|
0 | repos/tigerbeetle/src/clients/node/samples | repos/tigerbeetle/src/clients/node/samples/two-phase/README.md | <!-- This file is generated by [/src/scripts/client_readmes.zig](/src/scripts/client_readmes.zig). -->
# Two-Phase Transfer Node.js Sample
Code for this sample is in [./main.js](./main.js).
## Prerequisites
Linux >= 5.6 is the only production environment we
support. But for ease of development we also support macOS and Windows.
* NodeJS >= `18`
## Setup
First, clone this repo and `cd` into `tigerbeetle/src/clients/node/samples/two-phase`.
Then, install the TigerBeetle client:
```console
npm install tigerbeetle-node
```
## Start the TigerBeetle server
Follow steps in the repo README to [run
TigerBeetle](/README.md#running-tigerbeetle).
If you are not running on port `localhost:3000`, set
the environment variable `TB_ADDRESS` to the full
address of the TigerBeetle server you started.
## Run this sample
Now you can run this sample:
```console
node main.js
```
## Walkthrough
Here's what this project does.
## 1. Create accounts
This project starts by creating two accounts (`1` and `2`).
## 2. Create pending transfer
Then it begins a
pending transfer of `500` of an amount from account `1` to
account `2`.
## 3. Fetch and validate pending account balances
Then it fetches both accounts and validates that **account `1`** has:
* `debits_posted = 0`
* `credits_posted = 0`
* `debits_pending = 500`
* and `credits_pending = 0`
And that **account `2`** has:
* `debits_posted = 0`
* `credits_posted = 0`
* `debits_pending = 0`
* and `credits_pending = 500`
(This is because a pending
transfer only affects **pending** credits and debits on accounts,
not **posted** credits and debits.)
## 4. Post pending transfer
Then it creates a second transfer that marks the first
transfer as posted.
## 5. Fetch and validate transfers
Then it fetches both transfers, validates
that the two transfers exist, validates that the first
transfer had (and still has) a `pending` flag, and validates
that the second transfer had (and still has) a
`post_pending_transfer` flag.
## 6. Fetch and validate final account balances
Finally, it fetches both accounts, validates they both exist,
and checks that credits and debits for both account are now
*posted*, not pending.
Specifically, that **account `1`** has:
* `debits_posted = 500`
* `credits_posted = 0`
* `debits_pending = 0`
* and `credits_pending = 0`
And that **account `2`** has:
* `debits_posted = 0`
* `credits_posted = 500`
* `debits_pending = 0`
* and `credits_pending = 0`
|
0 | repos/tigerbeetle/src/clients/node/samples | repos/tigerbeetle/src/clients/node/samples/two-phase/main.js | const assert = require("assert");
const {
createClient,
CreateAccountError,
CreateTransferError,
TransferFlags,
} = require("tigerbeetle-node");
const client = createClient({
cluster_id: 0n,
replica_addresses: [process.env.TB_ADDRESS || '3000'],
});
async function main() {
// Create two accounts
let accountErrors = await client.createAccounts([
{
id: 1n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
flags: 0,
timestamp: 0n,
},
{
id: 2n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
flags: 0,
timestamp: 0n,
},
]);
for (const error of accountErrors) {
console.error(`Batch account at ${error.index} failed to create: ${CreateAccountError[error.result]}.`);
}
assert.equal(accountErrors.length, 0);
// Start a pending transfer
let transferErrors = await client.createTransfers([
{
id: 1n,
debit_account_id: 1n,
credit_account_id: 2n,
amount: 500n,
pending_id: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 1,
flags: TransferFlags.pending,
timestamp: 0n,
},
]);
for (const error of transferErrors) {
console.error(`Batch transfer at ${error.index} failed to create: ${CreateTransferError[error.result]}.`);
}
assert.equal(transferErrors.length, 0);
// Validate accounts pending and posted debits/credits before finishing the two-phase transfer
let accounts = await client.lookupAccounts([1n, 2n]);
assert.equal(accounts.length, 2);
for (let account of accounts) {
if (account.id === 1n) {
assert.equal(account.debits_posted, 0);
assert.equal(account.credits_posted, 0);
assert.equal(account.debits_pending, 500);
assert.equal(account.credits_pending, 0);
} else if (account.id === 2n) {
assert.equal(account.debits_posted, 0);
assert.equal(account.credits_posted, 0);
assert.equal(account.debits_pending, 0);
assert.equal(account.credits_pending, 500);
} else {
assert.fail("Unexpected account: " + JSON.stringify(account, null, 2));
}
}
// Create a second transfer simply posting the first transfer
transferErrors = await client.createTransfers([
{
id: 2n,
debit_account_id: 1n,
credit_account_id: 2n,
amount: 500n,
pending_id: 1n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 1,
flags: TransferFlags.post_pending_transfer,
timestamp: 0n,
},
]);
for (const error of transferErrors) {
console.error(`Batch transfer at ${error.index} failed to create: ${CreateTransferError[error.result]}.`);
}
assert.equal(transferErrors.length, 0);
// Validate the contents of all transfers
let transfers = await client.lookupTransfers([1n, 2n]);
assert.equal(transfers.length, 2);
for (let transfer of transfers) {
if (transfer.id === 1n) {
assert.equal(transfer.flags & TransferFlags.pending, TransferFlags.pending);
} else if (transfer.id === 2n) {
assert.equal(transfer.flags & TransferFlags.post_pending_transfer, TransferFlags.post_pending_transfer);
} else {
assert.fail("Unexpected transfer: " + transfer.id);
}
}
// Validate accounts pending and posted debits/credits after finishing the two-phase transfer
accounts = await client.lookupAccounts([1n, 2n]);
assert.equal(accounts.length, 2);
for (let account of accounts) {
if (account.id === 1n) {
assert.equal(account.debits_posted, 500);
assert.equal(account.credits_posted, 0);
assert.equal(account.debits_pending, 0);
assert.equal(account.credits_pending, 0);
} else if (account.id === 2n) {
assert.equal(account.debits_posted, 0);
assert.equal(account.credits_posted, 500);
assert.equal(account.debits_pending, 0);
assert.equal(account.credits_pending, 0);
} else {
assert.fail("Unexpected account: " + account.id);
}
}
console.log('ok');
}
main().then(() => {
process.exit(0);
}).catch((e) => {
console.error(e);
process.exit(1);
});
|
0 | repos/tigerbeetle/src/clients/node | repos/tigerbeetle/src/clients/node/src/test.ts | import assert, { AssertionError } from 'assert'
import {
createClient,
Account,
Transfer,
TransferFlags,
CreateAccountError,
CreateTransferError,
AccountFilter,
AccountFilterFlags,
AccountFlags,
amount_max,
id,
QueryFilter,
QueryFilterFlags,
} from '.'
const client = createClient({
cluster_id: 0n,
replica_addresses: [process.env.TB_ADDRESS || '3000']
})
// Test data
const accountA: Account = {
id: 17n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 718,
flags: 0,
timestamp: 0n // this will be set correctly by the TigerBeetle server
}
const accountB: Account = {
id: 19n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 719,
flags: 0,
timestamp: 0n // this will be set correctly by the TigerBeetle server
}
const tests: Array<{ name: string, fn: () => Promise<void> }> = []
function test(name: string, fn: () => Promise<void>) {
tests.push({ name, fn })
}
test.skip = (name: string, fn: () => Promise<void>) => {
console.log(name + ': SKIPPED')
}
test('id() monotonically increasing', async (): Promise<void> => {
let idA = id();
for (let i = 0; i < 10_000_000; i++) {
// Ensure ID is monotonic between milliseconds if the loop executes too fast.
if (i % 10_000 == 0) {
await new Promise(resolve => setTimeout(resolve, 1))
}
const idB = id();
assert.ok(idB > idA, 'id() returned an id that did not monotonically increase');
idA = idB;
}
})
test('range check `code` on Account to be u16', async (): Promise<void> => {
const account = { ...accountA, id: 0n }
account.code = 65535 + 1
const codeError = await client.createAccounts([account]).catch(error => error)
assert.strictEqual(codeError.message, 'code must be a u16.')
const accounts = await client.lookupAccounts([account.id])
assert.deepStrictEqual(accounts, [])
})
test('can create accounts', async (): Promise<void> => {
const errors = await client.createAccounts([accountA])
assert.deepStrictEqual(errors, [])
})
test('can return error on account', async (): Promise<void> => {
const errors = await client.createAccounts([accountA, accountB])
assert.strictEqual(errors.length, 1)
assert.deepStrictEqual(errors[0], { index: 0, result: CreateAccountError.exists })
})
test('error if timestamp is not set to 0n on account', async (): Promise<void> => {
const account = { ...accountA, timestamp: 2n, id: 3n }
const errors = await client.createAccounts([account])
assert.strictEqual(errors.length, 1)
assert.deepStrictEqual(errors[0], { index: 0, result: CreateAccountError.timestamp_must_be_zero })
})
test('can lookup accounts', async (): Promise<void> => {
const accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
const account1 = accounts[0]
assert.strictEqual(account1.id, 17n)
assert.strictEqual(account1.credits_posted, 0n)
assert.strictEqual(account1.credits_pending, 0n)
assert.strictEqual(account1.debits_posted, 0n)
assert.strictEqual(account1.debits_pending, 0n)
assert.strictEqual(account1.user_data_128, 0n)
assert.strictEqual(account1.user_data_64, 0n)
assert.strictEqual(account1.user_data_32, 0)
assert.strictEqual(account1.code, 718)
assert.strictEqual(account1.ledger, 1)
assert.strictEqual(account1.flags, 0)
assert.ok(account1.timestamp > 0n)
const account2 = accounts[1]
assert.strictEqual(account2.id, 19n)
assert.strictEqual(account2.credits_posted, 0n)
assert.strictEqual(account2.credits_pending, 0n)
assert.strictEqual(account2.debits_posted, 0n)
assert.strictEqual(account2.debits_pending, 0n)
assert.strictEqual(account2.user_data_128, 0n)
assert.strictEqual(account2.user_data_64, 0n)
assert.strictEqual(account2.user_data_32, 0)
assert.strictEqual(account2.code, 719)
assert.strictEqual(account2.ledger, 1)
assert.strictEqual(account2.flags, 0)
assert.ok(account2.timestamp > 0n)
})
test('can create a transfer', async (): Promise<void> => {
const transfer: Transfer = {
id: 1n,
debit_account_id: accountB.id,
credit_account_id: accountA.id,
amount: 100n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 0,
ledger: 1,
code: 1,
flags: 0,
timestamp: 0n, // this will be set correctly by the TigerBeetle server
}
const errors = await client.createTransfers([transfer])
assert.deepStrictEqual(errors, [])
const accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.strictEqual(accounts[0].credits_posted, 100n)
assert.strictEqual(accounts[0].credits_pending, 0n)
assert.strictEqual(accounts[0].debits_posted, 0n)
assert.strictEqual(accounts[0].debits_pending, 0n)
assert.strictEqual(accounts[1].credits_posted, 0n)
assert.strictEqual(accounts[1].credits_pending, 0n)
assert.strictEqual(accounts[1].debits_posted, 100n)
assert.strictEqual(accounts[1].debits_pending, 0n)
})
test('can create a two-phase transfer', async (): Promise<void> => {
let flags = 0
flags |= TransferFlags.pending
const transfer: Transfer = {
id: 2n,
debit_account_id: accountB.id,
credit_account_id: accountA.id,
amount: 50n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 2e9,
ledger: 1,
code: 1,
flags,
timestamp: 0n, // this will be set correctly by the TigerBeetle server
}
const errors = await client.createTransfers([transfer])
assert.deepStrictEqual(errors, [])
const accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.strictEqual(accounts[0].credits_posted, 100n)
assert.strictEqual(accounts[0].credits_pending, 50n)
assert.strictEqual(accounts[0].debits_posted, 0n)
assert.strictEqual(accounts[0].debits_pending, 0n)
assert.strictEqual(accounts[1].credits_posted, 0n)
assert.strictEqual(accounts[1].credits_pending, 0n)
assert.strictEqual(accounts[1].debits_posted, 100n)
assert.strictEqual(accounts[1].debits_pending, 50n)
// Lookup the transfer:
const transfers = await client.lookupTransfers([transfer.id])
assert.strictEqual(transfers.length, 1)
assert.strictEqual(transfers[0].id, 2n)
assert.strictEqual(transfers[0].debit_account_id, accountB.id)
assert.strictEqual(transfers[0].credit_account_id, accountA.id)
assert.strictEqual(transfers[0].amount, 50n)
assert.strictEqual(transfers[0].user_data_128, 0n)
assert.strictEqual(transfers[0].user_data_64, 0n)
assert.strictEqual(transfers[0].user_data_32, 0)
assert.strictEqual(transfers[0].timeout > 0, true)
assert.strictEqual(transfers[0].code, 1)
assert.strictEqual(transfers[0].flags, 2)
assert.strictEqual(transfers[0].timestamp > 0, true)
})
test('can post a two-phase transfer', async (): Promise<void> => {
let flags = 0
flags |= TransferFlags.post_pending_transfer
const commit: Transfer = {
id: 3n,
debit_account_id: BigInt(0),
credit_account_id: BigInt(0),
amount: amount_max,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 2n,// must match the id of the pending transfer
timeout: 0,
ledger: 1,
code: 1,
flags: flags,
timestamp: 0n, // this will be set correctly by the TigerBeetle server
}
const errors = await client.createTransfers([commit])
assert.deepStrictEqual(errors, [])
const accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.strictEqual(accounts[0].credits_posted, 150n)
assert.strictEqual(accounts[0].credits_pending, 0n)
assert.strictEqual(accounts[0].debits_posted, 0n)
assert.strictEqual(accounts[0].debits_pending, 0n)
assert.strictEqual(accounts[1].credits_posted, 0n)
assert.strictEqual(accounts[1].credits_pending, 0n)
assert.strictEqual(accounts[1].debits_posted, 150n)
assert.strictEqual(accounts[1].debits_pending, 0n)
})
test('can reject a two-phase transfer', async (): Promise<void> => {
// Create a two-phase transfer:
const transfer: Transfer = {
id: 4n,
debit_account_id: accountB.id,
credit_account_id: accountA.id,
amount: 50n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 1e9,
ledger: 1,
code: 1,
flags: TransferFlags.pending,
timestamp: 0n, // this will be set correctly by the TigerBeetle server
}
const transferErrors = await client.createTransfers([transfer])
assert.deepStrictEqual(transferErrors, [])
// send in the reject
const reject: Transfer = {
id: 5n,
debit_account_id: BigInt(0),
credit_account_id: BigInt(0),
amount: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 4n, // must match the id of the pending transfer
timeout: 0,
ledger: 1,
code: 1,
flags: TransferFlags.void_pending_transfer,
timestamp: 0n, // this will be set correctly by the TigerBeetle server
}
const errors = await client.createTransfers([reject])
assert.deepStrictEqual(errors, [])
const accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.strictEqual(accounts[0].credits_posted, 150n)
assert.strictEqual(accounts[0].credits_pending, 0n)
assert.strictEqual(accounts[0].debits_posted, 0n)
assert.strictEqual(accounts[0].debits_pending, 0n)
assert.strictEqual(accounts[1].credits_posted, 0n)
assert.strictEqual(accounts[1].credits_pending, 0n)
assert.strictEqual(accounts[1].debits_posted, 150n)
assert.strictEqual(accounts[1].debits_pending, 0n)
})
test('can link transfers', async (): Promise<void> => {
const transfer1: Transfer = {
id: 6n,
debit_account_id: accountB.id,
credit_account_id: accountA.id,
amount: 100n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 0,
ledger: 1,
code: 1,
flags: TransferFlags.linked, // points to transfer2
timestamp: 0n, // will be set correctly by the TigerBeetle server
}
const transfer2: Transfer = {
id: 6n,
debit_account_id: accountB.id,
credit_account_id: accountA.id,
amount: 100n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 0,
ledger: 1,
code: 1,
// Does not have linked flag as it is the end of the chain.
// This will also cause it to fail as this is now a duplicate with different flags
flags: 0,
timestamp: 0n, // will be set correctly by the TigerBeetle server
}
const errors = await client.createTransfers([transfer1, transfer2])
assert.strictEqual(errors.length, 2)
assert.deepStrictEqual(errors[0], { index: 0, result: CreateTransferError.linked_event_failed })
assert.deepStrictEqual(errors[1], { index: 1, result: CreateTransferError.exists_with_different_flags })
const accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.strictEqual(accounts[0].credits_posted, 150n)
assert.strictEqual(accounts[0].credits_pending, 0n)
assert.strictEqual(accounts[0].debits_posted, 0n)
assert.strictEqual(accounts[0].debits_pending, 0n)
assert.strictEqual(accounts[1].credits_posted, 0n)
assert.strictEqual(accounts[1].credits_pending, 0n)
assert.strictEqual(accounts[1].debits_posted, 150n)
assert.strictEqual(accounts[1].debits_pending, 0n)
})
test('cannot void an expired transfer', async (): Promise<void> => {
// Create a two-phase transfer:
const transfer: Transfer = {
id: 6n,
debit_account_id: accountB.id,
credit_account_id: accountA.id,
amount: 50n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 1,
ledger: 1,
code: 1,
flags: TransferFlags.pending,
timestamp: 0n, // this will be set correctly by the TigerBeetle server
}
const transferErrors = await client.createTransfers([transfer])
assert.deepStrictEqual(transferErrors, [])
var accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.strictEqual(accounts[0].credits_posted, 150n)
assert.strictEqual(accounts[0].credits_pending, 50n)
assert.strictEqual(accounts[0].debits_posted, 0n)
assert.strictEqual(accounts[0].debits_pending, 0n)
assert.strictEqual(accounts[1].credits_posted, 0n)
assert.strictEqual(accounts[1].credits_pending, 0n)
assert.strictEqual(accounts[1].debits_posted, 150n)
assert.strictEqual(accounts[1].debits_pending, 50n)
// We need to wait 1s for the server to expire the transfer, however the
// server can pulse the expiry operation anytime after the timeout,
// so adding an extra delay to avoid flaky tests.
// TODO: Use `await setTimeout(1000)` when upgrade to Node > 15.
const extra_wait_time = 250;
await new Promise(_ => setTimeout(_, (transfer.timeout * 1000) + extra_wait_time));
// Looking up the accounts again for the updated balance.
accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.strictEqual(accounts[0].credits_posted, 150n)
assert.strictEqual(accounts[0].credits_pending, 0n)
assert.strictEqual(accounts[0].debits_posted, 0n)
assert.strictEqual(accounts[0].debits_pending, 0n)
assert.strictEqual(accounts[1].credits_posted, 0n)
assert.strictEqual(accounts[1].credits_pending, 0n)
assert.strictEqual(accounts[1].debits_posted, 150n)
assert.strictEqual(accounts[1].debits_pending, 0n)
// send in the reject
const reject: Transfer = {
id: 7n,
debit_account_id: BigInt(0),
credit_account_id: BigInt(0),
amount: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 6n, // must match the id of the pending transfer
timeout: 0,
ledger: 1,
code: 1,
flags: TransferFlags.void_pending_transfer,
timestamp: 0n, // this will be set correctly by the TigerBeetle server
}
const errors = await client.createTransfers([reject])
assert.strictEqual(errors.length, 1)
assert.deepStrictEqual(errors[0], { index: 0, result: CreateTransferError.pending_transfer_expired })
})
test('can close accounts', async (): Promise<void> => {
const closing_transfer: Transfer = {
id: id(),
debit_account_id: accountB.id,
credit_account_id: accountA.id,
amount: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 0,
ledger: 1,
code: 1,
flags: TransferFlags.closing_debit | TransferFlags.closing_credit | TransferFlags.pending,
timestamp: 0n, // will be set correctly by the TigerBeetle server
}
let errors = await client.createTransfers([closing_transfer])
assert.strictEqual(errors.length, 0)
let accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.ok(accountA.flags != accounts[0].flags)
assert.ok((accounts[0].flags & AccountFlags.closed) != 0)
assert.ok(accountB.flags != accounts[1].flags)
assert.ok((accounts[1].flags & AccountFlags.closed) != 0)
const voiding_transfer: Transfer = {
id: id(),
debit_account_id: accountB.id,
credit_account_id: accountA.id,
amount: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
ledger: 1,
code: 1,
flags: TransferFlags.void_pending_transfer,
pending_id: closing_transfer.id,
timestamp: 0n, // will be set correctly by the TigerBeetle server
}
errors = await client.createTransfers([voiding_transfer])
assert.strictEqual(errors.length, 0)
accounts = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accounts.length, 2)
assert.strictEqual(accountA.flags, accounts[0].flags)
assert.ok((accounts[0].flags & AccountFlags.closed) == 0)
assert.strictEqual(accountB.flags, accounts[1].flags)
assert.ok((accounts[1].flags & AccountFlags.closed) == 0)
})
test('can get account transfers', async (): Promise<void> => {
const accountC: Account = {
id: 21n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 718,
flags: AccountFlags.history,
timestamp: 0n
}
const account_errors = await client.createAccounts([accountC])
assert.deepStrictEqual(account_errors, [])
var transfers_created : Transfer[] = [];
// Create transfers where the new account is either the debit or credit account:
for (var i=0; i<10;i++) {
transfers_created.push({
id: BigInt(i + 10000),
debit_account_id: i % 2 == 0 ? accountC.id : accountA.id,
credit_account_id: i % 2 == 0 ? accountB.id : accountC.id,
amount: 100n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 0,
ledger: 1,
code: 1,
flags: 0,
timestamp: 0n,
});
}
const transfers_created_result = await client.createTransfers(transfers_created)
assert.deepStrictEqual(transfers_created_result, [])
// Query all transfers for accountC:
var filter: AccountFilter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
var transfers = await client.getAccountTransfers(filter)
var account_balances = await client.getAccountBalances(filter)
assert.strictEqual(transfers.length, transfers_created.length)
assert.strictEqual(account_balances.length, transfers.length)
var timestamp = 0n;
var i = 0;
for (var transfer of transfers) {
assert.ok(timestamp < transfer.timestamp);
timestamp = transfer.timestamp;
assert.ok(account_balances[i].timestamp == transfer.timestamp);
i++;
}
// Query only the debit transfers for accountC, descending:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: AccountFilterFlags.debits | AccountFilterFlags.reversed,
}
transfers = await client.getAccountTransfers(filter)
account_balances = await client.getAccountBalances(filter)
assert.strictEqual(transfers.length, transfers_created.length / 2)
assert.strictEqual(account_balances.length, transfers.length)
timestamp = 1n << 64n;
i = 0;
for (var transfer of transfers) {
assert.ok(transfer.timestamp < timestamp);
timestamp = transfer.timestamp;
assert.ok(account_balances[i].timestamp == transfer.timestamp);
i++;
}
// Query only the credit transfers for accountC, descending:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: AccountFilterFlags.credits | AccountFilterFlags.reversed,
}
transfers = await client.getAccountTransfers(filter)
account_balances = await client.getAccountBalances(filter)
assert.strictEqual(transfers.length, transfers_created.length / 2)
assert.strictEqual(account_balances.length, transfers.length)
timestamp = 1n << 64n;
i = 0;
for (var transfer of transfers) {
assert.ok(transfer.timestamp < timestamp);
timestamp = transfer.timestamp;
assert.ok(account_balances[i].timestamp == transfer.timestamp);
i++;
}
// Query the first 5 transfers for accountC:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: 0n,
limit: transfers_created.length / 2,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
transfers = await client.getAccountTransfers(filter)
account_balances = await client.getAccountBalances(filter)
assert.strictEqual(transfers.length, transfers_created.length / 2)
assert.strictEqual(account_balances.length, transfers.length)
timestamp = 0n;
i = 0;
for (var transfer of transfers) {
assert.ok(timestamp < transfer.timestamp);
timestamp = transfer.timestamp;
assert.ok(account_balances[i].timestamp == transfer.timestamp);
i++;
}
// Query the next 5 transfers for accountC, with pagination:
filter = {
account_id: accountC.id,
timestamp_min: timestamp + 1n,
timestamp_max: 0n,
limit: transfers_created.length / 2,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
transfers = await client.getAccountTransfers(filter)
account_balances = await client.getAccountBalances(filter)
assert.strictEqual(transfers.length, transfers_created.length / 2)
assert.strictEqual(account_balances.length, transfers.length)
i = 0;
for (var transfer of transfers) {
assert.ok(timestamp < transfer.timestamp);
timestamp = transfer.timestamp;
assert.ok(account_balances[i].timestamp == transfer.timestamp);
i++;
}
// Query again, no more transfers should be found:
filter = {
account_id: accountC.id,
timestamp_min: timestamp + 1n,
timestamp_max: 0n,
limit: transfers_created.length / 2,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
transfers = await client.getAccountTransfers(filter)
account_balances = await client.getAccountBalances(filter)
assert.deepStrictEqual(transfers, [])
assert.strictEqual(account_balances.length, transfers.length)
// Query the first 5 transfers for accountC ORDER BY DESC:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: 0n,
limit: transfers_created.length / 2,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits | AccountFilterFlags.reversed,
}
transfers = await client.getAccountTransfers(filter)
account_balances = await client.getAccountBalances(filter)
assert.strictEqual(transfers.length, transfers_created.length / 2)
assert.strictEqual(account_balances.length, transfers.length)
timestamp = 1n << 64n;
i = 0;
for (var transfer of transfers) {
assert.ok(timestamp > transfer.timestamp);
timestamp = transfer.timestamp;
assert.ok(account_balances[i].timestamp == transfer.timestamp);
i++;
}
// Query the next 5 transfers for accountC, with pagination:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: timestamp - 1n,
limit: transfers_created.length / 2,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits | AccountFilterFlags.reversed,
}
transfers = await client.getAccountTransfers(filter)
account_balances = await client.getAccountBalances(filter)
assert.strictEqual(transfers.length, transfers_created.length / 2)
assert.strictEqual(account_balances.length, transfers.length)
i = 0;
for (var transfer of transfers) {
assert.ok(timestamp > transfer.timestamp);
timestamp = transfer.timestamp;
assert.ok(account_balances[i].timestamp == transfer.timestamp);
i++;
}
// Query again, no more transfers should be found:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: timestamp - 1n,
limit: transfers_created.length / 2,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits | AccountFilterFlags.reversed,
}
transfers = await client.getAccountTransfers(filter)
account_balances = await client.getAccountBalances(filter)
assert.deepStrictEqual(transfers, [])
assert.strictEqual(account_balances.length, transfers.length)
// Invalid account:
filter = {
account_id: 0n,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
assert.deepStrictEqual((await client.getAccountTransfers(filter)), [])
assert.deepStrictEqual((await client.getAccountBalances(filter)), [])
// Invalid timestamp min:
filter = {
account_id: accountC.id,
timestamp_min: (1n << 64n) - 1n, // ulong max value
timestamp_max: 0n,
limit: 8190,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
assert.deepStrictEqual((await client.getAccountTransfers(filter)), [])
assert.deepStrictEqual((await client.getAccountBalances(filter)), [])
// Invalid timestamp max:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: (1n << 64n) - 1n, // ulong max value
limit: 8190,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
assert.deepStrictEqual((await client.getAccountTransfers(filter)), [])
assert.deepStrictEqual((await client.getAccountBalances(filter)), [])
// Invalid timestamp range:
filter = {
account_id: accountC.id,
timestamp_min: (1n << 64n) - 2n, // ulong max - 1
timestamp_max: 1n,
limit: 8190,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
assert.deepStrictEqual((await client.getAccountTransfers(filter)), [])
assert.deepStrictEqual((await client.getAccountBalances(filter)), [])
// Zero limit:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 0,
flags: AccountFilterFlags.credits | AccountFilterFlags.debits,
}
assert.deepStrictEqual((await client.getAccountTransfers(filter)), [])
assert.deepStrictEqual((await client.getAccountBalances(filter)), [])
// Empty flags:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: AccountFilterFlags.none,
}
assert.deepStrictEqual((await client.getAccountTransfers(filter)), [])
assert.deepStrictEqual((await client.getAccountBalances(filter)), [])
// Invalid flags:
filter = {
account_id: accountC.id,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: 0xFFFF,
}
assert.deepStrictEqual((await client.getAccountTransfers(filter)), [])
assert.deepStrictEqual((await client.getAccountBalances(filter)), [])
})
test('can query accounts', async (): Promise<void> => {
{
var accounts : Account[] = [];
// Create transfers:
for (var i=0; i<10;i++) {
accounts.push({
id: id(),
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: i % 2 == 0 ? 1000n : 2000n,
user_data_64: i % 2 == 0 ? 100n : 200n,
user_data_32: i % 2 == 0 ? 10 : 20,
ledger: 1,
code: 999,
flags: AccountFlags.none,
reserved: 0,
timestamp: 0n,
})
}
const create_accounts_result = await client.createAccounts(accounts)
assert.deepStrictEqual(create_accounts_result, [])
}
{
// Querying accounts where:
// `user_data_128=1000 AND user_data_64=100 AND user_data_32=10
// AND code=999 AND ledger=1 ORDER BY timestamp ASC`.
var filter: QueryFilter = {
user_data_128: 1000n,
user_data_64: 100n,
user_data_32: 10,
ledger: 1,
code: 999,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.none,
}
var query: Account[] = await client.queryAccounts(filter)
assert.strictEqual(query.length, 5)
var timestamp = 0n;
for (var account of query) {
assert.ok(timestamp < account.timestamp);
timestamp = account.timestamp;
assert.strictEqual(account.user_data_128, filter.user_data_128);
assert.strictEqual(account.user_data_64, filter.user_data_64);
assert.strictEqual(account.user_data_32, filter.user_data_32);
assert.strictEqual(account.ledger, filter.ledger);
assert.strictEqual(account.code, filter.code);
}
}
{
// Querying accounts where:
// `user_data_128=2000 AND user_data_64=200 AND user_data_32=20
// AND code=999 AND ledger=1 ORDER BY timestamp DESC`.
var filter: QueryFilter = {
user_data_128: 2000n,
user_data_64: 200n,
user_data_32: 20,
ledger: 1,
code: 999,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.reversed,
}
var query: Account[] = await client.queryAccounts(filter)
assert.strictEqual(query.length, 5)
var timestamp = 1n << 64n;
for (var account of query) {
assert.ok(timestamp > account.timestamp);
timestamp = account.timestamp;
assert.strictEqual(account.user_data_128, filter.user_data_128);
assert.strictEqual(account.user_data_64, filter.user_data_64);
assert.strictEqual(account.user_data_32, filter.user_data_32);
assert.strictEqual(account.ledger, filter.ledger);
assert.strictEqual(account.code, filter.code);
}
}
{
// Querying accounts where:
// `code=999 ORDER BY timestamp ASC`
var filter: QueryFilter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 999,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.none,
}
var query: Account[] = await client.queryAccounts(filter)
assert.strictEqual(query.length, 10)
var timestamp = 0n;
for (var account of query) {
assert.ok(timestamp < account.timestamp);
timestamp = account.timestamp;
assert.strictEqual(account.code, filter.code);
}
}
{
// Querying accounts where:
// `code=999 ORDER BY timestamp DESC LIMIT 5`.
var filter: QueryFilter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 999,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 5,
flags: QueryFilterFlags.reversed,
}
// First 5 items:
var query: Account[] = await client.queryAccounts(filter)
assert.strictEqual(query.length, 5)
var timestamp = 1n << 64n;
for (var account of query) {
assert.ok(timestamp > account.timestamp);
timestamp = account.timestamp;
assert.strictEqual(account.code, filter.code);
}
// Next 5 items:
filter.timestamp_max = timestamp - 1n
query = await client.queryAccounts(filter)
assert.strictEqual(query.length, 5)
for (var account of query) {
assert.ok(timestamp > account.timestamp);
timestamp = account.timestamp;
assert.strictEqual(account.code, filter.code);
}
// No more results:
filter.timestamp_max = timestamp - 1n
query = await client.queryAccounts(filter)
assert.strictEqual(query.length, 0)
}
{
// Not found:
var filter: QueryFilter = {
user_data_128: 0n,
user_data_64: 200n,
user_data_32: 10,
ledger: 0,
code: 0,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.none,
}
var query: Account[] = await client.queryAccounts(filter)
assert.strictEqual(query.length, 0)
}
})
test('can query transfers', async (): Promise<void> => {
{
const account: Account = {
id: id(),
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 718,
flags: AccountFlags.none,
timestamp: 0n
}
const create_accounts_result = await client.createAccounts([account])
assert.deepStrictEqual(create_accounts_result, [])
var transfers_created : Transfer[] = [];
// Create transfers:
for (var i=0; i<10;i++) {
transfers_created.push({
id: id(),
debit_account_id: i % 2 == 0 ? account.id : accountA.id,
credit_account_id: i % 2 == 0 ? accountB.id : account.id,
amount: 100n,
user_data_128: i % 2 == 0 ? 1000n : 2000n,
user_data_64: i % 2 == 0 ? 100n : 200n,
user_data_32: i % 2 == 0 ? 10 : 20,
pending_id: 0n,
timeout: 0,
ledger: 1,
code: 999,
flags: 0,
timestamp: 0n,
})
}
const create_transfers_result = await client.createTransfers(transfers_created)
assert.deepStrictEqual(create_transfers_result, [])
}
{
// Querying transfers where:
// `user_data_128=1000 AND user_data_64=100 AND user_data_32=10
// AND code=999 AND ledger=1 ORDER BY timestamp ASC`.
var filter: QueryFilter = {
user_data_128: 1000n,
user_data_64: 100n,
user_data_32: 10,
ledger: 1,
code: 999,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.none,
}
var query: Transfer[] = await client.queryTransfers(filter)
assert.strictEqual(query.length, 5)
var timestamp = 0n;
for (var transfer of query) {
assert.ok(timestamp < transfer.timestamp);
timestamp = transfer.timestamp;
assert.strictEqual(transfer.user_data_128, filter.user_data_128);
assert.strictEqual(transfer.user_data_64, filter.user_data_64);
assert.strictEqual(transfer.user_data_32, filter.user_data_32);
assert.strictEqual(transfer.ledger, filter.ledger);
assert.strictEqual(transfer.code, filter.code);
}
}
{
// Querying transfers where:
// `user_data_128=2000 AND user_data_64=200 AND user_data_32=20
// AND code=999 AND ledger=1 ORDER BY timestamp DESC`.
var filter: QueryFilter = {
user_data_128: 2000n,
user_data_64: 200n,
user_data_32: 20,
ledger: 1,
code: 999,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.reversed,
}
var query: Transfer[] = await client.queryTransfers(filter)
assert.strictEqual(query.length, 5)
var timestamp = 1n << 64n;
for (var transfer of query) {
assert.ok(timestamp > transfer.timestamp);
timestamp = transfer.timestamp;
assert.strictEqual(transfer.user_data_128, filter.user_data_128);
assert.strictEqual(transfer.user_data_64, filter.user_data_64);
assert.strictEqual(transfer.user_data_32, filter.user_data_32);
assert.strictEqual(transfer.ledger, filter.ledger);
assert.strictEqual(transfer.code, filter.code);
}
}
{
// Querying transfers where:
// `code=999 ORDER BY timestamp ASC`
var filter: QueryFilter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 999,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.none,
}
var query: Transfer[] = await client.queryTransfers(filter)
assert.strictEqual(query.length, 10)
var timestamp = 0n;
for (var transfer of query) {
assert.ok(timestamp < transfer.timestamp);
timestamp = transfer.timestamp;
assert.strictEqual(transfer.code, filter.code);
}
}
{
// Querying transfers where:
// `code=999 ORDER BY timestamp DESC LIMIT 5`.
var filter: QueryFilter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 999,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 5,
flags: QueryFilterFlags.reversed,
}
// First 5 items:
var query: Transfer[] = await client.queryTransfers(filter)
assert.strictEqual(query.length, 5)
var timestamp = 1n << 64n;
for (var transfer of query) {
assert.ok(timestamp > transfer.timestamp);
timestamp = transfer.timestamp;
assert.strictEqual(transfer.code, filter.code);
}
// Next 5 items:
filter.timestamp_max = timestamp - 1n
query = await client.queryTransfers(filter)
assert.strictEqual(query.length, 5)
for (var transfer of query) {
assert.ok(timestamp > transfer.timestamp);
timestamp = transfer.timestamp;
assert.strictEqual(transfer.code, filter.code);
}
// No more results:
filter.timestamp_max = timestamp - 1n
query = await client.queryTransfers(filter)
assert.strictEqual(query.length, 0)
}
{
// Not found:
var filter: QueryFilter = {
user_data_128: 0n,
user_data_64: 200n,
user_data_32: 10,
ledger: 0,
code: 0,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.none,
}
var query: Transfer[] = await client.queryTransfers(filter)
assert.strictEqual(query.length, 0)
}
})
test('query with invalid filter', async (): Promise<void> => {
// Invalid timestamp min:
var filter: QueryFilter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 0,
timestamp_min: (1n << 64n) - 1n, // ulong max value
timestamp_max: 0n,
limit: 8190,
flags: QueryFilterFlags.none,
}
assert.deepStrictEqual((await client.queryAccounts(filter)), [])
assert.deepStrictEqual((await client.queryTransfers(filter)), [])
// Invalid timestamp max:
filter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 0,
timestamp_min: 0n,
timestamp_max: (1n << 64n) - 1n, // ulong max value,
limit: 8190,
flags: QueryFilterFlags.none,
}
assert.deepStrictEqual((await client.queryAccounts(filter)), [])
assert.deepStrictEqual((await client.queryTransfers(filter)), [])
// Invalid timestamp range:
filter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 0,
timestamp_min: (1n << 64n) - 2n, // ulong max - 1
timestamp_max: 1n,
limit: 8190,
flags: QueryFilterFlags.none,
}
assert.deepStrictEqual((await client.queryAccounts(filter)), [])
assert.deepStrictEqual((await client.queryTransfers(filter)), [])
// Zero limit:
filter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 0,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 0,
flags: QueryFilterFlags.none,
}
assert.deepStrictEqual((await client.queryAccounts(filter)), [])
assert.deepStrictEqual((await client.queryTransfers(filter)), [])
// Invalid flags:
filter = {
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
ledger: 0,
code: 0,
timestamp_min: 0n,
timestamp_max: 0n,
limit: 0,
flags: 0xFFFF,
}
assert.deepStrictEqual((await client.queryAccounts(filter)), [])
assert.deepStrictEqual((await client.queryTransfers(filter)), [])
})
test('can import accounts and transfers', async (): Promise<void> => {
const accountTmp: Account = {
id: id(),
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 718,
flags: 0,
timestamp: 0n // this will be set correctly by the TigerBeetle server
}
let accountsErrors = await client.createAccounts([accountTmp])
assert.deepStrictEqual(accountsErrors, [])
let accountLookup = await client.lookupAccounts([accountTmp.id])
assert.strictEqual(accountLookup.length, 1)
const timestampMax = accountLookup[0].timestamp
// Wait 10 ms so we can use the account's timestamp as the reference for past time
// after the last object inserted.
await new Promise(_ => setTimeout(_, 10));
const accountA: Account = {
id: id(),
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 718,
flags: AccountFlags.imported,
timestamp: timestampMax + 1n // user-defined timestamp
}
const accountB: Account = {
id: id(),
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 718,
flags: AccountFlags.imported,
timestamp: timestampMax + 2n // user-defined timestamp
}
accountsErrors = await client.createAccounts([accountA, accountB])
assert.deepStrictEqual(accountsErrors, [])
accountLookup = await client.lookupAccounts([accountA.id, accountB.id])
assert.strictEqual(accountLookup.length, 2)
assert.strictEqual(accountLookup[0].timestamp, accountA.timestamp)
assert.strictEqual(accountLookup[1].timestamp, accountB.timestamp)
const transfer: Transfer = {
id: id(),
debit_account_id: accountA.id,
credit_account_id: accountB.id,
amount: 100n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
pending_id: 0n,
timeout: 0,
ledger: 1,
code: 1,
flags: TransferFlags.imported,
timestamp: timestampMax + 3n, // user-defined timestamp.
}
const errors = await client.createTransfers([transfer])
assert.deepStrictEqual(errors, [])
const transfers = await client.lookupTransfers([transfer.id])
assert.strictEqual(transfers.length, 1)
assert.strictEqual(transfers[0].timestamp, timestampMax + 3n)
})
async function main () {
const start = new Date().getTime()
try {
for (let i = 0; i < tests.length; i++) {
await tests[i].fn().then(() => {
console.log(tests[i].name + ": PASSED")
}).catch(error => {
console.log(tests[i].name + ": FAILED")
throw error
})
}
const end = new Date().getTime()
console.log('Time taken (s):', (end - start)/1000)
} finally {
await client.destroy()
}
}
main().catch((error: AssertionError) => {
console.log('operator:', error.operator)
console.log('stack:', error.stack)
process.exit(-1);
})
|
0 | repos/tigerbeetle/src/clients/node | repos/tigerbeetle/src/clients/node/src/c.zig | pub usingnamespace @cImport({
@cInclude("node_api.h");
});
|
0 | repos/tigerbeetle/src/clients/node | repos/tigerbeetle/src/clients/node/src/translate.zig | const std = @import("std");
const assert = std.debug.assert;
const c = @import("c.zig");
pub fn register_function(
env: c.napi_env,
exports: c.napi_value,
comptime name: [:0]const u8,
function: *const fn (env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value,
) !void {
var napi_function: c.napi_value = undefined;
if (c.napi_create_function(env, null, 0, function, null, &napi_function) != c.napi_ok) {
return throw(env, "Failed to create function " ++ name ++ "().");
}
if (c.napi_set_named_property(
env,
exports,
@as([*c]const u8, @ptrCast(name)),
napi_function,
) != c.napi_ok) {
return throw(env, "Failed to add " ++ name ++ "() to exports.");
}
}
const TranslationError = error{ExceptionThrown};
pub fn throw(env: c.napi_env, comptime message: [:0]const u8) TranslationError {
const result = c.napi_throw_error(env, null, @as([*c]const u8, @ptrCast(message)));
switch (result) {
c.napi_ok, c.napi_pending_exception => {},
else => unreachable,
}
return TranslationError.ExceptionThrown;
}
pub fn capture_null(env: c.napi_env) !c.napi_value {
var result: c.napi_value = undefined;
if (c.napi_get_null(env, &result) != c.napi_ok) {
return throw(env, "Failed to capture the value of \"null\".");
}
return result;
}
pub fn extract_args(env: c.napi_env, info: c.napi_callback_info, comptime args: struct {
count: usize,
function: []const u8,
}) ![args.count]c.napi_value {
var argc = args.count;
var argv: [args.count]c.napi_value = undefined;
if (c.napi_get_cb_info(env, info, &argc, &argv, null, null) != c.napi_ok) {
return throw(
env,
std.fmt.comptimePrint("Failed to get args for {s}()\x00", .{args.function}),
);
}
if (argc != args.count) {
return throw(
env,
std.fmt.comptimePrint("Function {s}() requires exactly {} arguments.\x00", .{
args.function,
args.count,
}),
);
}
return argv;
}
pub fn create_external(env: c.napi_env, context: *anyopaque) !c.napi_value {
var result: c.napi_value = null;
if (c.napi_create_external(env, context, null, null, &result) != c.napi_ok) {
return throw(env, "Failed to create external for client context.");
}
return result;
}
pub fn value_external(
env: c.napi_env,
value: c.napi_value,
comptime error_message: [:0]const u8,
) !?*anyopaque {
var result: ?*anyopaque = undefined;
if (c.napi_get_value_external(env, value, &result) != c.napi_ok) {
return throw(env, error_message);
}
return result;
}
pub fn slice_from_object(
env: c.napi_env,
object: c.napi_value,
comptime key: [:0]const u8,
) ![]const u8 {
var property: c.napi_value = undefined;
if (c.napi_get_named_property(env, object, key, &property) != c.napi_ok) {
return throw(env, key ++ " must be defined");
}
return slice_from_value(env, property, key);
}
pub fn slice_from_value(
env: c.napi_env,
value: c.napi_value,
comptime key: [:0]const u8,
) ![]u8 {
var is_buffer: bool = undefined;
assert(c.napi_is_buffer(env, value, &is_buffer) == c.napi_ok);
if (!is_buffer) return throw(env, key ++ " must be a buffer");
var data: ?*anyopaque = null;
var data_length: usize = undefined;
assert(c.napi_get_buffer_info(env, value, &data, &data_length) == c.napi_ok);
if (data_length < 1) return throw(env, key ++ " must not be empty");
return @as([*]u8, @ptrCast(data.?))[0..data_length];
}
pub fn u128_from_object(env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8) !u128 {
var property: c.napi_value = undefined;
if (c.napi_get_named_property(env, object, key, &property) != c.napi_ok) {
return throw(env, key ++ " must be defined");
}
return u128_from_value(env, property, key);
}
pub fn u64_from_object(env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8) !u64 {
var property: c.napi_value = undefined;
if (c.napi_get_named_property(env, object, key, &property) != c.napi_ok) {
return throw(env, key ++ " must be defined");
}
return u64_from_value(env, property, key);
}
pub fn u32_from_object(env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8) !u32 {
var property: c.napi_value = undefined;
if (c.napi_get_named_property(env, object, key, &property) != c.napi_ok) {
return throw(env, key ++ " must be defined");
}
return u32_from_value(env, property, key);
}
pub fn u16_from_object(env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8) !u16 {
const result = try u32_from_object(env, object, key);
if (result > std.math.maxInt(u16)) {
return throw(env, key ++ " must be a u16.");
}
return @as(u16, @intCast(result));
}
pub fn u128_from_value(env: c.napi_env, value: c.napi_value, comptime name: [:0]const u8) !u128 {
// A BigInt's value (using ^ to mean exponent) is
// (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...).
// V8 says that the words are little endian. If we were on a big endian machine
// we would need to convert, but big endian is not supported by tigerbeetle.
var result: u128 = 0;
var sign_bit: c_int = undefined;
const words: *[2]u64 = @ptrCast(&result);
var word_count: usize = 2;
switch (c.napi_get_value_bigint_words(env, value, &sign_bit, &word_count, words)) {
c.napi_ok => {},
c.napi_bigint_expected => return throw(env, name ++ " must be a BigInt"),
else => unreachable,
}
if (sign_bit != 0) return throw(env, name ++ " must be positive");
if (word_count > 2) return throw(env, name ++ " must fit in 128 bits");
return result;
}
pub fn u64_from_value(env: c.napi_env, value: c.napi_value, comptime name: [:0]const u8) !u64 {
var result: u64 = undefined;
var lossless: bool = undefined;
switch (c.napi_get_value_bigint_uint64(env, value, &result, &lossless)) {
c.napi_ok => {},
c.napi_bigint_expected => return throw(env, name ++ " must be an unsigned 64-bit BigInt"),
else => unreachable,
}
if (!lossless) return throw(env, name ++ " conversion was lossy");
return result;
}
pub fn u32_from_value(env: c.napi_env, value: c.napi_value, comptime name: [:0]const u8) !u32 {
var result: u32 = undefined;
// TODO Check whether this will coerce signed numbers to a u32:
// In that case we need to use the appropriate napi method to do more type checking here.
// We want to make sure this is: unsigned, and an integer.
switch (c.napi_get_value_uint32(env, value, &result)) {
c.napi_ok => {},
c.napi_number_expected => return throw(env, name ++ " must be a number"),
else => unreachable,
}
return result;
}
pub fn u128_into_object(
env: c.napi_env,
object: c.napi_value,
comptime key: [:0]const u8,
value: u128,
comptime error_message: [:0]const u8,
) !void {
// A BigInt's value (using ^ to mean exponent) is
// (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...).
// V8 says that the words are little endian. If we were on a big endian machine
// we would need to convert, but big endian is not supported by tigerbeetle.
var bigint: c.napi_value = undefined;
if (c.napi_create_bigint_words(
env,
0,
2,
@as(*const [2]u64, @ptrCast(&value)),
&bigint,
) != c.napi_ok) {
return throw(env, error_message);
}
if (c.napi_set_named_property(
env,
object,
@ptrCast(key),
bigint,
) != c.napi_ok) {
return throw(env, error_message);
}
}
pub fn u64_into_object(
env: c.napi_env,
object: c.napi_value,
comptime key: [:0]const u8,
value: u64,
comptime error_message: [:0]const u8,
) !void {
var result: c.napi_value = undefined;
if (c.napi_create_bigint_uint64(env, value, &result) != c.napi_ok) {
return throw(env, error_message);
}
if (c.napi_set_named_property(
env,
object,
@ptrCast(key),
result,
) != c.napi_ok) {
return throw(env, error_message);
}
}
pub fn u32_into_object(
env: c.napi_env,
object: c.napi_value,
comptime key: [:0]const u8,
value: u32,
comptime error_message: [:0]const u8,
) !void {
var result: c.napi_value = undefined;
if (c.napi_create_uint32(env, value, &result) != c.napi_ok) {
return throw(env, error_message);
}
if (c.napi_set_named_property(env, object, @ptrCast(key), result) != c.napi_ok) {
return throw(env, error_message);
}
}
pub fn u16_into_object(
env: c.napi_env,
object: c.napi_value,
comptime key: [:0]const u8,
value: u16,
comptime error_message: [:0]const u8,
) !void {
try u32_into_object(env, object, key, value, error_message);
}
pub fn create_object(env: c.napi_env, comptime error_message: [:0]const u8) !c.napi_value {
var result: c.napi_value = undefined;
if (c.napi_create_object(env, &result) != c.napi_ok) {
return throw(env, error_message);
}
return result;
}
pub fn create_array(
env: c.napi_env,
length: u32,
comptime error_message: [:0]const u8,
) !c.napi_value {
var result: c.napi_value = undefined;
if (c.napi_create_array_with_length(env, length, &result) != c.napi_ok) {
return throw(env, error_message);
}
return result;
}
pub fn set_array_element(
env: c.napi_env,
array: c.napi_value,
index: u32,
value: c.napi_value,
comptime error_message: [:0]const u8,
) !void {
if (c.napi_set_element(env, array, index, value) != c.napi_ok) {
return throw(env, error_message);
}
}
pub fn array_element(env: c.napi_env, array: c.napi_value, index: u32) !c.napi_value {
var element: c.napi_value = undefined;
if (c.napi_get_element(env, array, index, &element) != c.napi_ok) {
return throw(env, "Failed to get array element.");
}
return element;
}
pub fn array_length(env: c.napi_env, array: c.napi_value) !u32 {
var is_array: bool = undefined;
assert(c.napi_is_array(env, array, &is_array) == c.napi_ok);
if (!is_array) return throw(env, "Batch must be an Array.");
var length: u32 = undefined;
assert(c.napi_get_array_length(env, array, &length) == c.napi_ok);
return length;
}
pub fn delete_reference(env: c.napi_env, reference: c.napi_ref) !void {
if (c.napi_delete_reference(env, reference) != c.napi_ok) {
return throw(env, "Failed to delete callback reference.");
}
}
pub fn call_function(
env: c.napi_env,
this: c.napi_value,
callback: c.napi_value,
args: []c.napi_value,
) !c.napi_value {
var result: c.napi_value = undefined;
switch (c.napi_call_function(env, this, callback, args.len, args.ptr, &result)) {
c.napi_ok => {},
// the user's callback may throw a JS exception or call other functions that do so. We
// therefore don't throw another error.
c.napi_pending_exception => {},
else => return throw(env, "Failed to invoke results callback."),
}
return result;
}
pub fn reference_value(
env: c.napi_env,
callback_reference: c.napi_ref,
comptime error_message: [:0]const u8,
) !c.napi_value {
var result: c.napi_value = undefined;
if (c.napi_get_reference_value(env, callback_reference, &result) != c.napi_ok) {
return throw(env, error_message);
}
return result;
}
|
0 | repos/tigerbeetle/src/clients/node | repos/tigerbeetle/src/clients/node/src/bindings.ts | ///////////////////////////////////////////////////////
// This file was auto-generated by node_bindings.zig //
// Do not manually modify. //
///////////////////////////////////////////////////////
/**
* See [AccountFlags](https://docs.tigerbeetle.com/reference/account#flags)
*/
export enum AccountFlags {
none = 0,
/**
* See [linked](https://docs.tigerbeetle.com/reference/account#flagslinked)
*/
linked = (1 << 0),
/**
* See [debits_must_not_exceed_credits](https://docs.tigerbeetle.com/reference/account#flagsdebits_must_not_exceed_credits)
*/
debits_must_not_exceed_credits = (1 << 1),
/**
* See [credits_must_not_exceed_debits](https://docs.tigerbeetle.com/reference/account#flagscredits_must_not_exceed_debits)
*/
credits_must_not_exceed_debits = (1 << 2),
/**
* See [history](https://docs.tigerbeetle.com/reference/account#flagshistory)
*/
history = (1 << 3),
/**
* See [imported](https://docs.tigerbeetle.com/reference/account#flagsimported)
*/
imported = (1 << 4),
/**
* See [closed](https://docs.tigerbeetle.com/reference/account#flagsclosed)
*/
closed = (1 << 5),
}
/**
* See [TransferFlags](https://docs.tigerbeetle.com/reference/transfer#flags)
*/
export enum TransferFlags {
none = 0,
/**
* See [linked](https://docs.tigerbeetle.com/reference/transfer#flagslinked)
*/
linked = (1 << 0),
/**
* See [pending](https://docs.tigerbeetle.com/reference/transfer#flagspending)
*/
pending = (1 << 1),
/**
* See [post_pending_transfer](https://docs.tigerbeetle.com/reference/transfer#flagspost_pending_transfer)
*/
post_pending_transfer = (1 << 2),
/**
* See [void_pending_transfer](https://docs.tigerbeetle.com/reference/transfer#flagsvoid_pending_transfer)
*/
void_pending_transfer = (1 << 3),
/**
* See [balancing_debit](https://docs.tigerbeetle.com/reference/transfer#flagsbalancing_debit)
*/
balancing_debit = (1 << 4),
/**
* See [balancing_credit](https://docs.tigerbeetle.com/reference/transfer#flagsbalancing_credit)
*/
balancing_credit = (1 << 5),
/**
* See [closing_debit](https://docs.tigerbeetle.com/reference/transfer#flagsclosing_debit)
*/
closing_debit = (1 << 6),
/**
* See [closing_credit](https://docs.tigerbeetle.com/reference/transfer#flagsclosing_credit)
*/
closing_credit = (1 << 7),
/**
* See [imported](https://docs.tigerbeetle.com/reference/transfer#flagsimported)
*/
imported = (1 << 8),
}
/**
* See [AccountFilterFlags](https://docs.tigerbeetle.com/reference/account-filter#flags)
*/
export enum AccountFilterFlags {
none = 0,
/**
* See [debits](https://docs.tigerbeetle.com/reference/account-filter#flagsdebits)
*/
debits = (1 << 0),
/**
* See [credits](https://docs.tigerbeetle.com/reference/account-filter#flagscredits)
*/
credits = (1 << 1),
/**
* See [reversed](https://docs.tigerbeetle.com/reference/account-filter#flagsreversed)
*/
reversed = (1 << 2),
}
/**
* See [QueryFilterFlags](https://docs.tigerbeetle.com/reference/query-filter#flags)
*/
export enum QueryFilterFlags {
none = 0,
/**
* See [reversed](https://docs.tigerbeetle.com/reference/query-filter#flagsreversed)
*/
reversed = (1 << 0),
}
/**
* See [Account](https://docs.tigerbeetle.com/reference/account/#)
*/
export type Account = {
/**
* See [id](https://docs.tigerbeetle.com/reference/account/#id)
*/
id: bigint
/**
* See [debits_pending](https://docs.tigerbeetle.com/reference/account/#debits_pending)
*/
debits_pending: bigint
/**
* See [debits_posted](https://docs.tigerbeetle.com/reference/account/#debits_posted)
*/
debits_posted: bigint
/**
* See [credits_pending](https://docs.tigerbeetle.com/reference/account/#credits_pending)
*/
credits_pending: bigint
/**
* See [credits_posted](https://docs.tigerbeetle.com/reference/account/#credits_posted)
*/
credits_posted: bigint
/**
* See [user_data_128](https://docs.tigerbeetle.com/reference/account/#user_data_128)
*/
user_data_128: bigint
/**
* See [user_data_64](https://docs.tigerbeetle.com/reference/account/#user_data_64)
*/
user_data_64: bigint
/**
* See [user_data_32](https://docs.tigerbeetle.com/reference/account/#user_data_32)
*/
user_data_32: number
/**
* See [reserved](https://docs.tigerbeetle.com/reference/account/#reserved)
*/
reserved: number
/**
* See [ledger](https://docs.tigerbeetle.com/reference/account/#ledger)
*/
ledger: number
/**
* See [code](https://docs.tigerbeetle.com/reference/account/#code)
*/
code: number
/**
* See [flags](https://docs.tigerbeetle.com/reference/account/#flags)
*/
flags: number
/**
* See [timestamp](https://docs.tigerbeetle.com/reference/account/#timestamp)
*/
timestamp: bigint
}
/**
* See [Transfer](https://docs.tigerbeetle.com/reference/transfer/#)
*/
export type Transfer = {
/**
* See [id](https://docs.tigerbeetle.com/reference/transfer/#id)
*/
id: bigint
/**
* See [debit_account_id](https://docs.tigerbeetle.com/reference/transfer/#debit_account_id)
*/
debit_account_id: bigint
/**
* See [credit_account_id](https://docs.tigerbeetle.com/reference/transfer/#credit_account_id)
*/
credit_account_id: bigint
/**
* See [amount](https://docs.tigerbeetle.com/reference/transfer/#amount)
*/
amount: bigint
/**
* See [pending_id](https://docs.tigerbeetle.com/reference/transfer/#pending_id)
*/
pending_id: bigint
/**
* See [user_data_128](https://docs.tigerbeetle.com/reference/transfer/#user_data_128)
*/
user_data_128: bigint
/**
* See [user_data_64](https://docs.tigerbeetle.com/reference/transfer/#user_data_64)
*/
user_data_64: bigint
/**
* See [user_data_32](https://docs.tigerbeetle.com/reference/transfer/#user_data_32)
*/
user_data_32: number
/**
* See [timeout](https://docs.tigerbeetle.com/reference/transfer/#timeout)
*/
timeout: number
/**
* See [ledger](https://docs.tigerbeetle.com/reference/transfer/#ledger)
*/
ledger: number
/**
* See [code](https://docs.tigerbeetle.com/reference/transfer/#code)
*/
code: number
/**
* See [flags](https://docs.tigerbeetle.com/reference/transfer/#flags)
*/
flags: number
/**
* See [timestamp](https://docs.tigerbeetle.com/reference/transfer/#timestamp)
*/
timestamp: bigint
}
/**
* See [CreateAccountError](https://docs.tigerbeetle.com/reference/requests/create_accounts#)
*/
export enum CreateAccountError {
/**
* See [ok](https://docs.tigerbeetle.com/reference/requests/create_accounts#ok)
*/
ok = 0,
/**
* See [linked_event_failed](https://docs.tigerbeetle.com/reference/requests/create_accounts#linked_event_failed)
*/
linked_event_failed = 1,
/**
* See [linked_event_chain_open](https://docs.tigerbeetle.com/reference/requests/create_accounts#linked_event_chain_open)
*/
linked_event_chain_open = 2,
/**
* See [imported_event_expected](https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_expected)
*/
imported_event_expected = 22,
/**
* See [imported_event_not_expected](https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_not_expected)
*/
imported_event_not_expected = 23,
/**
* See [timestamp_must_be_zero](https://docs.tigerbeetle.com/reference/requests/create_accounts#timestamp_must_be_zero)
*/
timestamp_must_be_zero = 3,
/**
* See [imported_event_timestamp_out_of_range](https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_timestamp_out_of_range)
*/
imported_event_timestamp_out_of_range = 24,
/**
* See [imported_event_timestamp_must_not_advance](https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_timestamp_must_not_advance)
*/
imported_event_timestamp_must_not_advance = 25,
/**
* See [reserved_field](https://docs.tigerbeetle.com/reference/requests/create_accounts#reserved_field)
*/
reserved_field = 4,
/**
* See [reserved_flag](https://docs.tigerbeetle.com/reference/requests/create_accounts#reserved_flag)
*/
reserved_flag = 5,
/**
* See [id_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_accounts#id_must_not_be_zero)
*/
id_must_not_be_zero = 6,
/**
* See [id_must_not_be_int_max](https://docs.tigerbeetle.com/reference/requests/create_accounts#id_must_not_be_int_max)
*/
id_must_not_be_int_max = 7,
/**
* See [flags_are_mutually_exclusive](https://docs.tigerbeetle.com/reference/requests/create_accounts#flags_are_mutually_exclusive)
*/
flags_are_mutually_exclusive = 8,
/**
* See [debits_pending_must_be_zero](https://docs.tigerbeetle.com/reference/requests/create_accounts#debits_pending_must_be_zero)
*/
debits_pending_must_be_zero = 9,
/**
* See [debits_posted_must_be_zero](https://docs.tigerbeetle.com/reference/requests/create_accounts#debits_posted_must_be_zero)
*/
debits_posted_must_be_zero = 10,
/**
* See [credits_pending_must_be_zero](https://docs.tigerbeetle.com/reference/requests/create_accounts#credits_pending_must_be_zero)
*/
credits_pending_must_be_zero = 11,
/**
* See [credits_posted_must_be_zero](https://docs.tigerbeetle.com/reference/requests/create_accounts#credits_posted_must_be_zero)
*/
credits_posted_must_be_zero = 12,
/**
* See [ledger_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_accounts#ledger_must_not_be_zero)
*/
ledger_must_not_be_zero = 13,
/**
* See [code_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_accounts#code_must_not_be_zero)
*/
code_must_not_be_zero = 14,
/**
* See [exists_with_different_flags](https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_flags)
*/
exists_with_different_flags = 15,
/**
* See [exists_with_different_user_data_128](https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_user_data_128)
*/
exists_with_different_user_data_128 = 16,
/**
* See [exists_with_different_user_data_64](https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_user_data_64)
*/
exists_with_different_user_data_64 = 17,
/**
* See [exists_with_different_user_data_32](https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_user_data_32)
*/
exists_with_different_user_data_32 = 18,
/**
* See [exists_with_different_ledger](https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_ledger)
*/
exists_with_different_ledger = 19,
/**
* See [exists_with_different_code](https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_code)
*/
exists_with_different_code = 20,
/**
* See [exists](https://docs.tigerbeetle.com/reference/requests/create_accounts#exists)
*/
exists = 21,
/**
* See [imported_event_timestamp_must_not_regress](https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_timestamp_must_not_regress)
*/
imported_event_timestamp_must_not_regress = 26,
}
/**
* See [CreateTransferError](https://docs.tigerbeetle.com/reference/requests/create_transfers#)
*/
export enum CreateTransferError {
/**
* See [ok](https://docs.tigerbeetle.com/reference/requests/create_transfers#ok)
*/
ok = 0,
/**
* See [linked_event_failed](https://docs.tigerbeetle.com/reference/requests/create_transfers#linked_event_failed)
*/
linked_event_failed = 1,
/**
* See [linked_event_chain_open](https://docs.tigerbeetle.com/reference/requests/create_transfers#linked_event_chain_open)
*/
linked_event_chain_open = 2,
/**
* See [timestamp_must_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#timestamp_must_be_zero)
*/
timestamp_must_be_zero = 3,
/**
* See [reserved_flag](https://docs.tigerbeetle.com/reference/requests/create_transfers#reserved_flag)
*/
reserved_flag = 4,
/**
* See [id_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#id_must_not_be_zero)
*/
id_must_not_be_zero = 5,
/**
* See [id_must_not_be_int_max](https://docs.tigerbeetle.com/reference/requests/create_transfers#id_must_not_be_int_max)
*/
id_must_not_be_int_max = 6,
/**
* See [flags_are_mutually_exclusive](https://docs.tigerbeetle.com/reference/requests/create_transfers#flags_are_mutually_exclusive)
*/
flags_are_mutually_exclusive = 7,
/**
* See [debit_account_id_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#debit_account_id_must_not_be_zero)
*/
debit_account_id_must_not_be_zero = 8,
/**
* See [debit_account_id_must_not_be_int_max](https://docs.tigerbeetle.com/reference/requests/create_transfers#debit_account_id_must_not_be_int_max)
*/
debit_account_id_must_not_be_int_max = 9,
/**
* See [credit_account_id_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#credit_account_id_must_not_be_zero)
*/
credit_account_id_must_not_be_zero = 10,
/**
* See [credit_account_id_must_not_be_int_max](https://docs.tigerbeetle.com/reference/requests/create_transfers#credit_account_id_must_not_be_int_max)
*/
credit_account_id_must_not_be_int_max = 11,
/**
* See [accounts_must_be_different](https://docs.tigerbeetle.com/reference/requests/create_transfers#accounts_must_be_different)
*/
accounts_must_be_different = 12,
/**
* See [pending_id_must_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_id_must_be_zero)
*/
pending_id_must_be_zero = 13,
/**
* See [pending_id_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_id_must_not_be_zero)
*/
pending_id_must_not_be_zero = 14,
/**
* See [pending_id_must_not_be_int_max](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_id_must_not_be_int_max)
*/
pending_id_must_not_be_int_max = 15,
/**
* See [pending_id_must_be_different](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_id_must_be_different)
*/
pending_id_must_be_different = 16,
/**
* See [timeout_reserved_for_pending_transfer](https://docs.tigerbeetle.com/reference/requests/create_transfers#timeout_reserved_for_pending_transfer)
*/
timeout_reserved_for_pending_transfer = 17,
/**
* See [amount_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#amount_must_not_be_zero)
*/
amount_must_not_be_zero = 18,
/**
* See [ledger_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#ledger_must_not_be_zero)
*/
ledger_must_not_be_zero = 19,
/**
* See [code_must_not_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#code_must_not_be_zero)
*/
code_must_not_be_zero = 20,
/**
* See [debit_account_not_found](https://docs.tigerbeetle.com/reference/requests/create_transfers#debit_account_not_found)
*/
debit_account_not_found = 21,
/**
* See [credit_account_not_found](https://docs.tigerbeetle.com/reference/requests/create_transfers#credit_account_not_found)
*/
credit_account_not_found = 22,
/**
* See [accounts_must_have_the_same_ledger](https://docs.tigerbeetle.com/reference/requests/create_transfers#accounts_must_have_the_same_ledger)
*/
accounts_must_have_the_same_ledger = 23,
/**
* See [transfer_must_have_the_same_ledger_as_accounts](https://docs.tigerbeetle.com/reference/requests/create_transfers#transfer_must_have_the_same_ledger_as_accounts)
*/
transfer_must_have_the_same_ledger_as_accounts = 24,
/**
* See [pending_transfer_not_found](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_not_found)
*/
pending_transfer_not_found = 25,
/**
* See [pending_transfer_not_pending](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_not_pending)
*/
pending_transfer_not_pending = 26,
/**
* See [pending_transfer_has_different_debit_account_id](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_debit_account_id)
*/
pending_transfer_has_different_debit_account_id = 27,
/**
* See [pending_transfer_has_different_credit_account_id](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_credit_account_id)
*/
pending_transfer_has_different_credit_account_id = 28,
/**
* See [pending_transfer_has_different_ledger](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_ledger)
*/
pending_transfer_has_different_ledger = 29,
/**
* See [pending_transfer_has_different_code](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_code)
*/
pending_transfer_has_different_code = 30,
/**
* See [exceeds_pending_transfer_amount](https://docs.tigerbeetle.com/reference/requests/create_transfers#exceeds_pending_transfer_amount)
*/
exceeds_pending_transfer_amount = 31,
/**
* See [pending_transfer_has_different_amount](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_amount)
*/
pending_transfer_has_different_amount = 32,
/**
* See [pending_transfer_already_posted](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_already_posted)
*/
pending_transfer_already_posted = 33,
/**
* See [pending_transfer_already_voided](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_already_voided)
*/
pending_transfer_already_voided = 34,
/**
* See [pending_transfer_expired](https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_expired)
*/
pending_transfer_expired = 35,
/**
* See [exists_with_different_flags](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_flags)
*/
exists_with_different_flags = 36,
/**
* See [exists_with_different_debit_account_id](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_debit_account_id)
*/
exists_with_different_debit_account_id = 37,
/**
* See [exists_with_different_credit_account_id](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_credit_account_id)
*/
exists_with_different_credit_account_id = 38,
/**
* See [exists_with_different_amount](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_amount)
*/
exists_with_different_amount = 39,
/**
* See [exists_with_different_pending_id](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_pending_id)
*/
exists_with_different_pending_id = 40,
/**
* See [exists_with_different_user_data_128](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_user_data_128)
*/
exists_with_different_user_data_128 = 41,
/**
* See [exists_with_different_user_data_64](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_user_data_64)
*/
exists_with_different_user_data_64 = 42,
/**
* See [exists_with_different_user_data_32](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_user_data_32)
*/
exists_with_different_user_data_32 = 43,
/**
* See [exists_with_different_timeout](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_timeout)
*/
exists_with_different_timeout = 44,
/**
* See [exists_with_different_code](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_code)
*/
exists_with_different_code = 45,
/**
* See [exists](https://docs.tigerbeetle.com/reference/requests/create_transfers#exists)
*/
exists = 46,
/**
* See [overflows_debits_pending](https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_debits_pending)
*/
overflows_debits_pending = 47,
/**
* See [overflows_credits_pending](https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_credits_pending)
*/
overflows_credits_pending = 48,
/**
* See [overflows_debits_posted](https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_debits_posted)
*/
overflows_debits_posted = 49,
/**
* See [overflows_credits_posted](https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_credits_posted)
*/
overflows_credits_posted = 50,
/**
* See [overflows_debits](https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_debits)
*/
overflows_debits = 51,
/**
* See [overflows_credits](https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_credits)
*/
overflows_credits = 52,
/**
* See [overflows_timeout](https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_timeout)
*/
overflows_timeout = 53,
/**
* See [exceeds_credits](https://docs.tigerbeetle.com/reference/requests/create_transfers#exceeds_credits)
*/
exceeds_credits = 54,
/**
* See [exceeds_debits](https://docs.tigerbeetle.com/reference/requests/create_transfers#exceeds_debits)
*/
exceeds_debits = 55,
/**
* See [imported_event_expected](https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_expected)
*/
imported_event_expected = 56,
/**
* See [imported_event_not_expected](https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_not_expected)
*/
imported_event_not_expected = 57,
/**
* See [imported_event_timestamp_out_of_range](https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_out_of_range)
*/
imported_event_timestamp_out_of_range = 58,
/**
* See [imported_event_timestamp_must_not_advance](https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_must_not_advance)
*/
imported_event_timestamp_must_not_advance = 59,
/**
* See [imported_event_timestamp_must_not_regress](https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_must_not_regress)
*/
imported_event_timestamp_must_not_regress = 60,
/**
* See [imported_event_timestamp_must_postdate_debit_account](https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_must_postdate_debit_account)
*/
imported_event_timestamp_must_postdate_debit_account = 61,
/**
* See [imported_event_timestamp_must_postdate_credit_account](https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_must_postdate_credit_account)
*/
imported_event_timestamp_must_postdate_credit_account = 62,
/**
* See [imported_event_timeout_must_be_zero](https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timeout_must_be_zero)
*/
imported_event_timeout_must_be_zero = 63,
/**
* See [closing_transfer_must_be_pending](https://docs.tigerbeetle.com/reference/requests/create_transfers#closing_transfer_must_be_pending)
*/
closing_transfer_must_be_pending = 64,
/**
* See [debit_account_already_closed](https://docs.tigerbeetle.com/reference/requests/create_transfers#debit_account_already_closed)
*/
debit_account_already_closed = 65,
/**
* See [credit_account_already_closed](https://docs.tigerbeetle.com/reference/requests/create_transfers#credit_account_already_closed)
*/
credit_account_already_closed = 66,
}
export type CreateAccountsError = {
index: number
result: CreateAccountError
}
export type CreateTransfersError = {
index: number
result: CreateTransferError
}
/**
* See [AccountFilter](https://docs.tigerbeetle.com/reference/account-filter#)
*/
export type AccountFilter = {
/**
* See [account_id](https://docs.tigerbeetle.com/reference/account-filter#account_id)
*/
account_id: bigint
/**
* See [timestamp_min](https://docs.tigerbeetle.com/reference/account-filter#timestamp_min)
*/
timestamp_min: bigint
/**
* See [timestamp_max](https://docs.tigerbeetle.com/reference/account-filter#timestamp_max)
*/
timestamp_max: bigint
/**
* See [limit](https://docs.tigerbeetle.com/reference/account-filter#limit)
*/
limit: number
/**
* See [flags](https://docs.tigerbeetle.com/reference/account-filter#flags)
*/
flags: number
}
/**
* See [QueryFilter](https://docs.tigerbeetle.com/reference/query-filter#)
*/
export type QueryFilter = {
/**
* See [user_data_128](https://docs.tigerbeetle.com/reference/query-filter#user_data_128)
*/
user_data_128: bigint
/**
* See [user_data_64](https://docs.tigerbeetle.com/reference/query-filter#user_data_64)
*/
user_data_64: bigint
/**
* See [user_data_32](https://docs.tigerbeetle.com/reference/query-filter#user_data_32)
*/
user_data_32: number
/**
* See [ledger](https://docs.tigerbeetle.com/reference/query-filter#ledger)
*/
ledger: number
/**
* See [code](https://docs.tigerbeetle.com/reference/query-filter#code)
*/
code: number
/**
* See [timestamp_min](https://docs.tigerbeetle.com/reference/query-filter#timestamp_min)
*/
timestamp_min: bigint
/**
* See [timestamp_max](https://docs.tigerbeetle.com/reference/query-filter#timestamp_max)
*/
timestamp_max: bigint
/**
* See [limit](https://docs.tigerbeetle.com/reference/query-filter#limit)
*/
limit: number
/**
* See [flags](https://docs.tigerbeetle.com/reference/query-filter#flags)
*/
flags: number
}
/**
* See [AccountBalance](https://docs.tigerbeetle.com/reference/account-balances#)
*/
export type AccountBalance = {
/**
* See [debits_pending](https://docs.tigerbeetle.com/reference/account-balances#debits_pending)
*/
debits_pending: bigint
/**
* See [debits_posted](https://docs.tigerbeetle.com/reference/account-balances#debits_posted)
*/
debits_posted: bigint
/**
* See [credits_pending](https://docs.tigerbeetle.com/reference/account-balances#credits_pending)
*/
credits_pending: bigint
/**
* See [credits_posted](https://docs.tigerbeetle.com/reference/account-balances#credits_posted)
*/
credits_posted: bigint
/**
* See [timestamp](https://docs.tigerbeetle.com/reference/account-balances#timestamp)
*/
timestamp: bigint
}
export enum Operation {
pulse = 128,
create_accounts = 129,
create_transfers = 130,
lookup_accounts = 131,
lookup_transfers = 132,
get_account_transfers = 133,
get_account_balances = 134,
query_accounts = 135,
query_transfers = 136,
}
|
0 | repos/tigerbeetle/src/clients/node | repos/tigerbeetle/src/clients/node/src/index.ts | export * from './bindings'
import {
Account,
Transfer,
CreateAccountsError,
CreateTransfersError,
Operation,
AccountFilter,
AccountBalance,
QueryFilter,
} from './bindings'
import { randomFillSync } from 'node:crypto'
const binding: Binding = (() => {
const { arch, platform } = process
const archMap = {
"arm64": "aarch64",
"x64": "x86_64"
}
const platformMap = {
"linux": "linux",
"darwin": "macos",
"win32" : "windows",
}
if (! (arch in archMap)) {
throw new Error(`Unsupported arch: ${arch}`)
}
if (! (platform in platformMap)) {
throw new Error(`Unsupported platform: ${platform}`)
}
let extra = ''
/**
* We need to detect during runtime which libc we're running on to load the correct NAPI.
* binary.
*
* Rationale: The /proc/self/map_files/ subdirectory contains entries corresponding to
* memory-mapped files loaded by Node.
* https://man7.org/linux/man-pages/man5/proc.5.html: We detect a musl-based distro by
* checking if any library contains the name "musl".
*
* Prior art: https://github.com/xerial/sqlite-jdbc/issues/623
*/
const fs = require('fs')
const path = require('path')
if (platform === 'linux') {
extra = '-gnu'
for (const file of fs.readdirSync("/proc/self/map_files/")) {
const realPath = fs.readlinkSync(path.join("/proc/self/map_files/", file))
if (realPath.includes('musl')) {
extra = '-musl'
break
}
}
}
const filename = `./bin/${archMap[arch]}-${platformMap[platform]}${extra}/client.node`
return require(filename)
})()
export type Context = object // tb_client
export type AccountID = bigint // u128
export type TransferID = bigint // u128
export type Event = Account | Transfer | AccountID | TransferID | AccountFilter | QueryFilter
export type Result = CreateAccountsError | CreateTransfersError | Account | Transfer | AccountBalance
export type ResultCallback = (error: Error | null, results: Result[] | null) => void
export const amount_max: bigint = (2n ** 128n) - 1n
interface BindingInitArgs {
cluster_id: bigint, // u128
replica_addresses: Buffer,
}
interface Binding {
init: (args: BindingInitArgs) => Context
submit: (context: Context, operation: Operation, batch: Event[], callback: ResultCallback) => void
deinit: (context: Context) => void,
}
export interface ClientInitArgs {
cluster_id: bigint, // u128
replica_addresses: Array<string | number>,
}
export interface Client {
createAccounts: (batch: Account[]) => Promise<CreateAccountsError[]>
createTransfers: (batch: Transfer[]) => Promise<CreateTransfersError[]>
lookupAccounts: (batch: AccountID[]) => Promise<Account[]>
lookupTransfers: (batch: TransferID[]) => Promise<Transfer[]>
getAccountTransfers: (filter: AccountFilter) => Promise<Transfer[]>
getAccountBalances: (filter: AccountFilter) => Promise<AccountBalance[]>
queryAccounts: (filter: QueryFilter) => Promise<Account[]>
queryTransfers: (filter: QueryFilter) => Promise<Transfer[]>
destroy: () => void
}
export function createClient (args: ClientInitArgs): Client {
// Context becomes null when `destroy` is called. After that point, further `request` Promises
// throw a shutdown Error. This prevents tb_client calls from happening after tb_client_deinit().
let context: Context | null = binding.init({
cluster_id: args.cluster_id,
replica_addresses: Buffer.from(args.replica_addresses.join(',')),
})
const destroy = () => {
if (context) binding.deinit(context)
context = null;
}
const request = <T extends Result>(operation: Operation, batch: Event[]): Promise<T[]> => {
return new Promise((resolve, reject) => {
try {
if (!context) throw new Error('Client was shutdown.');
binding.submit(context, operation, batch, (error, result) => {
if (error) {
reject(error)
} else if (result) {
resolve(result as T[])
} else {
throw new Error("UB: Binding invoked callback without error or result")
}
})
} catch (err) {
reject(err)
}
})
}
return {
createAccounts(batch) { return request(Operation.create_accounts, batch) },
createTransfers(batch) { return request(Operation.create_transfers, batch) },
lookupAccounts(batch) { return request(Operation.lookup_accounts, batch) },
lookupTransfers(batch) { return request(Operation.lookup_transfers, batch) },
getAccountTransfers(filter) { return request(Operation.get_account_transfers, [filter]) },
getAccountBalances(filter) { return request(Operation.get_account_balances, [filter]) },
queryAccounts(filter) { return request(Operation.query_accounts, [filter]) },
queryTransfers(filter) { return request(Operation.query_transfers, [filter]) },
destroy,
}
}
let idLastTimestamp = 0;
let idLastBuffer = new DataView(new ArrayBuffer(16));
/**
* Generates a Universally Unique and Sortable Identifier as a u128 bigint.
*
* @remarks
* Based on {@link https://github.com/ulid/spec}, IDs returned are guaranteed to be monotonically
* increasing.
*/
export function id(): bigint {
// Ensure timestamp monotonically increases and generate a new random on each new timestamp.
let timestamp = Date.now()
if (timestamp <= idLastTimestamp) {
timestamp = idLastTimestamp
} else {
idLastTimestamp = timestamp
randomFillSync(idLastBuffer)
}
// Increment the u80 in idLastBuffer using carry arithmetic on u32s (as JS doesn't have fast u64).
const littleEndian = true
const randomLo32 = idLastBuffer.getUint32(0, littleEndian) + 1
const randomHi32 = idLastBuffer.getUint32(4, littleEndian) + (randomLo32 > 0xFFFFFFFF ? 1 : 0)
const randomHi16 = idLastBuffer.getUint16(8, littleEndian) + (randomHi32 > 0xFFFFFFFF ? 1 : 0)
if (randomHi16 > 0xFFFF) {
throw new Error('random bits overflow on monotonic increment')
}
// Store the incremented random monotonic and the timestamp into the buffer.
idLastBuffer.setUint32(0, randomLo32 & 0xFFFFFFFF, littleEndian)
idLastBuffer.setUint32(4, randomHi32 & 0xFFFFFFFF, littleEndian)
idLastBuffer.setUint16(8, randomHi16, littleEndian) // No need to mask since checked above.
idLastBuffer.setUint16(10, timestamp & 0xFFFF, littleEndian) // timestamp lo.
idLastBuffer.setUint32(12, (timestamp >>> 16) & 0xFFFFFFFF, littleEndian) // timestamp hi.
// Then return the buffer's contents as a little-endian u128 bigint.
const lo = idLastBuffer.getBigUint64(0, littleEndian)
const hi = idLastBuffer.getBigUint64(8, littleEndian)
return (hi << 64n) | lo
}
|
0 | repos/tigerbeetle/src/clients/node | repos/tigerbeetle/src/clients/node/src/benchmark.ts | import assert from 'assert'
import {
Account,
createClient,
Transfer,
TransferFlags,
} from '.'
const MAX_TRANSFERS = 51200
// CI runs benchmark.ts against a "--development" replica.
const MAX_REQUEST_BATCH_SIZE = 254
const IS_TWO_PHASE_TRANSFER = false
const client = createClient({
cluster_id: 0n,
replica_addresses: [process.env.TB_ADDRESS || '3000']
})
const TRANSFER_SIZE = 128
const accountA: Account = {
id: 137n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
flags: 0,
timestamp: 0n,
}
const accountB: Account = {
id: 138n,
debits_pending: 0n,
debits_posted: 0n,
credits_pending: 0n,
credits_posted: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
reserved: 0,
ledger: 1,
code: 1,
flags: 0,
timestamp: 0n,
}
const runBenchmark = async () => {
console.log(`pre-allocating ${MAX_TRANSFERS} transfers and posts...`)
const transfers: Transfer[][] = []
const posts: Transfer[][] = []
let count = 0
while (count < MAX_TRANSFERS) {
const pendingBatch: Transfer[] = []
const postBatch: Transfer[] = []
for (let i = 0; i < MAX_REQUEST_BATCH_SIZE; i++) {
if (count === MAX_TRANSFERS) break
count += 1
pendingBatch.push({
id: BigInt(count),
debit_account_id: accountA.id,
credit_account_id: accountB.id,
amount: 1n,
pending_id: 0n,
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: IS_TWO_PHASE_TRANSFER ? 2 : 0,
code: 1,
ledger: 1,
flags: IS_TWO_PHASE_TRANSFER ? TransferFlags.pending : 0,
timestamp: 0n,
})
if (IS_TWO_PHASE_TRANSFER) {
postBatch.push({
id: BigInt(MAX_TRANSFERS + count),
debit_account_id: accountA.id,
credit_account_id: accountB.id,
amount: 1n,
pending_id: BigInt(count),
user_data_128: 0n,
user_data_64: 0n,
user_data_32: 0,
timeout: 0,
code: 1,
ledger: 1,
flags: IS_TWO_PHASE_TRANSFER ? TransferFlags.post_pending_transfer : 0,
timestamp: 0n,
})
}
}
transfers.push(pendingBatch)
if (IS_TWO_PHASE_TRANSFER) posts.push(postBatch)
}
assert(count === MAX_TRANSFERS)
console.log(`starting benchmark. MAX_TRANSFERS=${MAX_TRANSFERS} REQUEST_BATCH_SIZE=${MAX_REQUEST_BATCH_SIZE} NUMBER_OF_BATCHES=${transfers.length}`)
let maxCreateTransfersLatency = 0
let maxCommitTransfersLatency = 0
const start = Date.now()
for (let i = 0; i < transfers.length; i++) {
const ms1 = Date.now()
const transferErrors = await client.createTransfers(transfers[i])
assert(transferErrors.length === 0)
const ms2 = Date.now()
const createTransferLatency = ms2 - ms1
if (createTransferLatency > maxCreateTransfersLatency) {
maxCreateTransfersLatency = createTransferLatency
}
if (IS_TWO_PHASE_TRANSFER) {
const commitErrors = await client.createTransfers(posts[i])
assert(commitErrors.length === 0)
const ms3 = Date.now()
const commitTransferLatency = ms3 - ms2
if (commitTransferLatency > maxCommitTransfersLatency) {
maxCommitTransfersLatency = commitTransferLatency
}
}
}
const ms = Date.now() - start
return {
ms,
maxCommitTransfersLatency,
maxCreateTransfersLatency
}
}
const main = async () => {
console.log("creating the accounts...")
await client.createAccounts([accountA, accountB])
const accountResults = await client.lookupAccounts([accountA.id, accountB.id])
assert(accountResults.length === 2)
assert(accountResults[0].debits_posted === 0n)
assert(accountResults[1].debits_posted === 0n)
const benchmark = await runBenchmark()
const accounts = await client.lookupAccounts([accountA.id, accountB.id])
const result = Math.floor((1000 * MAX_TRANSFERS)/benchmark.ms)
console.log("=============================")
console.log(`${IS_TWO_PHASE_TRANSFER ? 'two-phase ' : ''}transfers per second: ${result}`)
console.log(`create transfers max p100 latency per 10 000 transfers = ${benchmark.maxCreateTransfersLatency}ms`)
console.log(`commit transfers max p100 latency per 10 000 transfers = ${benchmark.maxCommitTransfersLatency}ms`)
assert(accounts.length === 2)
assert(accounts[0].debits_posted === BigInt(MAX_TRANSFERS))
assert(accounts[1].credits_posted === BigInt(MAX_TRANSFERS))
}
main().catch(error => {
console.log(error)
}).finally(async () => {
await client.destroy()
})
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/java/ci.zig | const std = @import("std");
const log = std.log;
const assert = std.debug.assert;
const flags = @import("../../flags.zig");
const fatal = flags.fatal;
const Shell = @import("../../shell.zig");
const TmpTigerBeetle = @import("../../testing/tmp_tigerbeetle.zig");
pub fn tests(shell: *Shell, gpa: std.mem.Allocator) !void {
assert(shell.file_exists("pom.xml"));
try shell.zig("build clients:java -Drelease -Dconfig=production", .{});
try shell.zig("build -Drelease -Dconfig=production", .{});
try shell.zig("build test:jni", .{});
// Java's maven doesn't support a separate test command, or a way to add dependency on a
// project (as opposed to a compiled jar file).
//
// For this reason, we do all our testing in one go, imperatively building a client jar and
// installing it into the local maven repository.
try shell.exec("mvn --batch-mode --file pom.xml --quiet formatter:validate", .{});
try shell.exec("mvn --batch-mode --file pom.xml --quiet install", .{});
inline for (.{ "basic", "two-phase", "two-phase-many", "walkthrough" }) |sample| {
log.info("testing sample '{s}'", .{sample});
try shell.pushd("./samples/" ++ sample);
defer shell.popd();
var tmp_beetle = try TmpTigerBeetle.init(gpa, .{});
defer tmp_beetle.deinit(gpa);
errdefer tmp_beetle.log_stderr();
try shell.env.put("TB_ADDRESS", tmp_beetle.port_str.slice());
try shell.exec(
\\mvn --batch-mode --file pom.xml --quiet
\\ package exec:java
, .{});
}
}
pub fn validate_release(shell: *Shell, gpa: std.mem.Allocator, options: struct {
version: []const u8,
tigerbeetle: []const u8,
}) !void {
var tmp_beetle = try TmpTigerBeetle.init(gpa, .{
.prebuilt = options.tigerbeetle,
});
defer tmp_beetle.deinit(gpa);
errdefer tmp_beetle.log_stderr();
try shell.env.put("TB_ADDRESS", tmp_beetle.port_str.slice());
try shell.cwd.writeFile(.{ .sub_path = "pom.xml", .data = try shell.fmt(
\\<project>
\\ <modelVersion>4.0.0</modelVersion>
\\ <groupId>com.tigerbeetle</groupId>
\\ <artifactId>samples</artifactId>
\\ <version>1.0-SNAPSHOT</version>
\\
\\ <properties>
\\ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
\\ <maven.compiler.source>11</maven.compiler.source>
\\ <maven.compiler.target>11</maven.compiler.target>
\\ </properties>
\\
\\ <build>
\\ <plugins>
\\ <plugin>
\\ <groupId>org.apache.maven.plugins</groupId>
\\ <artifactId>maven-compiler-plugin</artifactId>
\\ <version>3.8.1</version>
\\ <configuration>
\\ <compilerArgs>
\\ <arg>-Xlint:all,-options,-path</arg>
\\ </compilerArgs>
\\ </configuration>
\\ </plugin>
\\
\\ <plugin>
\\ <groupId>org.codehaus.mojo</groupId>
\\ <artifactId>exec-maven-plugin</artifactId>
\\ <version>1.6.0</version>
\\ <configuration>
\\ <mainClass>com.tigerbeetle.samples.Main</mainClass>
\\ </configuration>
\\ </plugin>
\\ </plugins>
\\ </build>
\\
\\ <dependencies>
\\ <dependency>
\\ <groupId>com.tigerbeetle</groupId>
\\ <artifactId>tigerbeetle-java</artifactId>
\\ <version>{s}</version>
\\ </dependency>
\\ </dependencies>
\\</project>
, .{options.version}) });
try Shell.copy_path(
shell.project_root,
"src/clients/java/samples/basic/src/main/java/Main.java",
shell.cwd,
"src/main/java/Main.java",
);
// According to the docs, java package might not be immediately available:
//
// > Upon release, your component will be published to Central: this typically occurs within 30
// > minutes, though updates to search can take up to four hours.
//
// <https://central.sonatype.org/publish/publish-guide/#releasing-to-central>
//
// Retry the download for 45 minutes, passing `--update-snapshots` to thwart local negative
// caching.
for (0..9) |_| {
if (try mvn_update(shell) == .ok) break;
log.warn("waiting for 5 minutes for the {s} version to appear in maven cental", .{
options.version,
});
std.time.sleep(5 * std.time.ns_per_min);
} else {
switch (try mvn_update(shell)) {
.ok => {},
.retry => |err| {
log.err("package is not available in maven central", .{});
return err;
},
}
}
try shell.exec("mvn exec:java", .{});
}
fn mvn_update(shell: *Shell) !union(enum) { ok, retry: anyerror } {
if (shell.exec("mvn package --update-snapshots", .{})) {
return .ok;
} else |err| {
// Re-run immediately to capture stdout (sic) to check if the failure is indeed due to
// the package missing from the registry.
const exec_result = try shell.exec_raw("mvn package --update-snapshots", .{});
switch (exec_result.term) {
.Exited => |code| if (code == 0) return .ok,
else => {},
}
const package_missing = std.mem.indexOf(
u8,
exec_result.stdout,
"Could not resolve dependencies",
) != null;
if (package_missing) return .{ .retry = err };
return err;
}
}
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/java/docs.zig | const builtin = @import("builtin");
const std = @import("std");
const Docs = @import("../docs_types.zig").Docs;
pub const JavaDocs = Docs{
.directory = "java",
.markdown_name = "java",
.extension = "java",
.proper_name = "Java",
.test_source_path = "src/main/java/",
.name = "tigerbeetle-java",
.description =
\\The TigerBeetle client for Java.
\\
\\[](https://javadoc.io/doc/com.tigerbeetle/tigerbeetle-java)
\\
\\[](https://central.sonatype.com/namespace/com.tigerbeetle)
,
.prerequisites =
\\* Java >= 11
\\* Maven >= 3.6 (not strictly necessary but it's what our guides assume)
,
.project_file_name = "pom.xml",
.project_file =
\\<project xmlns="http://maven.apache.org/POM/4.0.0"
\\ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\\ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
\\ <modelVersion>4.0.0</modelVersion>
\\
\\ <groupId>com.tigerbeetle</groupId>
\\ <artifactId>samples</artifactId>
\\ <version>1.0-SNAPSHOT</version>
\\
\\ <properties>
\\ <maven.compiler.source>11</maven.compiler.source>
\\ <maven.compiler.target>11</maven.compiler.target>
\\ </properties>
\\
\\ <build>
\\ <plugins>
\\ <plugin>
\\ <groupId>org.apache.maven.plugins</groupId>
\\ <artifactId>maven-compiler-plugin</artifactId>
\\ <version>3.8.1</version>
\\ <configuration>
\\ <compilerArgs>
\\ <arg>-Xlint:all,-options,-path</arg>
\\ </compilerArgs>
\\ </configuration>
\\ </plugin>
\\
\\ <plugin>
\\ <groupId>org.codehaus.mojo</groupId>
\\ <artifactId>exec-maven-plugin</artifactId>
\\ <version>1.6.0</version>
\\ <configuration>
\\ <mainClass>com.tigerbeetle.samples.Main</mainClass>
\\ </configuration>
\\ </plugin>
\\ </plugins>
\\ </build>
\\
\\ <dependencies>
\\ <dependency>
\\ <groupId>com.tigerbeetle</groupId>
\\ <artifactId>tigerbeetle-java</artifactId>
\\ <!-- Grab the latest commit from: https://repo1.maven.org/maven2/com/tigerbeetle/tigerbeetle-java/maven-metadata.xml -->
\\ <version>0.0.1-3431</version>
\\ </dependency>
\\ </dependencies>
\\</project>
,
.test_file_name = "Main",
.install_commands = "mvn install",
.run_commands = "mvn exec:java",
.examples = "",
.client_object_documentation = "",
.create_accounts_documentation =
\\The 128-bit fields like `id` and `user_data_128` have a few
\\overrides to make it easier to integrate. You can either
\\pass in a long, a pair of longs (least and most
\\significant bits), or a `byte[]`.
\\
\\There is also a `com.tigerbeetle.UInt128` helper with static
\\methods for converting 128-bit little-endian unsigned integers
\\between instances of `long`, `java.util.UUID`, `java.math.BigInteger` and `byte[]`.
\\
\\The fields for transfer amounts and account balances are also 128-bit,
\\but they are always represented as a `java.math.BigInteger`.
,
.account_flags_documentation =
\\To toggle behavior for an account, combine enum values stored in the
\\`AccountFlags` object with bitwise-or:
\\
\\* `AccountFlags.LINKED`
\\* `AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS`
\\* `AccountFlags.CREDITS_MUST_NOT_EXCEED_CREDITS`
\\* `AccountFlags.HISTORY`
,
.create_accounts_errors_documentation = "",
.create_transfers_documentation = "",
.create_transfers_errors_documentation = "",
.transfer_flags_documentation =
\\To toggle behavior for an account, combine enum values stored in the
\\`TransferFlags` object with bitwise-or:
\\
\\* `TransferFlags.NONE`
\\* `TransferFlags.LINKED`
\\* `TransferFlags.PENDING`
\\* `TransferFlags.POST_PENDING_TRANSFER`
\\* `TransferFlags.VOID_PENDING_TRANSFER`
,
};
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/java/exclude-pmd.properties | # PMD Source Code Analyzer Project
# https://pmd.github.io/
# Exclusion rules
# DoNotExtendJavaLangError: this class has "System Error" semantics,
# the application must not try to recover from them.
#
# UnnecessaryFullyQualifiedName: it is necessary to full qualify java.lang.AssertionError
# since both classes have the same name, but in different packages
com.tigerbeetle.AssertionError=DoNotExtendJavaLangError,UnnecessaryFullyQualifiedName
# AvoidCatchingThrowable: we do need to catch and store any Throwable
# during the callback, since we can't handle them from the C client's thread.
#
# UnusedPrivateField: some private fields are used from the JNI side.
com.tigerbeetle.Request=AvoidCatchingThrowable,UnusedPrivateField
# Avoid empty catch blocks: we need to ignore IOException errors.
com.tigerbeetle.JNILoader$Abi=EmptyCatchBlock
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/java/java_bindings.zig | const std = @import("std");
const vsr = @import("vsr");
const stdx = vsr.stdx;
const tb = vsr.tigerbeetle;
const tb_client = vsr.tb_client;
const assert = std.debug.assert;
const TypeMapping = struct {
name: []const u8,
private_fields: []const []const u8 = &.{},
readonly_fields: []const []const u8 = &.{},
docs_link: ?[]const u8 = null,
visibility: enum { public, internal } = .public,
constants: []const u8 = "",
pub fn is_private(comptime self: @This(), name: []const u8) bool {
inline for (self.private_fields) |field| {
if (std.mem.eql(u8, field, name)) {
return true;
}
} else return false;
}
pub fn is_read_only(comptime self: @This(), name: []const u8) bool {
inline for (self.readonly_fields) |field| {
if (std.mem.eql(u8, field, name)) {
return true;
}
} else return false;
}
};
/// Some 128-bit fields are better represented as `java.math.BigInteger`,
/// otherwise they are considered IDs and exposed as an array of bytes.
const big_integer = struct {
const fields = .{
"credits_posted",
"credits_pending",
"debits_posted",
"debits_pending",
"amount",
};
fn contains(comptime field: []const u8) bool {
return comptime blk: for (fields) |value| {
if (std.mem.eql(u8, field, value)) break :blk true;
} else false;
}
fn contains_any(comptime type_info: anytype) bool {
return comptime blk: for (type_info.fields) |field| {
if (contains(field.name)) break :blk true;
} else false;
}
};
const type_mappings = .{
.{ tb.AccountFlags, TypeMapping{
.name = "AccountFlags",
.private_fields = &.{"padding"},
.docs_link = "reference/account#flags",
} },
.{ tb.TransferFlags, TypeMapping{
.name = "TransferFlags",
.private_fields = &.{"padding"},
.docs_link = "reference/transfer#flags",
} },
.{ tb.AccountFilterFlags, TypeMapping{
.name = "AccountFilterFlags",
.private_fields = &.{"padding"},
.visibility = .internal,
} },
.{ tb.QueryFilterFlags, TypeMapping{
.name = "QueryFilterFlags",
.private_fields = &.{"padding"},
.visibility = .internal,
} },
.{ tb.Account, TypeMapping{
.name = "AccountBatch",
.private_fields = &.{"reserved"},
.readonly_fields = &.{
"debits_pending",
"credits_pending",
"debits_posted",
"credits_posted",
},
.docs_link = "reference/account#",
} },
.{ tb.AccountBalance, TypeMapping{
.name = "AccountBalanceBatch",
.private_fields = &.{"reserved"},
.readonly_fields = &.{
"debits_pending",
"credits_pending",
"debits_posted",
"credits_posted",
"timestamp",
},
.docs_link = "reference/account-balances#",
} },
.{
tb.Transfer, TypeMapping{
.name = "TransferBatch",
.private_fields = &.{"reserved"},
.readonly_fields = &.{},
.docs_link = "reference/transfer#",
.constants =
\\ public static final BigInteger AMOUNT_MAX =
\\ UInt128.asBigInteger(Long.MIN_VALUE, Long.MIN_VALUE);
\\
,
},
},
.{ tb.CreateAccountResult, TypeMapping{
.name = "CreateAccountResult",
.docs_link = "reference/requests/create_accounts#",
} },
.{ tb.CreateTransferResult, TypeMapping{
.name = "CreateTransferResult",
.docs_link = "reference/requests/create_transfers#",
} },
.{ tb.CreateAccountsResult, TypeMapping{
.name = "CreateAccountResultBatch",
.readonly_fields = &.{ "index", "result" },
} },
.{ tb.CreateTransfersResult, TypeMapping{
.name = "CreateTransferResultBatch",
.readonly_fields = &.{ "index", "result" },
} },
.{ tb.AccountFilter, TypeMapping{
.name = "AccountFilterBatch",
.visibility = .internal,
.private_fields = &.{"reserved"},
} },
.{ tb.QueryFilter, TypeMapping{
.name = "QueryFilterBatch",
.visibility = .internal,
.private_fields = &.{"reserved"},
} },
.{ tb_client.tb_status_t, TypeMapping{
.name = "InitializationStatus",
} },
.{ tb_client.tb_packet_status_t, TypeMapping{
.name = "PacketStatus",
} },
};
const auto_generated_code_notice =
\\//////////////////////////////////////////////////////////
\\// This file was auto-generated by java_bindings.zig
\\// Do not manually modify.
\\//////////////////////////////////////////////////////////
\\
;
fn java_type(
comptime Type: type,
) []const u8 {
switch (@typeInfo(Type)) {
.Enum => return comptime get_mapped_type_name(Type) orelse @compileError(
"Type " ++ @typeName(Type) ++ " not mapped.",
),
.Struct => |info| switch (info.layout) {
.@"packed" => return comptime java_type(std.meta.Int(.unsigned, @bitSizeOf(Type))),
else => return comptime get_mapped_type_name(Type) orelse @compileError(
"Type " ++ @typeName(Type) ++ " not mapped.",
),
},
.Int => |info| {
// For better API ergonomy,
// we expose 16-bit unsigned integers in Java as "int" instead of "short".
// Even though, the backing fields are always stored as "short".
std.debug.assert(info.signedness == .unsigned);
return switch (info.bits) {
1 => "byte",
8 => "byte",
16, 32 => "int",
64 => "long",
else => @compileError("invalid int type"),
};
},
else => @compileError("Unhandled type: " ++ @typeName(Type)),
}
}
fn get_mapped_type_name(comptime Type: type) ?[]const u8 {
inline for (type_mappings) |type_mapping| {
if (Type == type_mapping[0]) {
return type_mapping[1].name;
}
} else return null;
}
fn to_case(
comptime input: []const u8,
comptime case: enum { camel, pascal, upper },
) []const u8 {
// TODO(Zig): Cleanup when this is fixed after Zig 0.11.
// Without comptime blk, the compiler thinks slicing the output on return happens at runtime.
return comptime blk: {
var output: [input.len]u8 = undefined;
if (case == .upper) {
const len = std.ascii.upperString(output[0..], input).len;
break :blk stdx.comptime_slice(&output, len);
} else {
var len: usize = 0;
var iterator = std.mem.tokenize(u8, input, "_");
while (iterator.next()) |word| {
_ = std.ascii.lowerString(output[len..], word);
output[len] = std.ascii.toUpper(output[len]);
len += word.len;
}
output[0] = switch (case) {
.camel => std.ascii.toLower(output[0]),
.pascal => std.ascii.toUpper(output[0]),
.upper => unreachable,
};
break :blk stdx.comptime_slice(&output, len);
}
};
}
fn emit_enum(
buffer: *std.ArrayList(u8),
comptime Type: type,
comptime mapping: TypeMapping,
comptime int_type: []const u8,
) !void {
try buffer.writer().print(
\\{[notice]s}
\\package com.tigerbeetle;
\\
\\{[visibility]s}enum {[name]s} {{
\\
, .{
.visibility = if (mapping.visibility == .internal) "" else "public ",
.notice = auto_generated_code_notice,
.name = mapping.name,
});
const type_info = @typeInfo(Type).Enum;
inline for (type_info.fields, 0..) |field, i| {
if (comptime mapping.is_private(field.name)) continue;
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\
\\ /**
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
}
try buffer.writer().print(
\\ {[enum_name]s}(({[int_type]s}) {[value]d}){[separator]c}
\\
, .{
.enum_name = to_case(field.name, .pascal),
.int_type = int_type,
.value = @intFromEnum(@field(Type, field.name)),
.separator = if (i == type_info.fields.len - 1) ';' else ',',
});
}
try buffer.writer().print(
\\
\\ public final {[int_type]s} value;
\\
\\ static final {[name]s}[] enumByValue;
\\ static {{
\\ final var values = values();
\\ enumByValue = new {[name]s}[values.length];
\\ for (final var item : values) {{
\\ enumByValue[item.value] = item;
\\ }}
\\ }}
\\
\\ {[name]s}({[int_type]s} value) {{
\\ this.value = value;
\\ }}
\\
\\ public static {[name]s} fromValue({[int_type]s} value) {{
\\ if (value < 0 || value >= enumByValue.length)
\\ throw new IllegalArgumentException(
\\ String.format("Invalid {[name]s} value=%d", value));
\\
\\ final var item = enumByValue[value];
\\ AssertionError.assertTrue(item.value == value,
\\ "Unexpected {[name]s}: found=%d expected=%d", item.value, value);
\\ return item;
\\ }}
\\}}
\\
\\
, .{
.int_type = int_type,
.name = mapping.name,
});
}
fn emit_packed_enum(
buffer: *std.ArrayList(u8),
comptime type_info: anytype,
comptime mapping: TypeMapping,
comptime int_type: []const u8,
) !void {
try buffer.writer().print(
\\{[notice]s}
\\package com.tigerbeetle;
\\
\\{[visibility]s}interface {[name]s} {{
\\ {[int_type]s} NONE = ({[int_type]s}) 0;
\\
, .{
.visibility = if (mapping.visibility == .internal) "" else "public ",
.notice = auto_generated_code_notice,
.name = mapping.name,
.int_type = int_type,
});
inline for (type_info.fields, 0..) |field, i| {
if (comptime mapping.is_private(field.name)) continue;
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\
\\ /**
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
}
try buffer.writer().print(
\\ {[int_type]s} {[enum_name]s} = ({[int_type]s}) (1 << {[value]d});
\\
, .{
.int_type = int_type,
.enum_name = to_case(field.name, .upper),
.value = i,
});
}
try buffer.writer().print("\n", .{});
inline for (type_info.fields) |field| {
if (comptime mapping.is_private(field.name)) continue;
try buffer.writer().print(
\\ static boolean has{[flag_name]s}(final {[int_type]s} flags) {{
\\ return (flags & {[enum_name]s}) == {[enum_name]s};
\\ }}
\\
\\
, .{
.flag_name = to_case(field.name, .pascal),
.int_type = int_type,
.enum_name = to_case(field.name, .upper),
});
}
try buffer.writer().print(
\\}}
\\
, .{});
}
fn batch_type(comptime Type: type) []const u8 {
switch (@typeInfo(Type)) {
.Int => |info| {
std.debug.assert(info.signedness == .unsigned);
switch (info.bits) {
16 => return "UInt16",
32 => return "UInt32",
64 => return "UInt64",
else => {},
}
},
.Struct => |info| switch (info.layout) {
.@"packed" => return batch_type(std.meta.Int(.unsigned, @bitSizeOf(Type))),
else => {},
},
.Enum => return batch_type(std.meta.Int(.unsigned, @bitSizeOf(Type))),
else => {},
}
@compileError("Unhandled type: " ++ @typeName(Type));
}
fn emit_batch(
buffer: *std.ArrayList(u8),
comptime type_info: anytype,
comptime mapping: TypeMapping,
comptime size: usize,
) !void {
try buffer.writer().print(
\\{[notice]s}
\\package com.tigerbeetle;
\\
\\import java.nio.ByteBuffer;
\\{[big_integer_import]s}
\\
\\{[visibility]s}final class {[name]s} extends Batch {{
\\
\\{[constants]s}
\\ interface Struct {{
\\ int SIZE = {[size]d};
\\
\\
, .{
.visibility = if (mapping.visibility == .internal) "" else "public ",
.notice = auto_generated_code_notice,
.name = mapping.name,
.size = size,
.big_integer_import = if (big_integer.contains_any(type_info))
"import java.math.BigInteger;"
else
"",
.constants = mapping.constants,
});
// Fields offset:
var offset: usize = 0;
inline for (type_info.fields) |field| {
try buffer.writer().print(
\\ int {[field_name]s} = {[offset]d};
\\
, .{
.field_name = to_case(field.name, .pascal),
.offset = offset,
});
offset += @sizeOf(field.type);
}
// Constructors:
try buffer.writer().print(
\\ }}
\\
\\ static final {[name]s} EMPTY = new {[name]s}(0);
\\
\\ /**
\\ * Creates an empty batch with the desired maximum capacity.
\\ * <p>
\\ * Once created, an instance cannot be resized, however it may contain any number of elements
\\ * between zero and its {{@link #getCapacity capacity}}.
\\ *
\\ * @param capacity the maximum capacity.
\\ * @throws IllegalArgumentException if capacity is negative.
\\ */
\\ public {[name]s}(final int capacity) {{
\\ super(capacity, Struct.SIZE);
\\ }}
\\
\\ {[name]s}(final ByteBuffer buffer) {{
\\ super(buffer, Struct.SIZE);
\\ }}
\\
\\
, .{
.name = mapping.name,
});
// Properties:
inline for (type_info.fields) |field| {
if (field.type == u128) {
try emit_u128_batch_accessors(buffer, mapping, field);
} else {
try emit_batch_accessors(buffer, mapping, field);
}
}
try buffer.writer().print(
\\}}
\\
\\
, .{});
}
fn emit_batch_accessors(
buffer: *std.ArrayList(u8),
comptime mapping: TypeMapping,
comptime field: anytype,
) !void {
comptime assert(field.type != u128);
const is_private = comptime mapping.is_private(field.name);
const is_read_only = comptime mapping.is_read_only(field.name);
// Get:
try buffer.writer().print(
\\ /**
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\
, .{});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
if (@typeInfo(field.type) == .Array) {
try buffer.writer().print(
\\ {[visibility]s}byte[] get{[property]s}() {{
\\ return getArray(at(Struct.{[property]s}), {[array_len]d});
\\ }}
\\
\\
, .{
.visibility = if (is_private) "" else "public ",
.property = to_case(field.name, .pascal),
.array_len = @typeInfo(field.type).Array.len,
});
} else {
try buffer.writer().print(
\\ {[visibility]s}{[java_type]s} get{[property]s}() {{
\\ final var value = get{[batch_type]s}(at(Struct.{[property]s}));
\\ return {[return_expression]s};
\\ }}
\\
\\
, .{
.visibility = if (is_private) "" else "public ",
.java_type = java_type(field.type),
.property = to_case(field.name, .pascal),
.batch_type = batch_type(field.type),
.return_expression = comptime if (@typeInfo(field.type) == .Enum)
get_mapped_type_name(field.type).? ++ ".fromValue(value)"
else
"value",
});
}
// Set:
try buffer.writer().print(
\\ /**
\\ * @param {[param_name]s}
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\ * @throws IllegalStateException if a {{@link #isReadOnly() read-only}} batch.
\\
, .{
.param_name = to_case(field.name, .camel),
});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
if (@typeInfo(field.type) == .Array) {
try buffer.writer().print(
\\ {[visibility]s}void set{[property]s}(byte[] {[param_name]s}) {{
\\ if ({[param_name]s} == null)
\\ {[param_name]s} = new byte[{[array_len]d}];
\\ if ({[param_name]s}.length != {[array_len]d})
\\ throw new IllegalArgumentException("Reserved must be {[array_len]d} bytes long");
\\ putArray(at(Struct.{[property]s}), {[param_name]s});
\\ }}
\\
\\
, .{
.property = to_case(field.name, .pascal),
.param_name = to_case(field.name, .camel),
.visibility = if (is_private or is_read_only) "" else "public ",
.array_len = @typeInfo(field.type).Array.len,
});
} else {
try buffer.writer().print(
\\ {[visibility]s}void set{[property]s}(final {[java_type]s} {[param_name]s}) {{
\\ put{[batch_type]s}(at(Struct.{[property]s}), {[param_name]s}{[value_expression]s});
\\ }}
\\
\\
, .{
.property = to_case(field.name, .pascal),
.param_name = to_case(field.name, .camel),
.visibility = if (is_private or is_read_only) "" else "public ",
.batch_type = batch_type(field.type),
.java_type = java_type(field.type),
.value_expression = if (comptime @typeInfo(field.type) == .Enum)
".value"
else
"",
});
}
}
// We offer multiple APIs for dealing with UInt128 in Java:
// - A byte array, heap-allocated, for ids and user_data;
// - A BigInteger, heap-allocated, for balances and amounts;
// - Two 64-bit integers (long), stack-allocated, for both cases;
fn emit_u128_batch_accessors(
buffer: *std.ArrayList(u8),
comptime mapping: TypeMapping,
comptime field: anytype,
) !void {
comptime assert(field.type == u128);
const is_private = comptime mapping.is_private(field.name);
const is_read_only = comptime mapping.is_read_only(field.name);
if (big_integer.contains(field.name)) {
// Get BigInteger:
try buffer.writer().print(
\\ /**
\\ * @return a {{@link java.math.BigInteger}} representing the 128-bit value.
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\
, .{});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
try buffer.writer().print(
\\ {[visibility]s}BigInteger get{[property]s}() {{
\\ final var index = at(Struct.{[property]s});
\\ return UInt128.asBigInteger(
\\ getUInt128(index, UInt128.LeastSignificant),
\\ getUInt128(index, UInt128.MostSignificant));
\\ }}
\\
\\
, .{
.visibility = if (is_private) "" else "public ",
.property = to_case(field.name, .pascal),
});
} else {
// Get array:
try buffer.writer().print(
\\ /**
\\ * @return an array of 16 bytes representing the 128-bit value.
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\
, .{});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
try buffer.writer().print(
\\ {[visibility]s}byte[] get{[property]s}() {{
\\ return getUInt128(at(Struct.{[property]s}));
\\ }}
\\
\\
, .{
.visibility = if (is_private) "" else "public ",
.property = to_case(field.name, .pascal),
});
}
// Get long:
try buffer.writer().print(
\\ /**
\\ * @param part a {{@link UInt128}} enum indicating which part of the 128-bit value
\\ is to be retrieved.
\\ * @return a {{@code long}} representing the first 8 bytes of the 128-bit value if
\\ * {{@link UInt128#LeastSignificant}} is informed, or the last 8 bytes if
\\ * {{@link UInt128#MostSignificant}}.
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\
, .{});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
try buffer.writer().print(
\\ {[visibility]s}long get{[property]s}(final UInt128 part) {{
\\ return getUInt128(at(Struct.{[property]s}), part);
\\ }}
\\
\\
, .{
.visibility = if (is_private) "" else "public ",
.property = to_case(field.name, .pascal),
});
if (big_integer.contains(field.name)) {
// Set BigInteger:
try buffer.writer().print(
\\ /**
\\ * @param {[param_name]s} a {{@link java.math.BigInteger}} representing the 128-bit value.
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\ * @throws IllegalStateException if a {{@link #isReadOnly() read-only}} batch.
\\
, .{
.param_name = to_case(field.name, .camel),
});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
try buffer.writer().print(
\\ {[visibility]s}void set{[property]s}(final BigInteger {[param_name]s}) {{
\\ putUInt128(at(Struct.{[property]s}), UInt128.asBytes({[param_name]s}));
\\ }}
\\
\\
, .{
.visibility = if (is_private or is_read_only) "" else "public ",
.property = to_case(field.name, .pascal),
.param_name = to_case(field.name, .camel),
});
} else {
// Set array:
try buffer.writer().print(
\\ /**
\\ * @param {[param_name]s} an array of 16 bytes representing the 128-bit value.
\\ * @throws IllegalArgumentException if {{@code {[param_name]s}}} is not 16 bytes long.
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\ * @throws IllegalStateException if a {{@link #isReadOnly() read-only}} batch.
\\
, .{
.param_name = to_case(field.name, .camel),
});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
try buffer.writer().print(
\\ {[visibility]s}void set{[property]s}(final byte[] {[param_name]s}) {{
\\ putUInt128(at(Struct.{[property]s}), {[param_name]s});
\\ }}
\\
\\
, .{
.visibility = if (is_private or is_read_only) "" else "public ",
.property = to_case(field.name, .pascal),
.param_name = to_case(field.name, .camel),
});
}
// Set long:
try buffer.writer().print(
\\ /**
\\ * @param leastSignificant a {{@code long}} representing the first 8 bytes of the 128-bit value.
\\ * @param mostSignificant a {{@code long}} representing the last 8 bytes of the 128-bit value.
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\ * @throws IllegalStateException if a {{@link #isReadOnly() read-only}} batch.
\\
, .{});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
try buffer.writer().print(
\\ {[visibility]s}void set{[property]s}(final long leastSignificant, final long mostSignificant) {{
\\ putUInt128(at(Struct.{[property]s}), leastSignificant, mostSignificant);
\\ }}
\\
\\
, .{
.visibility = if (is_private or is_read_only) "" else "public ",
.property = to_case(field.name, .pascal),
});
// Set long without most significant bits
try buffer.writer().print(
\\ /**
\\ * @param leastSignificant a {{@code long}} representing the first 8 bytes of the 128-bit value.
\\ * @throws IllegalStateException if not at a {{@link #isValidPosition valid position}}.
\\ * @throws IllegalStateException if a {{@link #isReadOnly() read-only}} batch.
\\
, .{});
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ * @see <a href="https://docs.tigerbeetle.com/{[docs_link]s}{[field_name]s}">{[field_name]s}</a>
\\ */
\\
, .{
.docs_link = docs_link,
.field_name = field.name,
});
} else {
try buffer.writer().print(
\\ */
\\
, .{});
}
try buffer.writer().print(
\\ {[visibility]s}void set{[property]s}(final long leastSignificant) {{
\\ putUInt128(at(Struct.{[property]s}), leastSignificant, 0);
\\ }}
\\
\\
, .{
.visibility = if (is_private or is_read_only) "" else "public ",
.property = to_case(field.name, .pascal),
});
}
pub fn generate_bindings(
comptime ZigType: type,
comptime mapping: TypeMapping,
buffer: *std.ArrayList(u8),
) !void {
@setEvalBranchQuota(100_000);
switch (@typeInfo(ZigType)) {
.Struct => |info| switch (info.layout) {
.auto => @compileError(
"Only packed or extern structs are supported: " ++ @typeName(ZigType),
),
.@"packed" => try emit_packed_enum(
buffer,
info,
mapping,
comptime java_type(std.meta.Int(.unsigned, @bitSizeOf(ZigType))),
),
.@"extern" => try emit_batch(
buffer,
info,
mapping,
@sizeOf(ZigType),
),
},
.Enum => try emit_enum(
buffer,
ZigType,
mapping,
comptime java_type(std.meta.Int(.unsigned, @bitSizeOf(ZigType))),
),
else => @compileError("Type cannot be represented: " ++ @typeName(ZigType)),
}
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();
assert(args.skip());
const target_dir_path = args.next().?;
assert(args.next() == null);
var target_dir = try std.fs.cwd().openDir(target_dir_path, .{});
defer target_dir.close();
// Emit Java declarations.
inline for (type_mappings) |type_mapping| {
const ZigType = type_mapping[0];
const mapping = type_mapping[1];
var buffer = std.ArrayList(u8).init(allocator);
try generate_bindings(ZigType, mapping, &buffer);
try target_dir.writeFile(.{
.sub_path = mapping.name ++ ".java",
.data = buffer.items,
});
}
}
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/java/LICENSE.txt |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/java/pom.xml | <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tigerbeetle</groupId>
<artifactId>tigerbeetle-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>TigerBeetle Java client</name>
<description>The distributed financial accounting database designed for mission critical safety and performance.</description>
<developers>
<developer>
<name>The TigerBeetle contributors</name>
<email>[email protected]</email>
</developer>
</developers>
<organization>
<name>TigerBeetle, Inc.</name>
<url>https://www.tigerbeetle.com</url>
</organization>
<url>https://www.tigerbeetle.com</url>
<scm>
<url>https://github.com/tigerbeetle/tigerbeetle</url>
</scm>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<!-- JaCoCo thresholds -->
<jacoco.unit-tests.limit.instruction-ratio>95%</jacoco.unit-tests.limit.instruction-ratio>
<jacoco.unit-tests.limit.branch-ratio>85%</jacoco.unit-tests.limit.branch-ratio>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>[4.13.1,)</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>Windows</id>
<activation>
<os>
<family>Windows</family>
</os>
</activation>
<properties>
<executable.extension>.exe</executable.extension>
<script.extension>.bat</script.extension>
</properties>
</profile>
<profile>
<id>unix</id>
<activation>
<os>
<family>unix</family>
</os>
</activation>
<properties>
<executable.extension></executable.extension>
<script.extension>.sh</script.extension>
</properties>
</profile>
</profiles>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<workingDirectory>${project.basedir}</workingDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<!-- Excludes object files created during zig compilation -->
<excludes>
<exclude>**/*.o</exclude>
<exclude>**/*.obj</exclude>
<exclude>**/*.pdb</exclude>
<exclude>**/win*/*.lib</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<configuration>
<excludes>
<!-- Excluding exceptions classes -->
<exclude>com/tigerbeetle/InitializationException.class</exclude>
<exclude>com/tigerbeetle/RequestException.class</exclude>
<exclude>com/tigerbeetle/ConcurrencyExceededException.class</exclude>
<exclude>com/tigerbeetle/AssertionError.class</exclude>
<!-- Excluding JNILoader platform specifics -->
<exclude>com/tigerbeetle/JNILoader$OS.class</exclude>
<exclude>com/tigerbeetle/JNILoader$Arch.class</exclude>
<exclude>com/tigerbeetle/JNILoader$Abi.class</exclude>
<!-- Excluding enums -->
<exclude>com/tigerbeetle/PacketStatus.class</exclude>
<exclude>com/tigerbeetle/PacketAcquireStatus.class</exclude>
<exclude>com/tigerbeetle/InitializationStatus.class</exclude>
<exclude>com/tigerbeetle/TransferFlags.class</exclude>
<exclude>com/tigerbeetle/AccountFilterFlags.class</exclude>
<exclude>com/tigerbeetle/QueryFilterFlags.class</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>net.revelc.code.formatter</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<version>2.19.0</version>
<configuration>
<lineEnding>LF</lineEnding>
<configFile>${project.basedir}/eclipse-formatter.xml</configFile>
<!-- Excluding all autogenerated files -->
<excludes>
<exclude>com/tigerbeetle/AccountBatch.java</exclude>
<exclude>com/tigerbeetle/AccountFlags.java</exclude>
<exclude>com/tigerbeetle/CreateAccountResult.java</exclude>
<exclude>com/tigerbeetle/CreateAccountResultBatch.java</exclude>
<exclude>com/tigerbeetle/CreateTransferResult.java</exclude>
<exclude>com/tigerbeetle/CreateTransferResultBatch.java</exclude>
<exclude>com/tigerbeetle/InitializationStatus.java</exclude>
<exclude>com/tigerbeetle/PacketStatus.java</exclude>
<exclude>com/tigerbeetle/TransferBatch.java</exclude>
<exclude>com/tigerbeetle/TransferFlags.java</exclude>
<exclude>com/tigerbeetle/AccountFilterFlags.java</exclude>
<exclude>com/tigerbeetle/AccountFilterBatch.java</exclude>
<exclude>com/tigerbeetle/AccountBalanceBatch.java</exclude>
<exclude>com/tigerbeetle/QueryFilterFlags.java</exclude>
<exclude>com/tigerbeetle/QueryFilterBatch.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.19.0</version>
<configuration>
<linkXRef>false</linkXRef>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<!-- Formatter -->
<plugin>
<groupId>net.revelc.code.formatter</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<executions>
<execution>
<id>format</id>
<phase>validate</phase>
<goals>
<goal>format</goal>
</goals>
</execution>
<execution>
<!-- Format linter -->
<id>format-validate</id>
<goals>
<goal>validate</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Code Coverage using JaCoCo -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-check</id>
<phase>test</phase>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>INSTRUCTION</counter>
<value>COVEREDRATIO</value>
<minimum>${jacoco.unit-tests.limit.instruction-ratio}</minimum>
</limit>
<limit>
<counter>BRANCH</counter>
<value>COVEREDRATIO</value>
<minimum>${jacoco.unit-tests.limit.branch-ratio}</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
<!-- could be replaced by a online tool such as codecov -->
<execution>
<id>jacoco-report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Sign artifacts -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>deploy</phase>
<goals>
<goal>sign</goal>
</goals>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>
<!-- Source code jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Javadoc jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- PMD -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<executions>
<execution>
<id>pdm-check</id>
<phase>test</phase>
<goals>
<goal>check</goal>
</goals>
<configuration>
<verbose>true</verbose>
<excludeFromFailureFile>${project.basedir}/exclude-pmd.properties</excludeFromFailureFile>
</configuration>
</execution>
</executions>
</plugin>
<!-- Maven central -->
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.13</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://s01.oss.sonatype.org</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
<stagingProgressTimeoutMinutes>30</stagingProgressTimeoutMinutes>
</configuration>
</plugin>
</plugins>
</build>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</project>
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/java/README.md | ---
title: Java
---
<!-- This file is generated by [/src/scripts/client_readmes.zig](/src/scripts/client_readmes.zig). -->
# tigerbeetle-java
The TigerBeetle client for Java.
[](https://javadoc.io/doc/com.tigerbeetle/tigerbeetle-java)
[](https://central.sonatype.com/namespace/com.tigerbeetle)
## Prerequisites
Linux >= 5.6 is the only production environment we
support. But for ease of development we also support macOS and Windows.
* Java >= 11
* Maven >= 3.6 (not strictly necessary but it's what our guides assume)
## Setup
First, create a directory for your project and `cd` into the directory.
Then create `pom.xml` and copy this into it:
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tigerbeetle</groupId>
<artifactId>samples</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<arg>-Xlint:all,-options,-path</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>com.tigerbeetle.samples.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.tigerbeetle</groupId>
<artifactId>tigerbeetle-java</artifactId>
<!-- Grab the latest commit from: https://repo1.maven.org/maven2/com/tigerbeetle/tigerbeetle-java/maven-metadata.xml -->
<version>0.0.1-3431</version>
</dependency>
</dependencies>
</project>
```
Then, install the TigerBeetle client:
```console
mvn install
```
Now, create `src/main/java/Main.java` and copy this into it:
```java
package com.tigerbeetle.samples;
import com.tigerbeetle.*;
public final class Main {
public static void main(String[] args) throws Exception {
System.out.println("Import ok!");
}
}
```
Finally, build and run:
```console
mvn exec:java
```
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/java/samples/basic/): Create two accounts and transfer an amount between them.
* [Two-Phase Transfer](/src/clients/java/samples/two-phase/): Create two accounts and start a pending transfer between
them, then post the transfer.
* [Many Two-Phase Transfers](/src/clients/java/samples/two-phase-many/): Create two accounts and start a number of pending transfer
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.
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`.
```java
String replicaAddress = System.getenv("TB_ADDRESS");
byte[] clusterID = UInt128.asBytes(0);
String[] replicaAddresses = new String[] {replicaAddress == null ? "3000" : replicaAddress};
try (var client = new Client(clusterID, replicaAddresses)) {
// Use client
}
```
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).
```java
AccountBatch accounts = new AccountBatch(1);
accounts.add();
accounts.setId(137);
accounts.setUserData128(UInt128.asBytes(java.util.UUID.randomUUID()));
accounts.setUserData64(1234567890);
accounts.setUserData32(42);
accounts.setLedger(1);
accounts.setCode(718);
accounts.setFlags(0);
CreateAccountResultBatch accountErrors = client.createAccounts(accounts);
```
The 128-bit fields like `id` and `user_data_128` have a few
overrides to make it easier to integrate. You can either
pass in a long, a pair of longs (least and most
significant bits), or a `byte[]`.
There is also a `com.tigerbeetle.UInt128` helper with static
methods for converting 128-bit little-endian unsigned integers
between instances of `long`, `java.util.UUID`, `java.math.BigInteger` and `byte[]`.
The fields for transfer amounts and account balances are also 128-bit,
but they are always represented as a `java.math.BigInteger`.
### 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, combine enum values stored in the
`AccountFlags` object with bitwise-or:
* `AccountFlags.LINKED`
* `AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS`
* `AccountFlags.CREDITS_MUST_NOT_EXCEED_CREDITS`
* `AccountFlags.HISTORY`
For example, to link two accounts where the first account
additionally has the `debits_must_not_exceed_credits` constraint:
```java
accounts = new AccountBatch(3);
// First account
accounts.add();
// Code to fill out fields for first account
accounts.setFlags(AccountFlags.LINKED | AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS);
// Second account
accounts.add();
// Code to fill out fields for second account
accountErrors = client.createAccounts(accounts);
```
### 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).
```java
while (accountErrors.next()) {
switch (accountErrors.getResult()) {
case Exists:
System.err.printf("Account at %d already exists.\n",
accountErrors.getIndex());
break;
default:
System.err.printf("Error creating account at %d: %s\n",
accountErrors.getIndex(), accountErrors.getResult());
break;
}
}
```
## 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.
```java
IdBatch ids = new IdBatch(2);
ids.add(137);
ids.add(138);
accounts = client.lookupAccounts(ids);
```
## 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).
```java
TransferBatch transfers = new TransferBatch(1);
transfers.add();
transfers.setId(1);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setAmount(10);
transfers.setUserData128(UInt128.asBytes(java.util.UUID.randomUUID()));
transfers.setUserData64(1234567890);
transfers.setUserData32(42);
transfers.setTimeout(0);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setFlags(0);
CreateTransferResultBatch transferErrors = client.createTransfers(transfers);
```
### 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).
```java
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
case ExceedsCredits:
System.err.printf("Transfer at %d exceeds credits.\n",
transferErrors.getIndex());
break;
default:
System.err.printf("Error creating transfer at %d: %s\n",
transferErrors.getIndex(), transferErrors.getResult());
break;
}
}
```
## Batching
TigerBeetle performance is maximized when you batch
API requests. The client does not do this automatically for
you. So, for example, you *can* insert 1 million transfers
one at a time like so:
```java
var transferIds = new long[] {100, 101, 102};
var debitIds = new long[] {1, 2, 3};
var creditIds = new long[] {4, 5, 6};
var amounts = new long[] {1000, 29, 11};
for (int i = 0; i < transferIds.length; i++) {
TransferBatch batch = new TransferBatch(1);
batch.add();
batch.setId(transferIds[i]);
batch.setDebitAccountId(debitIds[i]);
batch.setCreditAccountId(creditIds[i]);
batch.setAmount(amounts[i]);
CreateTransferResultBatch errors = client.createTransfers(batch);
// Error handling omitted.
}
```
But the insert rate will be a *fraction* of
potential. Instead, **always batch what you can**.
The maximum batch size is set in the TigerBeetle server. The default
is 8190.
```java
var BATCH_SIZE = 8190;
for (int i = 0; i < transferIds.length; i += BATCH_SIZE) {
TransferBatch batch = new TransferBatch(BATCH_SIZE);
for (int j = 0; j < BATCH_SIZE && i + j < transferIds.length; j++) {
batch.add();
batch.setId(transferIds[i + j]);
batch.setDebitAccountId(debitIds[i + j]);
batch.setCreditAccountId(creditIds[i + j]);
batch.setAmount(amounts[i + j]);
}
CreateTransferResultBatch errors = client.createTransfers(batch);
// 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 an account, combine enum values stored in the
`TransferFlags` object with bitwise-or:
* `TransferFlags.NONE`
* `TransferFlags.LINKED`
* `TransferFlags.PENDING`
* `TransferFlags.POST_PENDING_TRANSFER`
* `TransferFlags.VOID_PENDING_TRANSFER`
For example, to link `transfer0` and `transfer1`:
```java
transfers = new TransferBatch(2);
// First transfer
transfers.add();
// Code to fill out fields for first transfer
transfers.setFlags(TransferFlags.LINKED);
// Second transfer
transfers.add();
// Code to fill out fields for second transfer
transferErrors = client.createTransfers(transfers);
```
### 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.
```java
transfers = new TransferBatch(1);
// First transfer
transfers.add();
// Code to fill out fields for first transfer
transfers.setFlags(TransferFlags.POST_PENDING_TRANSFER);
// Post the entire pending amount.
transfers.setAmount(TransferBatch.AMOUNT_MAX);
transferErrors = client.createTransfers(transfers);
```
#### 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.
```java
transfers = new TransferBatch(1);
// First transfer
transfers.add();
// Code to fill out fields for first transfer
transfers.setFlags(TransferFlags.VOID_PENDING_TRANSFER);
transferErrors = client.createTransfers(transfers);
```
## 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.
```java
ids = new IdBatch(2);
ids.add(1);
ids.add(2);
transfers = client.lookupTransfers(ids);
```
## 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.
```java
AccountFilter filter = new AccountFilter();
filter.setAccountId(2);
filter.setTimestampMin(0); // No filter by Timestamp.
filter.setTimestampMax(0); // No filter by Timestamp.
filter.setLimit(10); // Limit to ten transfers at most.
filter.setDebits(true); // Include transfer from the debit side.
filter.setCredits(true); // Include transfer from the credit side.
filter.setReversed(true); // Sort by timestamp in reverse-chronological order.
transfers = client.getAccountTransfers(filter);
```
## 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.
```java
filter = new AccountFilter();
filter.setAccountId(2);
filter.setTimestampMin(0); // No filter by Timestamp.
filter.setTimestampMax(0); // No filter by Timestamp.
filter.setLimit(10); // Limit to ten balances at most.
filter.setDebits(true); // Include transfer from the debit side.
filter.setCredits(true); // Include transfer from the credit side.
filter.setReversed(true); // Sort by timestamp in reverse-chronological order.
AccountBalanceBatch account_balances = client.getAccountBalances(filter);
```
## 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.
```java
var query_filter = new QueryFilter();
query_filter.setUserData128(1000); // Filter by UserData.
query_filter.setUserData64(100);
query_filter.setUserData32(10);
query_filter.setCode(1); // Filter by Code.
query_filter.setLedger(0); // No filter by Ledger.
query_filter.setTimestampMin(0); // No filter by Timestamp.
query_filter.setTimestampMax(0); // No filter by Timestamp.
query_filter.setLimit(10); // Limit to ten balances at most.
query_filter.setReversed(true); // Sort by timestamp in reverse-chronological order.
AccountBatch query_accounts = client.queryAccounts(query_filter);
```
## 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.
```java
query_filter = new QueryFilter();
query_filter.setUserData128(1000); // Filter by UserData.
query_filter.setUserData64(100);
query_filter.setUserData32(10);
query_filter.setCode(1); // Filter by Code.
query_filter.setLedger(0); // No filter by Ledger.
query_filter.setTimestampMin(0); // No filter by Timestamp.
query_filter.setTimestampMax(0); // No filter by Timestamp.
query_filter.setLimit(10); // Limit to ten balances at most.
query_filter.setReversed(true); // Sort by timestamp in reverse-chronological order.
TransferBatch query_transfers = client.queryTransfers(query_filter);
```
## 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`.
```java
transfers = new TransferBatch(10);
// An individual transfer (successful):
transfers.add();
transfers.setId(1);
// A chain of 4 transfers (the last transfer in the chain closes the chain with
// linked=false):
transfers.add();
transfers.setId(2); // Commit/rollback.
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(3); // Commit/rollback.
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(2); // Fail with exists
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(4); // Fail without committing
// An individual transfer (successful):
// This should not see any effect from the failed chain above.
transfers.add();
transfers.setId(2);
// A chain of 2 transfers (the first transfer fails the chain):
transfers.add();
transfers.setId(2);
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(3);
// A chain of 2 transfers (successful):
transfers.add();
transfers.setId(3);
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(4);
transferErrors = client.createTransfers(transfers);
```
## 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.
```java
// First, load and import all accounts with their timestamps from the historical source.
accounts = new AccountBatch(historicalAccounts.length);
for(int index = 0; index < historicalAccounts.length; index += 1) {
accounts.add();
// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
accounts.setTimestamp(historicalTimestamp);
// Set the account as `imported`.
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalAccounts.length - 1) {
accounts.setFlags(AccountFlags.IMPORTED | AccountFlags.LINKED);
} else {
accounts.setFlags(AccountFlags.IMPORTED);
}
// Populate the rest of the account:
// accounts.setId(historicalAccounts[index].Id);
// accounts.setCode(historicalAccounts[index].Code);
}
accountErrors = client.createAccounts(accounts);
// Error handling omitted.
// Then, load and import all transfers with their timestamps from the historical source.
transfers = new TransferBatch(historicalTransfers.length);
for(int index = 0; index < historicalTransfers.length; index += 1) {
transfers.add();
// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
transfers.setTimestamp(historicalTimestamp);
// Set the account as `imported`.
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalTransfers.length - 1) {
transfers.setFlags(TransferFlags.IMPORTED | TransferFlags.LINKED);
} else {
transfers.setFlags(TransferFlags.IMPORTED);
}
// Populate the rest of the transfer:
// transfers.setId(historicalTransfers[index].Id);
// transfers.setCode(historicalTransfers[index].Code);
}
transferErrors = client.createTransfers(transfers);
// 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.
```
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/java/eclipse-formatter.xml | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<profiles version="13">
<profile kind="CodeFormatterProfile" name="tigerbeetle-java-style" version="13">
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_prefer_two_fragments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_comment_inline_tags" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_local_variable_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter" value="1040"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="49"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression.count_dependent" value="16|4|80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration.count_dependent" value="16|4|49"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments" value="16"/>
<setting id="org.eclipse.jdt.core.compiler.source" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_local_variable_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="100"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="16"/>
<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_type_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_field_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.comment_new_line_at_start_of_html_paragraph" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comment_prefix" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_parameter_annotation" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter.count_dependent" value="1040|-1|1040"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.force_if_else_statement_brace" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="3"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_package_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type" value="1585"/>
<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_new_anonymous_class" value="20"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="100"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_member_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_for_statement" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
</profile>
</profiles> |
0 | repos/tigerbeetle/src/clients/java/samples | repos/tigerbeetle/src/clients/java/samples/two-phase-many/pom.xml | <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tigerbeetle</groupId>
<artifactId>samples</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<arg>-Xlint:all,-options,-path</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>com.tigerbeetle.samples.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.tigerbeetle</groupId>
<artifactId>tigerbeetle-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
|
0 | repos/tigerbeetle/src/clients/java/samples | repos/tigerbeetle/src/clients/java/samples/two-phase-many/README.md | <!-- This file is generated by [/src/scripts/client_readmes.zig](/src/scripts/client_readmes.zig). -->
# Many Two-Phase Transfers Java Sample
Code for this sample is in [./src/main/java/Main.java](./src/main/java/Main.java).
## Prerequisites
Linux >= 5.6 is the only production environment we
support. But for ease of development we also support macOS and Windows.
* Java >= 11
* Maven >= 3.6 (not strictly necessary but it's what our guides assume)
## Setup
First, clone this repo and `cd` into `tigerbeetle/src/clients/java/samples/two-phase-many`.
Then, install the TigerBeetle client:
```console
mvn install
```
## Start the TigerBeetle server
Follow steps in the repo README to [run
TigerBeetle](/README.md#running-tigerbeetle).
If you are not running on port `localhost:3000`, set
the environment variable `TB_ADDRESS` to the full
address of the TigerBeetle server you started.
## Run this sample
Now you can run this sample:
```console
mvn exec:java
```
## Walkthrough
Here's what this project does.
## 1. Create accounts
This project starts by creating two accounts (`1` and `2`).
## 2. Create pending transfers
Then it begins 5 pending transfers of amounts `100` to
`500`, incrementing by `100` for each transfer.
## 3. Fetch and validate pending account balances
Then it fetches both accounts and validates that **account `1`** has:
* `debits_posted = 0`
* `credits_posted = 0`
* `debits_pending = 1500`
* and `credits_pending = 0`
And that **account `2`** has:
* `debits_posted = 0`
* `credits_posted = 0`
* `debits_pending = 0`
* and `credits_pending = 1500`
(This is because a pending transfer only affects **pending**
credits and debits on accounts, not **posted** credits and
debits.)
## 4. Post and void alternating transfers
Then it alternatively posts and voids each transfer,
checking account balances after each transfer.
## 6. Fetch and validate final account balances
Finally, it fetches both accounts, validates they both exist,
and checks that credits and debits for both account are now
solely *posted*, not pending.
Specifically, that **account `1`** has:
* `debits_posted = 900`
* `credits_posted = 0`
* `debits_pending = 0`
* and `credits_pending = 0`
And that **account `2`** has:
* `debits_posted = 0`
* `credits_posted = 900`
* `debits_pending = 0`
* and `credits_pending = 0`
|
0 | repos/tigerbeetle/src/clients/java/samples/two-phase-many/src/main | repos/tigerbeetle/src/clients/java/samples/two-phase-many/src/main/java/Main.java | package com.tigerbeetle.samples;
import java.util.Arrays;
import java.math.BigInteger;
import com.tigerbeetle.*;
public final class Main {
public static void main(String[] args) throws Exception {
String replicaAddress = System.getenv("TB_ADDRESS");
byte[] clusterID = UInt128.asBytes(0);
String[] replicaAddresses = new String[] {replicaAddress == null ? "3000" : replicaAddress};
try (var client = new Client(clusterID, replicaAddresses)) {
// Create two accounts
AccountBatch accounts = new AccountBatch(2);
accounts.add();
accounts.setId(1);
accounts.setLedger(1);
accounts.setCode(1);
accounts.add();
accounts.setId(2);
accounts.setLedger(1);
accounts.setCode(1);
CreateAccountResultBatch accountErrors = client.createAccounts(accounts);
while (accountErrors.next()) {
switch (accountErrors.getResult()) {
default:
System.err.printf("Error creating account %d: %s\n",
accountErrors.getIndex(),
accountErrors.getResult());
assert false;
}
}
// Start five pending transfer.
TransferBatch transfers = new TransferBatch(5);
transfers.add();
transfers.setId(1);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(500);
transfers.setFlags(TransferFlags.PENDING);
transfers.add();
transfers.setId(2);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(200);
transfers.setFlags(TransferFlags.PENDING);
transfers.add();
transfers.setId(3);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(300);
transfers.setFlags(TransferFlags.PENDING);
transfers.add();
transfers.setId(4);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(400);
transfers.setFlags(TransferFlags.PENDING);
transfers.add();
transfers.setId(5);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(500);
transfers.setFlags(TransferFlags.PENDING);
CreateTransferResultBatch transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
// Validate accounts pending and posted debits/credits
// before finishing the two-phase transfer.
IdBatch ids = new IdBatch(2);
ids.add(1);
ids.add(2);
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 0;
assert accounts.getDebitsPending().intValueExact() == 500;
assert accounts.getCreditsPending().intValueExact() == 0;
} else if (Arrays.equals(accounts.getId(), UInt128.asBytes(2))) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 0;
assert accounts.getDebitsPending().intValueExact() == 0;
assert accounts.getCreditsPending().intValueExact() == 500;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
// Create a 6th transfer posting the 1st transfer.
transfers = new TransferBatch(1);
transfers.add();
transfers.setId(6);
transfers.setPendingId(1);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(100);
transfers.setFlags(TransferFlags.POST_PENDING_TRANSFER);
transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
// Validate account balances after posting 1st pending transfer.
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 100;
assert accounts.getCreditsPosted().intValueExact() == 0;
assert accounts.getDebitsPending().intValueExact() == 1400;
assert accounts.getCreditsPending().intValueExact() == 0;
} else if (accounts.getId(UInt128.LeastSignificant) == 2
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 100;
assert accounts.getDebitsPending().intValueExact() == 0;
assert accounts.getCreditsPending().intValueExact() == 1400;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
// Create a 6th transfer voiding the 2nd transfer.
transfers = new TransferBatch(1);
transfers.add();
transfers.setId(7);
transfers.setPendingId(2);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(200);
transfers.setFlags(TransferFlags.VOID_PENDING_TRANSFER);
transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
// Validate account balances after voiding 2nd pending transfer.
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 100;
assert accounts.getCreditsPosted().intValueExact() == 0;
assert accounts.getDebitsPending().intValueExact() == 1200;
assert accounts.getCreditsPending().intValueExact() == 0;
} else if (accounts.getId(UInt128.LeastSignificant) == 2
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 100;
assert accounts.getDebitsPending().intValueExact() == 0;
assert accounts.getCreditsPending().intValueExact() == 1200;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
// Create an 8th transfer posting the 3rd transfer.
transfers = new TransferBatch(1);
transfers.add();
transfers.setId(8);
transfers.setPendingId(3);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(300);
transfers.setFlags(TransferFlags.POST_PENDING_TRANSFER);
transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
// Validate account balances after posting 3rd pending transfer.
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValue() == 400;
assert accounts.getCreditsPosted().intValue() == 0;
assert accounts.getDebitsPending().intValue() == 900;
assert accounts.getCreditsPending().intValue() == 0;
} else if (accounts.getId(UInt128.LeastSignificant) == 2
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValue() == 0;
assert accounts.getCreditsPosted().intValue() == 400;
assert accounts.getDebitsPending().intValue() == 0;
assert accounts.getCreditsPending().intValue() == 900;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
// Create a 9th transfer voiding the 4th transfer.
transfers = new TransferBatch(1);
transfers.add();
transfers.setId(9);
transfers.setPendingId(4);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(400);
transfers.setFlags(TransferFlags.VOID_PENDING_TRANSFER);
transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
// Validate account balances after voiding 4th pending transfer.
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValue() == 400;
assert accounts.getCreditsPosted().intValue() == 0;
assert accounts.getDebitsPending().intValue() == 500;
assert accounts.getCreditsPending().intValue() == 0;
} else if (accounts.getId(UInt128.LeastSignificant) == 2
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValue() == 0;
assert accounts.getCreditsPosted().intValue() == 400;
assert accounts.getDebitsPending().intValue() == 0;
assert accounts.getCreditsPending().intValue() == 500;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
// Create a 10th transfer posting the 5th transfer.
transfers = new TransferBatch(1);
transfers.add();
transfers.setId(6);
transfers.setPendingId(1);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(100);
transfers.setFlags(TransferFlags.POST_PENDING_TRANSFER);
transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
// Validate account balances after posting 5th pending transfer.
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 900;
assert accounts.getCreditsPosted().intValueExact() == 0;
assert accounts.getDebitsPending().intValueExact() == 0;
assert accounts.getCreditsPending().intValueExact() == 0;
} else if (accounts.getId(UInt128.LeastSignificant) == 2
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 900;
assert accounts.getDebitsPending().intValueExact() == 0;
assert accounts.getCreditsPending().intValueExact() == 0;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
}
}
}
|
0 | repos/tigerbeetle/src/clients/java/samples | repos/tigerbeetle/src/clients/java/samples/basic/pom.xml | <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tigerbeetle</groupId>
<artifactId>samples</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<arg>-Xlint:all,-options,-path</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>com.tigerbeetle.samples.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.tigerbeetle</groupId>
<artifactId>tigerbeetle-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
|
0 | repos/tigerbeetle/src/clients/java/samples | repos/tigerbeetle/src/clients/java/samples/basic/README.md | <!-- This file is generated by [/src/scripts/client_readmes.zig](/src/scripts/client_readmes.zig). -->
# Basic Java Sample
Code for this sample is in [./src/main/java/Main.java](./src/main/java/Main.java).
## Prerequisites
Linux >= 5.6 is the only production environment we
support. But for ease of development we also support macOS and Windows.
* Java >= 11
* Maven >= 3.6 (not strictly necessary but it's what our guides assume)
## Setup
First, clone this repo and `cd` into `tigerbeetle/src/clients/java/samples/basic`.
Then, install the TigerBeetle client:
```console
mvn install
```
## Start the TigerBeetle server
Follow steps in the repo README to [run
TigerBeetle](/README.md#running-tigerbeetle).
If you are not running on port `localhost:3000`, set
the environment variable `TB_ADDRESS` to the full
address of the TigerBeetle server you started.
## Run this sample
Now you can run this sample:
```console
mvn exec:java
```
## Walkthrough
Here's what this project does.
## 1. Create accounts
This project starts by creating two accounts (`1` and `2`).
## 2. Create a transfer
Then it transfers `10` of an amount from account `1` to
account `2`.
## 3. Fetch and validate account balances
Then it fetches both accounts, checks they both exist, and
checks that **account `1`** has:
* `debits_posted = 10`
* and `credits_posted = 0`
And that **account `2`** has:
* `debits_posted= 0`
* and `credits_posted = 10`
|
0 | repos/tigerbeetle/src/clients/java/samples/basic/src/main | repos/tigerbeetle/src/clients/java/samples/basic/src/main/java/Main.java | package com.tigerbeetle.samples;
import java.util.Arrays;
import java.math.BigInteger;
import com.tigerbeetle.*;
public final class Main {
public static void main(String[] args) throws Exception {
String replicaAddress = System.getenv("TB_ADDRESS");
byte[] clusterID = UInt128.asBytes(0);
String[] replicaAddresses = new String[] {replicaAddress == null ? "3000" : replicaAddress};
try (var client = new Client(clusterID, replicaAddresses)) {
// Create two accounts
AccountBatch accounts = new AccountBatch(2);
accounts.add();
accounts.setId(1);
accounts.setLedger(1);
accounts.setCode(1);
accounts.add();
accounts.setId(2);
accounts.setLedger(1);
accounts.setCode(1);
CreateAccountResultBatch accountErrors = client.createAccounts(accounts);
while (accountErrors.next()) {
switch (accountErrors.getResult()) {
default:
System.err.printf("Error creating account %d: %s\n",
accountErrors.getIndex(),
accountErrors.getResult());
assert false;
}
}
TransferBatch transfers = new TransferBatch(1);
transfers.add();
transfers.setId(1);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(10);
CreateTransferResultBatch transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
IdBatch ids = new IdBatch(2);
ids.add(1);
ids.add(2);
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 10;
assert accounts.getCreditsPosted().intValueExact() == 0;
} else if (accounts.getId(UInt128.LeastSignificant) == 2
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 10;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
}
}
}
|
0 | repos/tigerbeetle/src/clients/java/samples | repos/tigerbeetle/src/clients/java/samples/walkthrough/pom.xml | <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tigerbeetle</groupId>
<artifactId>samples</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<arg>-Xlint:all,-options,-path</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>com.tigerbeetle.samples.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.tigerbeetle</groupId>
<artifactId>tigerbeetle-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
|
0 | repos/tigerbeetle/src/clients/java/samples | repos/tigerbeetle/src/clients/java/samples/walkthrough/README.md | Code from the [top-level README.md](../../README.md) collected into a single runnable project.
|
0 | repos/tigerbeetle/src/clients/java/samples/walkthrough/src/main | repos/tigerbeetle/src/clients/java/samples/walkthrough/src/main/java/Main.java | // section:imports
package com.tigerbeetle.samples;
import com.tigerbeetle.*;
public final class Main {
public static void main(String[] args) throws Exception {
System.out.println("Import ok!");
// endsection:imports
// section:client
String replicaAddress = System.getenv("TB_ADDRESS");
byte[] clusterID = UInt128.asBytes(0);
String[] replicaAddresses = new String[] {replicaAddress == null ? "3000" : replicaAddress};
try (var client = new Client(clusterID, replicaAddresses)) {
// Use client
}
// endsection:client
try (var client = new Client(clusterID, replicaAddresses)) {
// section:create-accounts
AccountBatch accounts = new AccountBatch(1);
accounts.add();
accounts.setId(137);
accounts.setUserData128(UInt128.asBytes(java.util.UUID.randomUUID()));
accounts.setUserData64(1234567890);
accounts.setUserData32(42);
accounts.setLedger(1);
accounts.setCode(718);
accounts.setFlags(0);
CreateAccountResultBatch accountErrors = client.createAccounts(accounts);
// endsection:create-accounts
// section:account-flags
accounts = new AccountBatch(3);
// First account
accounts.add();
// Code to fill out fields for first account
accounts.setFlags(AccountFlags.LINKED | AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS);
// Second account
accounts.add();
// Code to fill out fields for second account
accountErrors = client.createAccounts(accounts);
// endsection:account-flags
// section:create-accounts-errors
while (accountErrors.next()) {
switch (accountErrors.getResult()) {
case Exists:
System.err.printf("Account at %d already exists.\n",
accountErrors.getIndex());
break;
default:
System.err.printf("Error creating account at %d: %s\n",
accountErrors.getIndex(), accountErrors.getResult());
break;
}
}
// endsection:create-accounts-errors
// section:lookup-accounts
IdBatch ids = new IdBatch(2);
ids.add(137);
ids.add(138);
accounts = client.lookupAccounts(ids);
// endsection:lookup-accounts
// section:create-transfers
TransferBatch transfers = new TransferBatch(1);
transfers.add();
transfers.setId(1);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setAmount(10);
transfers.setUserData128(UInt128.asBytes(java.util.UUID.randomUUID()));
transfers.setUserData64(1234567890);
transfers.setUserData32(42);
transfers.setTimeout(0);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setFlags(0);
CreateTransferResultBatch transferErrors = client.createTransfers(transfers);
// endsection:create-transfers
// section:create-transfers-errors
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
case ExceedsCredits:
System.err.printf("Transfer at %d exceeds credits.\n",
transferErrors.getIndex());
break;
default:
System.err.printf("Error creating transfer at %d: %s\n",
transferErrors.getIndex(), transferErrors.getResult());
break;
}
}
// endsection:create-transfers-errors
// section:no-batch
var transferIds = new long[] {100, 101, 102};
var debitIds = new long[] {1, 2, 3};
var creditIds = new long[] {4, 5, 6};
var amounts = new long[] {1000, 29, 11};
for (int i = 0; i < transferIds.length; i++) {
TransferBatch batch = new TransferBatch(1);
batch.add();
batch.setId(transferIds[i]);
batch.setDebitAccountId(debitIds[i]);
batch.setCreditAccountId(creditIds[i]);
batch.setAmount(amounts[i]);
CreateTransferResultBatch errors = client.createTransfers(batch);
// Error handling omitted.
}
// endsection:no-batch
// section:batch
var BATCH_SIZE = 8190;
for (int i = 0; i < transferIds.length; i += BATCH_SIZE) {
TransferBatch batch = new TransferBatch(BATCH_SIZE);
for (int j = 0; j < BATCH_SIZE && i + j < transferIds.length; j++) {
batch.add();
batch.setId(transferIds[i + j]);
batch.setDebitAccountId(debitIds[i + j]);
batch.setCreditAccountId(creditIds[i + j]);
batch.setAmount(amounts[i + j]);
}
CreateTransferResultBatch errors = client.createTransfers(batch);
// Error handling omitted.
}
// endsection:batch
// section:transfer-flags-link
transfers = new TransferBatch(2);
// First transfer
transfers.add();
// Code to fill out fields for first transfer
transfers.setFlags(TransferFlags.LINKED);
// Second transfer
transfers.add();
// Code to fill out fields for second transfer
transferErrors = client.createTransfers(transfers);
// endsection:transfer-flags-link
// section:transfer-flags-post
transfers = new TransferBatch(1);
// First transfer
transfers.add();
// Code to fill out fields for first transfer
transfers.setFlags(TransferFlags.POST_PENDING_TRANSFER);
// Post the entire pending amount.
transfers.setAmount(TransferBatch.AMOUNT_MAX);
transferErrors = client.createTransfers(transfers);
// endsection:transfer-flags-post
// section:transfer-flags-void
transfers = new TransferBatch(1);
// First transfer
transfers.add();
// Code to fill out fields for first transfer
transfers.setFlags(TransferFlags.VOID_PENDING_TRANSFER);
transferErrors = client.createTransfers(transfers);
// endsection:transfer-flags-void
// section:lookup-transfers
ids = new IdBatch(2);
ids.add(1);
ids.add(2);
transfers = client.lookupTransfers(ids);
// endsection:lookup-transfers
// section:get-account-transfers
AccountFilter filter = new AccountFilter();
filter.setAccountId(2);
filter.setTimestampMin(0); // No filter by Timestamp.
filter.setTimestampMax(0); // No filter by Timestamp.
filter.setLimit(10); // Limit to ten transfers at most.
filter.setDebits(true); // Include transfer from the debit side.
filter.setCredits(true); // Include transfer from the credit side.
filter.setReversed(true); // Sort by timestamp in reverse-chronological order.
transfers = client.getAccountTransfers(filter);
// endsection:get-account-transfers
// section:get-account-balances
filter = new AccountFilter();
filter.setAccountId(2);
filter.setTimestampMin(0); // No filter by Timestamp.
filter.setTimestampMax(0); // No filter by Timestamp.
filter.setLimit(10); // Limit to ten balances at most.
filter.setDebits(true); // Include transfer from the debit side.
filter.setCredits(true); // Include transfer from the credit side.
filter.setReversed(true); // Sort by timestamp in reverse-chronological order.
AccountBalanceBatch account_balances = client.getAccountBalances(filter);
// endsection:get-account-balances
// section:query-accounts
var query_filter = new QueryFilter();
query_filter.setUserData128(1000); // Filter by UserData.
query_filter.setUserData64(100);
query_filter.setUserData32(10);
query_filter.setCode(1); // Filter by Code.
query_filter.setLedger(0); // No filter by Ledger.
query_filter.setTimestampMin(0); // No filter by Timestamp.
query_filter.setTimestampMax(0); // No filter by Timestamp.
query_filter.setLimit(10); // Limit to ten balances at most.
query_filter.setReversed(true); // Sort by timestamp in reverse-chronological order.
AccountBatch query_accounts = client.queryAccounts(query_filter);
// endsection:query-accounts
// section:query-transfers
query_filter = new QueryFilter();
query_filter.setUserData128(1000); // Filter by UserData.
query_filter.setUserData64(100);
query_filter.setUserData32(10);
query_filter.setCode(1); // Filter by Code.
query_filter.setLedger(0); // No filter by Ledger.
query_filter.setTimestampMin(0); // No filter by Timestamp.
query_filter.setTimestampMax(0); // No filter by Timestamp.
query_filter.setLimit(10); // Limit to ten balances at most.
query_filter.setReversed(true); // Sort by timestamp in reverse-chronological order.
TransferBatch query_transfers = client.queryTransfers(query_filter);
// endsection:query-transfers
// section:linked-events
transfers = new TransferBatch(10);
// An individual transfer (successful):
transfers.add();
transfers.setId(1);
// A chain of 4 transfers (the last transfer in the chain closes the chain with
// linked=false):
transfers.add();
transfers.setId(2); // Commit/rollback.
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(3); // Commit/rollback.
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(2); // Fail with exists
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(4); // Fail without committing
// An individual transfer (successful):
// This should not see any effect from the failed chain above.
transfers.add();
transfers.setId(2);
// A chain of 2 transfers (the first transfer fails the chain):
transfers.add();
transfers.setId(2);
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(3);
// A chain of 2 transfers (successful):
transfers.add();
transfers.setId(3);
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(4);
transferErrors = client.createTransfers(transfers);
// endsection:linked-events
// External source of time
long historicalTimestamp = 0L;
Object[] historicalAccounts = new Object[1];
Object[] historicalTransfers = new Object[1];
// section:imported-events
// First, load and import all accounts with their timestamps from the historical source.
accounts = new AccountBatch(historicalAccounts.length);
for(int index = 0; index < historicalAccounts.length; index += 1) {
accounts.add();
// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
accounts.setTimestamp(historicalTimestamp);
// Set the account as `imported`.
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalAccounts.length - 1) {
accounts.setFlags(AccountFlags.IMPORTED | AccountFlags.LINKED);
} else {
accounts.setFlags(AccountFlags.IMPORTED);
}
// Populate the rest of the account:
// accounts.setId(historicalAccounts[index].Id);
// accounts.setCode(historicalAccounts[index].Code);
}
accountErrors = client.createAccounts(accounts);
// Error handling omitted.
// Then, load and import all transfers with their timestamps from the historical source.
transfers = new TransferBatch(historicalTransfers.length);
for(int index = 0; index < historicalTransfers.length; index += 1) {
transfers.add();
// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
transfers.setTimestamp(historicalTimestamp);
// Set the account as `imported`.
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalTransfers.length - 1) {
transfers.setFlags(TransferFlags.IMPORTED | TransferFlags.LINKED);
} else {
transfers.setFlags(TransferFlags.IMPORTED);
}
// Populate the rest of the transfer:
// transfers.setId(historicalTransfers[index].Id);
// transfers.setCode(historicalTransfers[index].Code);
}
transferErrors = client.createTransfers(transfers);
// 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.
// endsection:imported-events
}
// section:imports
}
}
// endsection:imports
|
0 | repos/tigerbeetle/src/clients/java/samples | repos/tigerbeetle/src/clients/java/samples/two-phase/pom.xml | <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tigerbeetle</groupId>
<artifactId>samples</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<arg>-Xlint:all,-options,-path</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>com.tigerbeetle.samples.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.tigerbeetle</groupId>
<artifactId>tigerbeetle-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
|
0 | repos/tigerbeetle/src/clients/java/samples | repos/tigerbeetle/src/clients/java/samples/two-phase/README.md | <!-- This file is generated by [/src/scripts/client_readmes.zig](/src/scripts/client_readmes.zig). -->
# Two-Phase Transfer Java Sample
Code for this sample is in [./src/main/java/Main.java](./src/main/java/Main.java).
## Prerequisites
Linux >= 5.6 is the only production environment we
support. But for ease of development we also support macOS and Windows.
* Java >= 11
* Maven >= 3.6 (not strictly necessary but it's what our guides assume)
## Setup
First, clone this repo and `cd` into `tigerbeetle/src/clients/java/samples/two-phase`.
Then, install the TigerBeetle client:
```console
mvn install
```
## Start the TigerBeetle server
Follow steps in the repo README to [run
TigerBeetle](/README.md#running-tigerbeetle).
If you are not running on port `localhost:3000`, set
the environment variable `TB_ADDRESS` to the full
address of the TigerBeetle server you started.
## Run this sample
Now you can run this sample:
```console
mvn exec:java
```
## Walkthrough
Here's what this project does.
## 1. Create accounts
This project starts by creating two accounts (`1` and `2`).
## 2. Create pending transfer
Then it begins a
pending transfer of `500` of an amount from account `1` to
account `2`.
## 3. Fetch and validate pending account balances
Then it fetches both accounts and validates that **account `1`** has:
* `debits_posted = 0`
* `credits_posted = 0`
* `debits_pending = 500`
* and `credits_pending = 0`
And that **account `2`** has:
* `debits_posted = 0`
* `credits_posted = 0`
* `debits_pending = 0`
* and `credits_pending = 500`
(This is because a pending
transfer only affects **pending** credits and debits on accounts,
not **posted** credits and debits.)
## 4. Post pending transfer
Then it creates a second transfer that marks the first
transfer as posted.
## 5. Fetch and validate transfers
Then it fetches both transfers, validates
that the two transfers exist, validates that the first
transfer had (and still has) a `pending` flag, and validates
that the second transfer had (and still has) a
`post_pending_transfer` flag.
## 6. Fetch and validate final account balances
Finally, it fetches both accounts, validates they both exist,
and checks that credits and debits for both account are now
*posted*, not pending.
Specifically, that **account `1`** has:
* `debits_posted = 500`
* `credits_posted = 0`
* `debits_pending = 0`
* and `credits_pending = 0`
And that **account `2`** has:
* `debits_posted = 0`
* `credits_posted = 500`
* `debits_pending = 0`
* and `credits_pending = 0`
|
0 | repos/tigerbeetle/src/clients/java/samples/two-phase/src/main | repos/tigerbeetle/src/clients/java/samples/two-phase/src/main/java/Main.java | package com.tigerbeetle.samples;
import java.util.Arrays;
import java.util.UUID;
import java.math.BigInteger;
import com.tigerbeetle.*;
public final class Main {
public static void main(String[] args) throws Exception {
String replicaAddress = System.getenv("TB_ADDRESS");
byte[] clusterID = UInt128.asBytes(0);
String[] replicaAddresses = new String[] {replicaAddress == null ? "3000" : replicaAddress};
try (var client = new Client(clusterID, replicaAddresses)) {
// Create two accounts
AccountBatch accounts = new AccountBatch(2);
accounts.add();
accounts.setId(1);
accounts.setLedger(1);
accounts.setCode(1);
accounts.add();
accounts.setId(2);
accounts.setLedger(1);
accounts.setCode(1);
CreateAccountResultBatch accountErrors = client.createAccounts(accounts);
while (accountErrors.next()) {
switch (accountErrors.getResult()) {
default:
System.err.printf("Error creating account %d: %s\n",
accountErrors.getIndex(),
accountErrors.getResult());
assert false;
}
}
// Start a pending transfer
TransferBatch transfers = new TransferBatch(1);
transfers.add();
transfers.setId(1);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(500);
transfers.setFlags(TransferFlags.PENDING);
CreateTransferResultBatch transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
// Validate accounts pending and posted debits/credits before finishing the
// two-phase transfer
IdBatch ids = new IdBatch(2);
ids.add(1);
ids.add(2);
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 0;
assert accounts.getDebitsPending().intValueExact() == 500;
assert accounts.getCreditsPending().intValueExact() == 0;
} else if (accounts.getId(UInt128.LeastSignificant) == 2
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 0;
assert accounts.getDebitsPending().intValueExact() == 0;
assert accounts.getCreditsPending().intValueExact() == 500;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
// Create a second transfer simply posting the first transfer
transfers = new TransferBatch(1);
transfers.add();
transfers.setId(2);
transfers.setPendingId(1);
transfers.setDebitAccountId(1);
transfers.setCreditAccountId(2);
transfers.setLedger(1);
transfers.setCode(1);
transfers.setAmount(500);
transfers.setFlags(TransferFlags.POST_PENDING_TRANSFER);
transferErrors = client.createTransfers(transfers);
while (transferErrors.next()) {
switch (transferErrors.getResult()) {
default:
System.err.printf("Error creating transfer %d: %s\n",
transferErrors.getIndex(),
transferErrors.getResult());
assert false;
}
}
// Validate accounts pending and posted debits/credits after finishing the
// two-phase transfer
ids = new IdBatch(2);
ids.add(1);
ids.add(2);
accounts = client.lookupAccounts(ids);
assert accounts.getCapacity() == 2;
while (accounts.next()) {
if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 500;
assert accounts.getCreditsPosted().intValueExact() == 0;
assert accounts.getDebitsPending().intValueExact() == 0;
assert accounts.getCreditsPending().intValueExact() == 0;
} else if (accounts.getId(UInt128.LeastSignificant) == 1
&& accounts.getId(UInt128.MostSignificant) == 0) {
assert accounts.getDebitsPosted().intValueExact() == 0;
assert accounts.getCreditsPosted().intValueExact() == 500;
assert accounts.getDebitsPending().intValueExact() == 0;
assert accounts.getCreditsPending().intValueExact() == 0;
} else {
System.err.printf("Unexpected account: %s\n",
UInt128.asBigInteger(accounts.getId()).toString());
assert false;
}
}
}
}
}
|
0 | repos/tigerbeetle/src/clients/java | repos/tigerbeetle/src/clients/java/src/jni.zig | ///! Based on Java Native Interface Specification and Java Invocation API.
///! https://docs.oracle.com/en/java/javase/17/docs/specs/jni.
///!
///! We don't rely on @import("jni.h") to translate the JNI declarations by several factors:
///! - Ability to rewrite it using our naming convention and idiomatic Zig pointers
///! such as ?*, [*], [*:0], ?[*].
///! - Great stability of the JNI specification makes manual implementation a viable option.
///! - Licensing issues redistributing the jni.h file (or even translating it).
///! - To avoid duplicated function definitions by using comptime generated signatures
///! when calling the function table.
///! - To mitigate the risk of human error by using explicit vtable indexes instead of a
///! struct of function pointers sensitive to the fields ordering.
///!
///! Additionally, each function is unit tested against a real JVM to validate if they are
///! calling the correct vtable entry with the expected arguments.
const std = @import("std");
/// JNI calling convention.
pub const JNICALL: std.builtin.CallingConvention = .C;
// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getversion.
pub const jni_version_1_1: JInt = 0x00010001;
pub const jni_version_1_2: JInt = 0x00010002;
pub const jni_version_1_4: JInt = 0x00010004;
pub const jni_version_1_6: JInt = 0x00010006;
pub const jni_version_1_8: JInt = 0x00010008;
pub const jni_version_9: JInt = 0x00090000;
pub const jni_version_10: JInt = 0x000a0000;
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#return-codes.
pub const JNIResultType = enum(JInt) {
/// Success.
ok = 0,
/// Unknown error.
unknown = -1,
/// Thread detached from the VM.
thread_detached = -2,
/// JNI version error.
bad_version = -3,
/// Not enough memory.
out_of_memory = -4,
/// VM already created.
vm_already_exists = -5,
/// Invalid arguments.
invalid_arguments = -6,
/// Non exhaustive enum.
_,
};
// Primitive types:
// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/types.html#primitive-types.
pub const JBoolean = enum(u8) { jni_true = 1, jni_false = 0 };
pub const JByte = i8;
pub const JChar = u16;
pub const JShort = i16;
pub const JInt = i32;
pub const JLong = i64;
pub const JFloat = f32;
pub const JDouble = f64;
pub const JSize = JInt;
// Reference types:
// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/types.html#reference-types.
pub const JObject = ?*opaque {};
pub const JClass = JObject;
pub const JThrowable = JObject;
pub const JString = JObject;
pub const JArray = JObject;
pub const JBooleanArray = JArray;
pub const JByteArray = JArray;
pub const JCharArray = JArray;
pub const JShortArray = JArray;
pub const JIntArray = JArray;
pub const JLongArray = JArray;
pub const JFloatArray = JArray;
pub const JDoubleArray = JArray;
pub const JObjectArray = JArray;
pub const JWeakReference = JObject;
// Method and field IDs:
// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/types.html#field-and-method-ids.
pub const JFieldID = ?*opaque {};
pub const JMethodID = ?*opaque {};
/// This union is used as the element type in argument arrays.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/types.html#the-value-type.
pub const JValue = extern union {
object: JObject,
boolean: JBoolean,
byte: JByte,
char: JChar,
short: JShort,
int: JInt,
long: JLong,
float: JFloat,
double: JDouble,
pub fn to_jvalue(value: anytype) JValue {
return switch (@TypeOf(value)) {
JBoolean => .{ .boolean = value },
JByte => .{ .byte = value },
JChar => .{ .char = value },
JShort => .{ .short = value },
JInt => .{ .int = value },
JLong => .{ .long = value },
JFloat => .{ .float = value },
JDouble => .{ .double = value },
JObject => .{ .object = value },
else => unreachable,
};
}
};
/// Mode has no effect if elems is not a copy of the elements in array.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub const JArrayReleaseMode = enum(JInt) {
/// Copy back the content and free the elems buffer.
default = 0,
/// Copy back the content but do not free the elems buffer.
commit = 1,
/// Free the buffer without copying back the possible changes.
abort = 2,
};
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getobjectreftype.
pub const JObjectRefType = enum(JInt) {
invalid = 0,
local = 1,
global = 2,
weak_global = 3,
_,
};
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#registernatives.
pub const JNINativeMethod = extern struct {
name: [*:0]const u8,
signature: [*:0]const u8,
fn_ptr: ?*anyopaque,
};
pub const JNIEnv = opaque {
/// Each function is accessible at a fixed offset through the JNIEnv argument.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#interface-function-table.
const FunctionTable = enum(usize) {
/// Index 4: GetVersion
get_version = 4,
/// Index 5: DefineClass
define_class = 5,
/// Index 6: FindClass
find_class = 6,
/// Index 7: FromReflectedMethod
from_reflected_method = 7,
/// Index 8: FromReflectedField
from_feflected_field = 8,
/// Index 9: ToReflectedMethod
to_reflected_method = 9,
/// Index 10: GetSuperclass
get_super_class = 10,
/// Index 11: IsAssignableFrom
is_assignable_from = 11,
/// Index 12: ToReflectedField
to_reflected_field = 12,
/// Index 13: Throw
throw = 13,
/// Index 14: ThrowNew
throw_new = 14,
/// Index 15: ExceptionOccurred
exception_occurred = 15,
/// Index 16: ExceptionDescribe
exception_describe = 16,
/// Index 17: ExceptionClear
exception_clear = 17,
/// Index 18: FatalError
fatal_error = 18,
/// Index 19: PushLocalFrame
push_local_frame = 19,
/// Index 20: PopLocalFrame
pop_local_frame = 20,
/// Index 21: NewGlobalRef
new_global_ref = 21,
/// Index 22: DeleteGlobalRef
delete_global_ref = 22,
/// Index 23: DeleteLocalRef
delete_local_ref = 23,
/// Index 24: IsSameObject
is_same_object = 24,
/// Index 25: NewLocalRef
new_local_ref = 25,
/// Index 26: EnsureLocalCapacity
ensure_local_capacity = 26,
/// Index 27: AllocObject
alloc_object = 27,
/// Index 28: NewObject
/// Index 29: NewObjectV
/// Index 30: NewObjectA
new_object = 30,
/// Index 31: GetObjectClass
get_object_class = 31,
/// Index 32: IsInstanceOf
is_instance_of = 32,
/// Index 33: GetMethodID
get_method_id = 33,
/// Index 34: CallObjectMethod (omitted)
/// Index 35: CallObjectMethodV (omitted)
/// Index 36: CallObjectMethodA
call_object_method = 36,
/// Index 37: CallBooleanMethod (omitted)
/// Index 38: CallBooleanMethodV (omitted)
/// Index 39: CallBooleanMethodA
call_boolean_method = 39,
/// Index 40: CallByteMethod (omitted)
/// Index 41: CallByteMethodV (omitted)
/// Index 42: CallByteMethodA
call_byte_method = 42,
/// Index 43: CallCharMethod (omitted)
/// Index 44: CallCharMethodV (omitted)
/// Index 45: CallCharMethodA
call_char_method = 45,
/// Index 46: CallShortMethod (omitted)
/// Index 47: CallShortMethodV (omitted)
/// Index 48: CallShortMethodA
call_short_method = 48,
/// Index 49: CallIntMethod (omitted)
/// Index 50: CallIntMethodV (omitted)
/// Index 51: CallIntMethodA
call_int_method = 51,
/// Index 52: CallLongMethod (omitted)
/// Index 53: CallLongMethodV (omitted)
/// Index 54: CallLongMethodA
call_long_method = 54,
/// Index 55: CallFloatMethod (omitted)
/// Index 56: CallFloatMethodV (omitted)
/// Index 57: CallFloatMethodA
call_float_method = 57,
/// Index 58: CallDoubleMethod (omitted)
/// Index 59: CallDoubleMethodV (omitted)
/// Index 60: CallDoubleMethodA
call_double_method = 60,
/// Index 61: CallVoidMethod (omitted)
/// Index 62: CallVoidMethodV (omitted)
/// Index 63: CallVoidMethodA
call_void_method = 63,
/// Index 64: CallNonvirtualObjectMethod (omitted)
/// Index 65: CallNonvirtualObjectMethodV (omitted)
/// Index 66: CallNonvirtualObjectMethodA (omitted)
call_nonvirtual_object_method = 66,
/// Index 67: CallNonvirtualBooleanMethod (omitted)
/// Index 68: CallNonvirtualBooleanMethodV (omitted)
/// Index 69: CallNonvirtualBooleanMethodA (omitted)
call_nonvirtual_boolean_method = 69,
/// Index 70: CallNonvirtualByteMethod (omitted)
/// Index 71: CallNonvirtualByteMethodV (omitted)
/// Index 72: CallNonvirtualByteMethodA (omitted)
call_nonvirtual_byte_method = 72,
/// Index 73: CallNonvirtualCharMethod (omitted)
/// Index 74: CallNonvirtualCharMethodV (omitted)
/// Index 75: CallNonvirtualCharMethodA (omitted)
call_nonvirtual_char_method = 75,
/// Index 76: CallNonvirtualShortMethod (omitted)
/// Index 77: CallNonvirtualShortMethodV (omitted)
/// Index 78: CallNonvirtualShortMethodA (omitted)
call_nonvirtual_short_method = 78,
/// Index 79: CallNonvirtualIntMethod (omitted)
/// Index 80: CallNonvirtualIntMethodV (omitted)
/// Index 81: CallNonvirtualIntMethodA (omitted)
call_nonvirtual_int_method = 81,
/// Index 82: CallNonvirtualLongMethod (omitted)
/// Index 83: CallNonvirtualLongMethodV (omitted)
/// Index 84: CallNonvirtualLongMethodA (omitted)
call_nonvirtual_long_method = 84,
/// Index 85: CallNonvirtualFloatMethod (omitted)
/// Index 86: CallNonvirtualFloatMethodV (omitted)
/// Index 87: CallNonvirtualFloatMethodA (omitted)
call_nonvirtual_float_method = 87,
/// Index 88: CallNonvirtualDoubleMethod (omitted)
/// Index 89: CallNonvirtualDoubleMethodV (omitted)
/// Index 90: CallNonvirtualDoubleMethodA (omitted)
call_nonvirtual_double_method = 90,
/// Index 91: CallNonvirtualVoidMethod (omitted)
/// Index 92: CallNonvirtualVoidMethodV (omitted)
/// Index 93: CallNonvirtualVoidMethodA (omitted)
call_nonvirtual_void_method = 93,
/// Index 94: GetFieldID
get_field_id = 94,
/// Index 95: GetObjectField
get_object_field = 95,
/// Index 96: GetBooleanField
get_boolean_field = 96,
/// Index 97: GetByteField
get_byte_field = 97,
/// Index 98: GetCharField
get_char_field = 98,
/// Index 99: GetShortField
get_short_field = 99,
/// Index 100: GetIntField
get_int_field = 100,
/// Index 101: GetLongField
get_long_field = 101,
/// Index 102: GetFloatField
get_float_field = 102,
/// Index 103: GetDoubleField
get_double_field = 103,
/// Index 104: SetObjectField
set_object_field = 104,
/// Index 105: SetBooleanField
set_boolean_field = 105,
/// Index 106: SetByteField
set_byte_field = 106,
/// Index 107: SetCharField
set_char_field = 107,
/// Index 108: SetShortField
set_short_field = 108,
/// Index 109: SetIntField
set_int_field = 109,
/// Index 110: SetLongField
set_long_field = 110,
/// Index 111: SetFloatField
set_float_field = 111,
/// Index 112: SetDoubleField
set_double_field = 112,
/// Index 113: GetStaticMethodID
get_static_method_id = 113,
/// Index 114: CallStaticObjectMethod (omitted)
/// Index 115: CallStaticObjectMethodV (omitted)
/// Index 116: CallStaticObjectMethodA
call_static_object_method = 116,
/// Index 117: CallStaticBooleanMethod (omitted)
/// Index 118: CallStaticBooleanMethodV (omitted)
/// Index 119: CallStaticBooleanMethodA
call_static_boolean_method = 119,
/// Index 120: CallStaticBooleanMethod (omitted)
/// Index 121: CallStaticBooleanMethodV (omitted)
/// Index 122: CallStaticBooleanMethodA
call_static_byte_method = 122,
/// Index 123: CallStaticCharMethod (omitted)
/// Index 124: CallStaticCharMethodV (omitted)
/// Index 125: CallStaticCharMethodA
call_static_char_method = 125,
/// Index 126: CallStaticCharMethod (omitted)
/// Index 127: CallStaticCharMethodV (omitted)
/// Index 128: CallStaticCharMethodA
call_static_short_method = 128,
/// Index 129: CallStaticIntMethod (omitted)
/// Index 130: CallStaticIntMethodV (omitted)
/// Index 131: CallStaticIntMethodA
call_static_int_method = 131,
/// Index 132: CallStaticLongMethod (omitted)
/// Index 133: CallStaticLongMethodV (omitted)
/// Index 134: CallStaticLongMethodA
call_static_long_method = 134,
/// Index 135: CallStaticFloatMethod (omitted)
/// Index 136: CallStaticFloatMethodV (omitted)
/// Index 137: CallStaticFloatMethodA
call_static_float_method = 137,
/// Index 138: CallStaticDoubleMethod (omitted)
/// Index 139: CallStaticDoubleMethodV (omitted)
/// Index 140: CallStaticDoubleMethodA
call_static_double_method = 140,
/// Index 141: CallStaticVoidMethod (omitted)
/// Index 142: CallStaticVoidMethodV (omitted)
/// Index 143: CallStaticVoidMethodA
call_static_void_method = 143,
/// Index 144: GetStaticFieldID
get_static_field_id = 144,
/// Index 145: GetStaticObjectField
get_static_object_field = 145,
/// Index 146: GetStaticBooleanField
get_static_boolean_field = 146,
/// Index 147: GetStaticByteField
get_static_byte_field = 147,
/// Index 148: GetStaticCharField
get_static_char_field = 148,
/// Index 149: GetStaticShortField
get_static_short_field = 149,
/// Index 150: GetStaticIntField
get_static_int_field = 150,
/// Index 151: GetStaticLongField
get_static_long_field = 151,
/// Index 152: GetStaticFloatField
/// Returns the value of a static field of an object.
get_static_float_field = 152,
/// Index 153: GetStaticDoubleField
get_static_double_field = 153,
/// Index 154: SetStaticObjectField
set_static_object_field = 154,
/// Index 155: SetStaticBooleanField
set_static_boolean_field = 155,
/// Index 156: SetStaticByteField
/// Sets the value of a static field of an object.
set_static_byte_field = 156,
/// Index 157: SetStaticCharField
set_static_char_field = 157,
/// Index 158: SetStaticShortField
set_static_short_field = 158,
/// Index 159: SetStaticIntField
set_static_int_field = 159,
/// Index 160: SetStaticLongField
set_static_long_field = 160,
/// Index 161: SetStaticFloatField
set_static_float_field = 161,
/// Index 162: SetStaticDoubleField
set_static_double_field = 162,
/// Index 163: NewString
new_string = 163,
/// Index 164: GetStringLength
get_string_length = 164,
/// Index 165: GetStringChars
get_string_chars = 165,
/// Index 166: ReleaseStringChars
release_string_chars = 166,
/// Index 167: NewStringUTF
new_string_utf = 167,
/// Index 168: GetStringUTFLength
get_string_utf_length = 168,
/// Index 169: GetStringUTFChars
get_string_utf_chars = 169,
/// Index 170: ReleaseStringUTFChars
release_string_utf_chars = 170,
/// Index 171: GetArrayLength
get_array_length = 171,
/// Index 172: NewObjectArray
new_object_array = 172,
/// Index 173: GetObjectArrayElement
get_object_array_element = 173,
/// Index 174: SetObjectArrayElement
set_object_array_element = 174,
/// Index 175: NewBooleanArray
new_boolean_array = 175,
/// Index 176: NewByteArray
new_byte_array = 176,
/// Index 177: NewCharArray
new_char_array = 177,
/// Index 178: NewShortArray
new_short_array = 178,
/// Index 179: NewIntArray
new_int_array = 179,
/// Index 180: NewLongArray
new_long_array = 180,
/// Index 181: NewFloatArray
new_float_array = 181,
/// Index 182: NewDoubleArray
new_double_array = 182,
/// Index 183: GetBooleanArrayElements
get_boolean_array_elements = 183,
/// Index 184: GetByteArrayElements
get_byte_array_elements = 184,
/// Index 185: GetCharArrayElements
get_char_array_elements = 185,
/// Index 186: GetShortArrayElements
get_short_array_elements = 186,
/// Index 187: GetIntArrayElements
get_int_array_elements = 187,
/// Index 188: GetLongArrayElements
get_long_array_elements = 188,
/// Index 189: GetFloatArrayElements
get_float_array_elements = 189,
/// Index 190: GetDoubleArrayElements
get_double_array_elements = 190,
/// Index 191: ReleaseBooleanArrayElements
release_boolean_array_elements = 191,
/// Index 192: ReleaseByteArrayElements
release_byte_array_elements = 192,
/// Index 193: ReleaseCharArrayElements
release_char_array_elements = 193,
/// Index 194: ReleaseShortArrayElements
release_short_array_elements = 194,
/// Index 195: ReleaseIntArrayElements
release_int_array_elements = 195,
/// Index 196: ReleaseLongArrayElements
release_long_array_elements = 196,
/// Index 197: ReleaseFloatArrayElements
release_float_array_elements = 197,
/// Index 198: ReleaseDoubleArrayElements
release_double_array_elements = 198,
/// Index 199: GetBooleanArrayRegion
get_boolean_array_region = 199,
/// Index 200: GetByteArrayRegion
get_byte_array_region = 200,
/// Index 201: GetCharArrayRegion
get_char_array_region = 201,
/// Index 202: GetShortArrayRegion
get_short_array_region = 202,
/// Index 203: GetIntArrayRegion
get_int_array_region = 203,
/// Index 204: GetLongArrayRegion
get_long_array_region = 204,
/// Index 205: GetFloatArrayRegion
get_float_array_region = 205,
/// Index 206: GetDoubleArrayRegion
get_double_array_region = 206,
/// Index 207: SetBooleanArrayRegion
set_boolean_array_region = 207,
/// Index 208: SetByteArrayRegion
set_byte_array_region = 208,
/// Index 209: SetCharArrayRegion
set_char_array_region = 209,
/// Index 210: SetShortArrayRegion
set_short_array_region = 210,
/// Index 211: SetIntArrayRegion
set_int_array_region = 211,
/// Index 212: SetLongArrayRegion
set_long_array_region = 212,
/// Index 213: SetFloatArrayRegion
set_float_array_region = 213,
/// Index 214: SetDoubleArrayRegion
set_double_array_region = 214,
/// Index 215: RegisterNatives
register_natives = 215,
/// Index 216: UnregisterNatives
unregister_natives = 216,
/// Index 217: MonitorEnter
monitor_enter = 217,
/// Index 218: MonitorExit
monitor_exit = 218,
/// GetJavaVM - Index 219 in the JNIEnv interface function table
get_java_vm = 219,
/// Index 220: GetStringRegion
get_string_region = 220,
/// Index 221: GetStringUTFRegion
get_string_utf_region = 221,
/// Index 222: GetPrimitiveArrayCritical
get_primitive_array_critical = 222,
/// Index 223: ReleasePrimitiveArrayCritical
release_primitive_array_critical = 223,
/// Index 224: GetStringCritical
get_string_critical = 224,
/// Index 225: ReleaseStringCritical
release_string_critical = 225,
/// Index 226: NewWeakGlobalRef
new_weak_global_ref = 226,
/// Index 227: DeleteWeakGlobalRef
delete_weak_global_ref = 227,
/// Index 228: ExceptionCheck
exception_check = 228,
/// Index 229: NewDirectByteBuffer
new_direct_byte_buffer = 229,
/// Index 230: GetDirectBufferAddress
get_direct_buffer_address = 230,
/// GetDirectBufferCapacity - Index 231 in the JNIEnv interface function table
get_direct_buffer_capacity = 231,
/// Index 232: GetObjectRefType
get_object_ref_type = 232,
/// Index 233: GetModule
get_module = 233,
};
usingnamespace JniInterface(JNIEnv);
/// Returns the major version number in the higher 16 bits
/// and the minor version number in the lower 16 bits.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getversion.
pub inline fn get_version(
env: *JNIEnv,
) JInt {
return JNIEnv.interface_call(
env,
.get_version,
.{},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#defineclass.
pub inline fn define_class(
env: *JNIEnv,
name: [*:0]const u8,
loader: JObject,
buf: [*]const JByte,
buf_len: JSize,
) JClass {
return JNIEnv.interface_call(
env,
.define_class,
.{ name, loader, buf, buf_len },
);
}
/// The name argument is a fully-qualified class name or an array type signature.
/// For example "java/lang/String"
/// Returns a class object from a fully-qualified name, or NULL if the class cannot be found.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#findclass.
pub inline fn find_class(
env: *JNIEnv,
name: [*:0]const u8,
) JClass {
return JNIEnv.interface_call(
env,
.find_class,
.{name},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#fromreflectedmethod
pub inline fn from_reflected_method(
env: *JNIEnv,
jobject: JObject,
) JMethodID {
return JNIEnv.interface_call(
env,
.from_reflected_method,
.{jobject},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#fromfeflectedfield
pub inline fn from_feflected_field(
env: *JNIEnv,
jobject: JObject,
) JFieldID {
return JNIEnv.interface_call(
env,
.from_feflected_field,
.{jobject},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#toreflectedmethod
pub inline fn to_reflected_method(
env: *JNIEnv,
cls: JClass,
method_id: JMethodID,
is_static: JBoolean,
) JObject {
return JNIEnv.interface_call(
env,
.to_reflected_method,
.{ cls, method_id, is_static },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getsuperclass.
pub inline fn get_super_class(
env: *JNIEnv,
clazz: JClass,
) JClass {
return JNIEnv.interface_call(
env,
.get_super_class,
.{clazz},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#isassignablefrom.
pub inline fn is_assignable_from(
env: *JNIEnv,
clazz_1: JClass,
clazz_2: JClass,
) JBoolean {
return JNIEnv.interface_call(
env,
.is_assignable_from,
.{ clazz_1, clazz_2 },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#toreflectedfield.
pub inline fn to_reflected_field(
env: *JNIEnv,
cls: JClass,
field_id: JFieldID,
is_static: JBoolean,
) JObject {
return JNIEnv.interface_call(
env,
.to_reflected_field,
.{ cls, field_id, is_static },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#throw.
pub inline fn throw(
env: *JNIEnv,
obj: JThrowable,
) JNIResultType {
return JNIEnv.interface_call(
env,
.throw,
.{obj},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#thrownew.
pub inline fn throw_new(
env: *JNIEnv,
clazz: JClass,
message: [*:0]const u8,
) JNIResultType {
return JNIEnv.interface_call(
env,
.throw_new,
.{ clazz, message },
);
}
/// Returns the exception object that is currently in the process of being thrown,
/// or NULL if no exception is currently being thrown.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#exceptionoccurred.
pub inline fn exception_occurred(
env: *JNIEnv,
) JThrowable {
return JNIEnv.interface_call(
env,
.exception_occurred,
.{},
);
}
/// Prints an exception and a backtrace of the stack to a system error-reporting channel,
/// such as stderr. This is a convenience routine provided for debugging.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#exceptiondescribe.
pub inline fn exception_describe(
env: *JNIEnv,
) void {
JNIEnv.interface_call(
env,
.exception_describe,
.{},
);
}
/// Clears any exception that is currently being thrown.
/// If no exception is currently being thrown, this routine has no effect.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#exceptionclear.
pub inline fn exception_clear(
env: *JNIEnv,
) void {
JNIEnv.interface_call(
env,
.exception_clear,
.{},
);
}
/// Raises a fatal error and does not expect the VM to recover.
/// This function does not return.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#fatalerror.
pub inline fn fatal_error(
env: *JNIEnv,
msg: [*:0]const u8,
) noreturn {
JNIEnv.interface_call(
env,
.fatal_error,
.{msg},
);
unreachable;
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#pushlocalframe.
pub inline fn push_local_frame(
env: *JNIEnv,
capacity: JInt,
) JNIResultType {
return JNIEnv.interface_call(
env,
.push_local_frame,
.{capacity},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#poplocalframe.
pub inline fn pop_local_frame(
env: *JNIEnv,
result: JObject,
) JObject {
return JNIEnv.interface_call(
env,
.pop_local_frame,
.{result},
);
}
/// Returns a global reference to the given obj.
/// May return NULL if:
/// - obj refers to null;
/// - the system has run out of memory;
/// - obj was a weak global reference and has already been garbage collected.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newglobalref.
pub inline fn new_global_ref(
env: *JNIEnv,
obj: JObject,
) JObject {
return JNIEnv.interface_call(
env,
.new_global_ref,
.{obj},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#deleteglobalref.
pub inline fn delete_global_ref(
env: *JNIEnv,
global_ref: JObject,
) void {
JNIEnv.interface_call(
env,
.delete_global_ref,
.{global_ref},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#deletelocalref.
pub inline fn delete_local_ref(
env: *JNIEnv,
local_ref: JObject,
) void {
JNIEnv.interface_call(
env,
.delete_local_ref,
.{local_ref},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#issameobject.
pub inline fn is_same_object(
env: *JNIEnv,
ref_1: JObject,
ref_2: JObject,
) JBoolean {
return JNIEnv.interface_call(
env,
.is_same_object,
.{ ref_1, ref_2 },
);
}
/// Returns NULL if ref refers to null.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newlocalref.
pub inline fn new_local_ref(
env: *JNIEnv,
ref: JObject,
) JObject {
return JNIEnv.interface_call(
env,
.new_local_ref,
.{ref},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#ensurelocalcapacity.
pub inline fn ensure_local_capacity(
env: *JNIEnv,
capacity: JInt,
) JNIResultType {
return JNIEnv.interface_call(
env,
.ensure_local_capacity,
.{capacity},
);
}
/// Allocates a new Java object *without* invoking the constructor.
/// Returns a reference to the object.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#allocobject.
pub inline fn alloc_object(
env: *JNIEnv,
clazz: JClass,
) JObject {
return JNIEnv.interface_call(
env,
.alloc_object,
.{clazz},
);
}
/// Returns a Java object, or NULL if the object cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newobject.
pub inline fn new_object(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JObject {
return JNIEnv.interface_call(
env,
.new_object,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getobjectclass.
pub inline fn get_object_class(
env: *JNIEnv,
jobject: JObject,
) JClass {
return JNIEnv.interface_call(
env,
.get_object_class,
.{jobject},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#isinstanceof.
pub inline fn is_instance_of(
env: *JNIEnv,
jobject: JObject,
clazz: JClass,
) JBoolean {
return JNIEnv.interface_call(
env,
.is_instance_of,
.{ jobject, clazz },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getmethodid.
pub inline fn get_method_id(
env: *JNIEnv,
clazz: JClass,
name: [*:0]const u8,
sig: [*:0]const u8,
) JMethodID {
return JNIEnv.interface_call(
env,
.get_method_id,
.{ clazz, name, sig },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_object_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JObject {
return JNIEnv.interface_call(
env,
.call_object_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_boolean_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JBoolean {
return JNIEnv.interface_call(
env,
.call_boolean_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_byte_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JByte {
return JNIEnv.interface_call(
env,
.call_byte_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_char_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JChar {
return JNIEnv.interface_call(
env,
.call_char_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_short_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JShort {
return JNIEnv.interface_call(
env,
.call_short_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_int_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JInt {
return JNIEnv.interface_call(
env,
.call_int_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_long_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JLong {
return JNIEnv.interface_call(
env,
.call_long_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_float_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JFloat {
return JNIEnv.interface_call(
env,
.call_float_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_double_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) JDouble {
return JNIEnv.interface_call(
env,
.call_double_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#calltypemethod-routines-calltypemethoda-routines-calltypemethodv-routines.
pub inline fn call_void_method(
env: *JNIEnv,
obj: JObject,
method_id: JMethodID,
args: ?[*]const JValue,
) void {
JNIEnv.interface_call(
env,
.call_void_method,
.{ obj, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_object_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JObject {
return JNIEnv.interface_call(
env,
.call_nonvirtual_object_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_boolean_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JBoolean {
return JNIEnv.interface_call(
env,
.call_nonvirtual_boolean_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_byte_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JByte {
return JNIEnv.interface_call(
env,
.call_nonvirtual_byte_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_char_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JChar {
return JNIEnv.interface_call(
env,
.call_nonvirtual_char_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_short_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JShort {
return JNIEnv.interface_call(
env,
.call_nonvirtual_short_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_int_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JInt {
return JNIEnv.interface_call(
env,
.call_nonvirtual_int_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_long_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JLong {
return JNIEnv.interface_call(
env,
.call_nonvirtual_long_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_float_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JFloat {
return JNIEnv.interface_call(
env,
.call_nonvirtual_float_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_double_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JDouble {
return JNIEnv.interface_call(
env,
.call_nonvirtual_double_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callnonvirtualtypemethod-routines-callnonvirtualtypemethoda-routines-callnonvirtualtypemethodv-routines.
pub inline fn call_nonvirtual_void_method(
env: *JNIEnv,
obj: JObject,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) void {
JNIEnv.interface_call(
env,
.call_nonvirtual_void_method,
.{ obj, clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getfieldid.
pub inline fn get_field_id(
env: *JNIEnv,
clazz: JClass,
name: [*:0]const u8,
sig: [*:0]const u8,
) JFieldID {
return JNIEnv.interface_call(
env,
.get_field_id,
.{ clazz, name, sig },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_object_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JObject {
return JNIEnv.interface_call(
env,
.get_object_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_boolean_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JBoolean {
return JNIEnv.interface_call(
env,
.get_boolean_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_byte_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JByte {
return JNIEnv.interface_call(
env,
.get_byte_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_char_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JChar {
return JNIEnv.interface_call(
env,
.get_char_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_short_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JShort {
return JNIEnv.interface_call(
env,
.get_short_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_int_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JInt {
return JNIEnv.interface_call(
env,
.get_int_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_long_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JLong {
return JNIEnv.interface_call(
env,
.get_long_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_float_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JFloat {
return JNIEnv.interface_call(
env,
.get_float_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#gettypefield-routines.
pub inline fn get_double_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
) JDouble {
return JNIEnv.interface_call(
env,
.get_double_field,
.{ obj, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_object_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JObject,
) void {
JNIEnv.interface_call(
env,
.set_object_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_boolean_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JBoolean,
) void {
JNIEnv.interface_call(
env,
.set_boolean_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_byte_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JByte,
) void {
JNIEnv.interface_call(
env,
.set_byte_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_char_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JChar,
) void {
JNIEnv.interface_call(
env,
.set_char_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_short_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JShort,
) void {
JNIEnv.interface_call(
env,
.set_short_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_int_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JInt,
) void {
JNIEnv.interface_call(
env,
.set_int_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_long_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JLong,
) void {
JNIEnv.interface_call(
env,
.set_long_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_float_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JFloat,
) void {
JNIEnv.interface_call(
env,
.set_float_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#settypefield-routines.
pub inline fn set_double_field(
env: *JNIEnv,
obj: JObject,
field_id: JFieldID,
value: JDouble,
) void {
JNIEnv.interface_call(
env,
.set_double_field,
.{ obj, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstaticmethodid.
pub inline fn get_static_method_id(
env: *JNIEnv,
clazz: JClass,
name: [*:0]const u8,
sig: [*:0]const u8,
) JMethodID {
return JNIEnv.interface_call(
env,
.get_static_method_id,
.{ clazz, name, sig },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_object_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JObject {
return JNIEnv.interface_call(
env,
.call_static_object_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_boolean_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JBoolean {
return JNIEnv.interface_call(
env,
.call_static_boolean_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_byte_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JByte {
return JNIEnv.interface_call(
env,
.call_static_byte_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_char_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JChar {
return JNIEnv.interface_call(
env,
.call_static_char_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_short_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JShort {
return JNIEnv.interface_call(
env,
.call_static_short_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_int_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JInt {
return JNIEnv.interface_call(
env,
.call_static_int_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_long_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JLong {
return JNIEnv.interface_call(
env,
.call_static_long_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_float_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JFloat {
return JNIEnv.interface_call(
env,
.call_static_float_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_double_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) JDouble {
return JNIEnv.interface_call(
env,
.call_static_double_method,
.{ clazz, method_id, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#callstatictypemethod-routines-callstatictypemethoda-routines-callstatictypemethodv-routines.
pub inline fn call_static_void_method(
env: *JNIEnv,
clazz: JClass,
method_id: JMethodID,
args: ?[*]const JValue,
) void {
JNIEnv.interface_call(
env,
.call_static_void_method,
.{ clazz, method_id, args },
);
}
/// Returns a field ID, or NULL if the specified static field cannot be found.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstaticfieldid.
pub inline fn get_static_field_id(
env: *JNIEnv,
clazz: JClass,
name: [*:0]const u8,
sig: [*:0]const u8,
) JFieldID {
return JNIEnv.interface_call(
env,
.get_static_field_id,
.{ clazz, name, sig },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_object_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JObject {
return JNIEnv.interface_call(
env,
.get_static_object_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_boolean_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JBoolean {
return JNIEnv.interface_call(
env,
.get_static_boolean_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_byte_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JByte {
return JNIEnv.interface_call(
env,
.get_static_byte_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_char_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JChar {
return JNIEnv.interface_call(
env,
.get_static_char_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_short_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JShort {
return JNIEnv.interface_call(
env,
.get_static_short_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_int_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JInt {
return JNIEnv.interface_call(
env,
.get_static_int_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_long_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JLong {
return JNIEnv.interface_call(
env,
.get_static_long_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_float_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JFloat {
return JNIEnv.interface_call(
env,
.get_static_float_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn get_static_double_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
) JDouble {
return JNIEnv.interface_call(
env,
.get_static_double_field,
.{ clazz, field_id },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstatictypefield-routines.
pub inline fn set_static_object_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JObject,
) void {
JNIEnv.interface_call(
env,
.set_static_object_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setstatictypefield-routines.
pub inline fn set_static_boolean_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JBoolean,
) void {
JNIEnv.interface_call(
env,
.set_static_boolean_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setstatictypefield-routines.
pub inline fn set_static_byte_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JByte,
) void {
JNIEnv.interface_call(
env,
.set_static_byte_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setstatictypefield-routines.
pub inline fn set_static_char_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JChar,
) void {
JNIEnv.interface_call(
env,
.set_static_char_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setstatictypefield-routines.
pub inline fn set_static_short_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JShort,
) void {
JNIEnv.interface_call(
env,
.set_static_short_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setstatictypefield-routines.
pub inline fn set_static_int_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JInt,
) void {
JNIEnv.interface_call(
env,
.set_static_int_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setstatictypefield-routines.
pub inline fn set_static_long_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JLong,
) void {
JNIEnv.interface_call(
env,
.set_static_long_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setstatictypefield-routines.
pub inline fn set_static_float_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JFloat,
) void {
JNIEnv.interface_call(
env,
.set_static_float_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setstatictypefield-routines.
pub inline fn set_static_double_field(
env: *JNIEnv,
clazz: JClass,
field_id: JFieldID,
value: JDouble,
) void {
JNIEnv.interface_call(
env,
.set_static_double_field,
.{ clazz, field_id, value },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newstring.
pub inline fn new_string(
env: *JNIEnv,
unicode_chars: [*]const JChar,
size: JSize,
) JString {
return JNIEnv.interface_call(
env,
.new_string,
.{ unicode_chars, size },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringlength.
pub inline fn get_string_length(
env: *JNIEnv,
string: JString,
) JSize {
return JNIEnv.interface_call(
env,
.get_string_length,
.{string},
);
}
/// Returns a pointer to the array of Unicode characters of the string.
/// This pointer is valid until release_string_chars is called.
/// If is_copy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringchars.
pub inline fn get_string_chars(
env: *JNIEnv,
string: JString,
is_copy: ?*JBoolean,
) ?[*]const JChar {
return JNIEnv.interface_call(
env,
.get_string_chars,
.{ string, is_copy },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releasestringchars.
pub inline fn release_string_chars(
env: *JNIEnv,
string: JString,
chars: [*]const JChar,
) void {
JNIEnv.interface_call(
env,
.release_string_chars,
.{ string, chars },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newstringutf.
pub inline fn new_string_utf(
env: *JNIEnv,
bytes: [*:0]const u8,
) JString {
return JNIEnv.interface_call(
env,
.new_string_utf,
.{bytes},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringutflength.
pub inline fn get_string_utf_length(
env: *JNIEnv,
string: JString,
) JSize {
return JNIEnv.interface_call(
env,
.get_string_utf_length,
.{string},
);
}
/// Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding.
/// This array is valid until it is released by release_string_utf_chars.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringutfchars.
pub inline fn get_string_utf_chars(
env: *JNIEnv,
string: JString,
is_copy: ?*JBoolean,
) ?[*:0]const u8 {
return JNIEnv.interface_call(
env,
.get_string_utf_chars,
.{ string, is_copy },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releasestringutfchars.
pub inline fn release_string_utf_chars(
env: *JNIEnv,
string: JString,
utf: [*:0]const u8,
) void {
JNIEnv.interface_call(
env,
.release_string_utf_chars,
.{ string, utf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getarraylength.
pub inline fn get_array_length(
env: *JNIEnv,
array: JArray,
) JSize {
return JNIEnv.interface_call(
env,
.get_array_length,
.{array},
);
}
/// Constructs a new array holding objects in class elementClass.
/// All elements are initially set to initialElement.
/// Returns a Java array object, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newobjectarray.
pub inline fn new_object_array(
env: *JNIEnv,
length: JSize,
element_class: JClass,
initial_element: JObject,
) JObjectArray {
return JNIEnv.interface_call(
env,
.new_object_array,
.{ length, element_class, initial_element },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getobjectarrayelement.
pub inline fn get_object_array_element(
env: *JNIEnv,
array: JObjectArray,
index: JSize,
) JObject {
return JNIEnv.interface_call(
env,
.get_object_array_element,
.{ array, index },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setobjectarrayelement.
pub inline fn set_object_array_element(
env: *JNIEnv,
array: JObjectArray,
index: JSize,
value: JObject,
) void {
JNIEnv.interface_call(
env,
.set_object_array_element,
.{ array, index, value },
);
}
/// Returns a Java array, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newprimitivetypearray-routines.
pub inline fn new_boolean_array(
env: *JNIEnv,
length: JSize,
) JBooleanArray {
return JNIEnv.interface_call(
env,
.new_boolean_array,
.{length},
);
}
/// Returns a Java array, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newprimitivetypearray-routines.
pub inline fn new_byte_array(
env: *JNIEnv,
length: JSize,
) JByteArray {
return JNIEnv.interface_call(
env,
.new_byte_array,
.{length},
);
}
/// Returns a Java array, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newprimitivetypearray-routines.
pub inline fn new_char_array(
env: *JNIEnv,
length: JSize,
) JCharArray {
return JNIEnv.interface_call(
env,
.new_char_array,
.{length},
);
}
/// Returns a Java array, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newprimitivetypearray-routines.
pub inline fn new_short_array(
env: *JNIEnv,
length: JSize,
) JShortArray {
return JNIEnv.interface_call(
env,
.new_short_array,
.{length},
);
}
/// Returns a Java array, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newprimitivetypearray-routines.
pub inline fn new_int_array(
env: *JNIEnv,
length: JSize,
) JIntArray {
return JNIEnv.interface_call(
env,
.new_int_array,
.{length},
);
}
/// Returns a Java array, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newprimitivetypearray-routines.
pub inline fn new_long_array(
env: *JNIEnv,
length: JSize,
) JLongArray {
return JNIEnv.interface_call(
env,
.new_long_array,
.{length},
);
}
/// Returns a Java array, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newprimitivetypearray-routines.
pub inline fn new_float_array(
env: *JNIEnv,
length: JSize,
) JFloatArray {
return JNIEnv.interface_call(
env,
.new_float_array,
.{length},
);
}
/// Returns a Java array, or NULL if the array cannot be constructed.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newprimitivetypearray-routines.
pub inline fn new_double_array(
env: *JNIEnv,
length: JSize,
) JDoubleArray {
return JNIEnv.interface_call(
env,
.new_double_array,
.{length},
);
}
/// Returns the body of the primitive array.
/// The result is valid until the corresponding release function is called.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayelements-routines.
pub inline fn get_boolean_array_elements(
env: *JNIEnv,
array: JBooleanArray,
is_copy: ?*JBoolean,
) ?[*]JBoolean {
return JNIEnv.interface_call(
env,
.get_boolean_array_elements,
.{ array, is_copy },
);
}
/// Returns the body of the primitive array.
/// The result is valid until the corresponding release function is called.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayelements-routines.
pub inline fn get_byte_array_elements(
env: *JNIEnv,
array: JByteArray,
is_copy: ?*JBoolean,
) ?[*]JByte {
return JNIEnv.interface_call(
env,
.get_byte_array_elements,
.{ array, is_copy },
);
}
/// Returns the body of the primitive array.
/// The result is valid until the corresponding release function is called.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayelements-routines.
pub inline fn get_char_array_elements(
env: *JNIEnv,
array: JCharArray,
is_copy: ?*JBoolean,
) ?[*]JChar {
return JNIEnv.interface_call(
env,
.get_char_array_elements,
.{ array, is_copy },
);
}
/// Returns the body of the primitive array.
/// The result is valid until the corresponding release function is called.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayelements-routines.
pub inline fn get_short_array_elements(
env: *JNIEnv,
array: JShortArray,
is_copy: ?*JBoolean,
) ?[*]JShort {
return JNIEnv.interface_call(
env,
.get_short_array_elements,
.{ array, is_copy },
);
}
/// Returns the body of the primitive array.
/// The result is valid until the corresponding release function is called.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayelements-routines.
pub inline fn get_int_array_elements(
env: *JNIEnv,
array: JIntArray,
is_copy: ?*JBoolean,
) ?[*]JInt {
return JNIEnv.interface_call(
env,
.get_int_array_elements,
.{ array, is_copy },
);
}
/// Returns the body of the primitive array.
/// The result is valid until the corresponding release function is called.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayelements-routines.
pub inline fn get_long_array_elements(
env: *JNIEnv,
array: JLongArray,
is_copy: ?*JBoolean,
) ?[*]JLong {
return JNIEnv.interface_call(
env,
.get_long_array_elements,
.{ array, is_copy },
);
}
/// Returns the body of the primitive array.
/// The result is valid until the corresponding release function is called.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayelements-routines.
pub inline fn get_float_array_elements(
env: *JNIEnv,
array: JFloatArray,
is_copy: ?*JBoolean,
) ?[*]JFloat {
return JNIEnv.interface_call(
env,
.get_float_array_elements,
.{ array, is_copy },
);
}
/// Index 190: GetDoubleArrayElements
/// Returns the body of the primitive array.
/// The result is valid until the corresponding release function is called.
/// If isCopy is not NULL, then *is_copy is set to true if a copy is made,
/// or it is set to false if no copy is made.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayelements-routines.
pub inline fn get_double_array_elements(
env: *JNIEnv,
array: JDoubleArray,
is_copy: ?*JBoolean,
) ?[*]JDouble {
return JNIEnv.interface_call(
env,
.get_double_array_elements,
.{ array, is_copy },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub inline fn release_boolean_array_elements(
env: *JNIEnv,
array: JBooleanArray,
elems: [*]JBoolean,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_boolean_array_elements,
.{ array, elems, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub inline fn release_byte_array_elements(
env: *JNIEnv,
array: JByteArray,
elems: [*]JByte,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_byte_array_elements,
.{ array, elems, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub inline fn release_char_array_elements(
env: *JNIEnv,
array: JCharArray,
elems: [*]JChar,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_char_array_elements,
.{ array, elems, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub inline fn release_short_array_elements(
env: *JNIEnv,
array: JShortArray,
elems: [*]JShort,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_short_array_elements,
.{ array, elems, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub inline fn release_int_array_elements(
env: *JNIEnv,
array: JIntArray,
elems: [*]JInt,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_int_array_elements,
.{ array, elems, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub inline fn release_long_array_elements(
env: *JNIEnv,
array: JLongArray,
elems: [*]JLong,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_long_array_elements,
.{ array, elems, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub inline fn release_float_array_elements(
env: *JNIEnv,
array: JFloatArray,
elems: [*]JFloat,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_float_array_elements,
.{ array, elems, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivetypearrayelements-routines.
pub inline fn release_double_array_elements(
env: *JNIEnv,
array: JDoubleArray,
elems: [*]JDouble,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_double_array_elements,
.{ array, elems, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayregion-routines.
pub inline fn get_boolean_array_region(
env: *JNIEnv,
array: JBooleanArray,
start: JSize,
len: JSize,
buf: [*]JBoolean,
) void {
JNIEnv.interface_call(
env,
.get_boolean_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayregion-routines.
pub inline fn get_byte_array_region(
env: *JNIEnv,
array: JByteArray,
start: JSize,
len: JSize,
buf: [*]JByte,
) void {
JNIEnv.interface_call(
env,
.get_byte_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayregion-routines.
pub inline fn get_char_array_region(
env: *JNIEnv,
array: JCharArray,
start: JSize,
len: JSize,
buf: [*]JChar,
) void {
JNIEnv.interface_call(
env,
.get_char_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayregion-routines.
pub inline fn get_short_array_region(
env: *JNIEnv,
array: JShortArray,
start: JSize,
len: JSize,
buf: [*]JShort,
) void {
JNIEnv.interface_call(
env,
.get_short_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayregion-routines.
pub inline fn get_int_array_region(
env: *JNIEnv,
array: JIntArray,
start: JSize,
len: JSize,
buf: [*]JInt,
) void {
JNIEnv.interface_call(
env,
.get_int_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayregion-routines.
pub inline fn get_long_array_region(
env: *JNIEnv,
array: JLongArray,
start: JSize,
len: JSize,
buf: [*]JLong,
) void {
JNIEnv.interface_call(
env,
.get_long_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayregion-routines.
pub inline fn get_float_array_region(
env: *JNIEnv,
array: JFloatArray,
start: JSize,
len: JSize,
buf: [*]JFloat,
) void {
JNIEnv.interface_call(
env,
.get_float_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivetypearrayregion-routines.
pub inline fn get_double_array_region(
env: *JNIEnv,
array: JDoubleArray,
start: JSize,
len: JSize,
buf: [*]JDouble,
) void {
JNIEnv.interface_call(
env,
.get_double_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setprimitivetypearrayregion-routines.
pub inline fn set_boolean_array_region(
env: *JNIEnv,
array: JBooleanArray,
start: JSize,
len: JSize,
buf: [*]const JBoolean,
) void {
JNIEnv.interface_call(
env,
.set_boolean_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setprimitivetypearrayregion-routines.
pub inline fn set_byte_array_region(
env: *JNIEnv,
array: JByteArray,
start: JSize,
len: JSize,
buf: [*]const JByte,
) void {
JNIEnv.interface_call(
env,
.set_byte_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setprimitivetypearrayregion-routines.
pub inline fn set_char_array_region(
env: *JNIEnv,
array: JCharArray,
start: JSize,
len: JSize,
buf: [*]const JChar,
) void {
JNIEnv.interface_call(
env,
.set_char_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setprimitivetypearrayregion-routines.
pub inline fn set_short_array_region(
env: *JNIEnv,
array: JShortArray,
start: JSize,
len: JSize,
buf: [*]const JShort,
) void {
JNIEnv.interface_call(
env,
.set_short_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setprimitivetypearrayregion-routines.
pub inline fn set_int_array_region(
env: *JNIEnv,
array: JIntArray,
start: JSize,
len: JSize,
buf: [*]const JInt,
) void {
JNIEnv.interface_call(
env,
.set_int_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setprimitivetypearrayregion-routines.
pub inline fn set_long_array_region(
env: *JNIEnv,
array: JLongArray,
start: JSize,
len: JSize,
buf: [*]const JLong,
) void {
JNIEnv.interface_call(
env,
.set_long_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setprimitivetypearrayregion-routines.
pub inline fn set_float_array_region(
env: *JNIEnv,
array: JFloatArray,
start: JSize,
len: JSize,
buf: [*]const JFloat,
) void {
JNIEnv.interface_call(
env,
.set_float_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#setprimitivetypearrayregion-routines.
pub inline fn set_double_array_region(
env: *JNIEnv,
array: JDoubleArray,
start: JSize,
len: JSize,
buf: [*]const JDouble,
) void {
JNIEnv.interface_call(
env,
.set_double_array_region,
.{ array, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#registernatives.
pub inline fn register_natives(
env: *JNIEnv,
clazz: JClass,
methods: [*]const JNINativeMethod,
methods_len: JInt,
) JNIResultType {
return JNIEnv.interface_call(
env,
.register_natives,
.{ clazz, methods, methods_len },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#unregisternatives.
pub inline fn unregister_natives(
env: *JNIEnv,
clazz: JClass,
) JNIResultType {
return JNIEnv.interface_call(
env,
.unregister_natives,
.{clazz},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#monitorenter.
pub inline fn monitor_enter(
env: *JNIEnv,
obj: JObject,
) JNIResultType {
return JNIEnv.interface_call(
env,
.monitor_enter,
.{obj},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#monitorexit.
pub inline fn monitor_exit(
env: *JNIEnv,
obj: JObject,
) JNIResultType {
return JNIEnv.interface_call(
env,
.monitor_exit,
.{obj},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getjavavm.
pub inline fn get_java_vm(
env: *JNIEnv,
vm: **JavaVM,
) JNIResultType {
return JNIEnv.interface_call(
env,
.get_java_vm,
.{vm},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringregion.
pub inline fn get_string_region(
env: *JNIEnv,
string: JString,
start: JSize,
len: JSize,
buf: [*]JChar,
) void {
JNIEnv.interface_call(
env,
.get_string_region,
.{ string, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringutfregion.
pub inline fn get_string_utf_region(
env: *JNIEnv,
string: JString,
start: JSize,
len: JSize,
buf: [*]u8,
) void {
JNIEnv.interface_call(
env,
.get_string_utf_region,
.{ string, start, len, buf },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getprimitivearraycritical.
pub inline fn get_primitive_array_critical(
env: *JNIEnv,
array: JArray,
is_copy: ?*JBoolean,
) ?*anyopaque {
return JNIEnv.interface_call(
env,
.get_primitive_array_critical,
.{ array, is_copy },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#releaseprimitivearraycritical.
pub inline fn release_primitive_array_critical(
env: *JNIEnv,
array: JArray,
c_array: *anyopaque,
mode: JArrayReleaseMode,
) void {
JNIEnv.interface_call(
env,
.release_primitive_array_critical,
.{ array, c_array, mode },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringcritical-releasestringcritical.
pub inline fn get_string_critical(
env: *JNIEnv,
string: JString,
is_copy: ?*JBoolean,
) ?[*]const JChar {
return JNIEnv.interface_call(
env,
.get_string_critical,
.{ string, is_copy },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringcritical-releasestringcritical.
pub inline fn release_string_critical(
env: *JNIEnv,
string: JString,
chars: [*]const JChar,
) void {
JNIEnv.interface_call(
env,
.release_string_critical,
.{ string, chars },
);
}
/// Returns NULL if obj refers to null, or if the VM runs out of memory.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newweakglobalref.
pub inline fn new_weak_global_ref(
env: *JNIEnv,
obj: JObject,
) JWeakReference {
return JNIEnv.interface_call(
env,
.new_weak_global_ref,
.{obj},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#deleteweakglobalref.
pub inline fn delete_weak_global_ref(
env: *JNIEnv,
ref: JWeakReference,
) void {
JNIEnv.interface_call(
env,
.delete_weak_global_ref,
.{ref},
);
}
/// Returns true when there is a pending exception; otherwise, returns false.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#exceptioncheck.
pub inline fn exception_check(
env: *JNIEnv,
) JBoolean {
return JNIEnv.interface_call(
env,
.exception_check,
.{},
);
}
/// Allocates and returns a direct java.nio.ByteBuffer.
/// Returns NULL if an exception occurs,
/// or if JNI access to direct buffers is not supported by this virtual machine.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#newdirectbytebuffer.
pub inline fn new_direct_byte_buffer(
env: *JNIEnv,
address: *anyopaque,
capacity: JLong,
) JObject {
return JNIEnv.interface_call(
env,
.new_direct_byte_buffer,
.{ address, capacity },
);
}
/// Returns the starting address of the memory region referenced by the buffer.
/// Returns NULL if the memory region is undefined,
/// if the given object is not a direct java.nio.Buffer,
/// or if JNI access to direct buffers is not supported by this virtual machine.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getdirectbufferaddress.
pub inline fn get_direct_buffer_address(
env: *JNIEnv,
buf: JObject,
) ?[*]u8 {
return JNIEnv.interface_call(
env,
.get_direct_buffer_address,
.{buf},
);
}
/// Returns the capacity of the memory region associated with the buffer.
/// Returns -1 if the given object is not a direct java.nio.Buffer,
/// if the object is an unaligned view buffer and the processor architecture
/// does not support unaligned access,
/// or if JNI access to direct buffers is not supported by this virtual machine.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getdirectbuffercapacity.
pub inline fn get_direct_buffer_capacity(
env: *JNIEnv,
buf: JObject,
) JLong {
return JNIEnv.interface_call(
env,
.get_direct_buffer_capacity,
.{buf},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getobjectreftype.
pub inline fn get_object_ref_type(
env: *JNIEnv,
obj: JObject,
) JObjectRefType {
return JNIEnv.interface_call(
env,
.get_object_ref_type,
.{obj},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getmodule.
pub inline fn get_module(
env: *JNIEnv,
clazz: JClass,
) JObject {
return JNIEnv.interface_call(
env,
.get_module,
.{clazz},
);
}
};
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#jni_createjavavm.
pub const JavaVMOption = extern struct {
/// The option as a string in the default platform encoding.
option_string: [*:0]const u8,
extra_info: ?*anyopaque = null,
};
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#jni_createjavavm.
pub const JavaVMInitArgs = extern struct {
version: JInt,
options_len: JInt,
options: ?[*]JavaVMOption,
ignore_unrecognized: JBoolean,
};
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#attachcurrentthread.
pub const JavaVMAttachArgs = extern struct {
version: JInt,
name: [*:0]const u8,
group: JObject,
};
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html
pub const JavaVM = opaque {
/// Each function is accessible at a fixed offset through the JavaVM argument.
/// The JavaVM type is a pointer to the invocation API function table.
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#invocation-api-functions.
const FunctionTable = enum(usize) {
/// Index 3: DestroyJavaVM.
destroy_java_vm = 3,
/// Index 4: AttachCurrentThread.
attach_current_thread = 4,
/// Index 5: DetachCurrentThread.
detach_current_thread = 5,
/// Index 6: GetEnv.
get_env = 6,
/// Index 7: AttachCurrentThreadAsDaemon.
attach_current_thread_as_daemon = 7,
};
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#jni_getdefaultjavavminitargs.
pub const get_default_java_vm_init_args = struct {
extern "jvm" fn JNI_GetDefaultJavaVMInitArgs(
vm_args: ?*JavaVMInitArgs,
) callconv(.C) JNIResultType;
}.JNI_GetDefaultJavaVMInitArgs;
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#jni_get_createdjavavm.
pub const get_created_java_vm = struct {
extern "jvm" fn JNI_GetCreatedJavaVMs(
vm_buf: [*]*JavaVM,
buf_len: JSize,
vm_len: ?*JSize,
) callconv(.C) JNIResultType;
}.JNI_GetCreatedJavaVMs;
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#jni_createjavavm.
pub const create_java_vm = struct {
extern "jvm" fn JNI_CreateJavaVM(
jvm: **JavaVM,
env: **JNIEnv,
args: *JavaVMInitArgs,
) callconv(.C) JNIResultType;
}.JNI_CreateJavaVM;
usingnamespace JniInterface(JavaVM);
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#destroyjavavm.
pub inline fn destroy_java_vm(
vm: *JavaVM,
) JNIResultType {
return JavaVM.interface_call(
vm,
.destroy_java_vm,
.{},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#attachcurrentthread.
pub inline fn attach_current_thread(
vm: *JavaVM,
env: **JNIEnv,
args: ?*JavaVMAttachArgs,
) JNIResultType {
return JavaVM.interface_call(
vm,
.attach_current_thread,
.{ env, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#detachcurrentthread.
pub inline fn detach_current_thread(
vm: *JavaVM,
) JNIResultType {
return JavaVM.interface_call(
vm,
.detach_current_thread,
.{},
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#attach_currentthreadasdaemon.
pub inline fn attach_current_thread_as_daemon(
vm: *JavaVM,
env: **JNIEnv,
args: ?*JavaVMAttachArgs,
) JNIResultType {
return JavaVM.interface_call(
vm,
.attach_current_thread_as_daemon,
.{ env, args },
);
}
/// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/invocation.html#getenv
pub inline fn get_env(
vm: *JavaVM,
env: **JNIEnv,
version: JInt,
) JNIResultType {
return JavaVM.interface_call(
vm,
.get_env,
.{ env, version },
);
}
};
/// Invokes a function at the offset of the vtable, allowing to utilize the function pointer
/// without the need to declare a VTable layout, where the ordering of fields defines the ABI.
/// The function index is stored within T.FunctionTable enum, which only holds the index value.
/// The function signature is declared as an inline function within the T opaque type.
fn JniInterface(comptime T: type) type {
return struct {
fn JniFn(comptime function: T.FunctionTable) type {
const Fn = @TypeOf(@field(T, @tagName(function)));
var fn_info = @typeInfo(Fn);
switch (fn_info) {
.Fn => {
fn_info.Fn.calling_convention = JNICALL;
return @Type(fn_info);
},
else => @compileError("Expected " ++ @tagName(function) ++ " to be a function"),
}
}
pub inline fn interface_call(
self: *T,
comptime function: T.FunctionTable,
args: anytype,
) return_type: {
const type_info = @typeInfo(JniFn(function));
break :return_type type_info.Fn.return_type.?;
} {
const Fn = JniFn(function);
const VTable = extern struct {
functions: [*]const *const anyopaque,
};
const vtable: *VTable = @ptrCast(@alignCast(self));
const fn_ptr: *const Fn = @ptrCast(@alignCast(
vtable.functions[@intFromEnum(function)],
));
return @call(.auto, fn_ptr, .{self} ++ args);
}
};
}
|
0 | repos/tigerbeetle/src/clients/java | repos/tigerbeetle/src/clients/java/src/jni_tests.zig | ///! This test hosts an in-process JVM
///! using the JNI Invocation API.
const std = @import("std");
const jni = @import("jni.zig");
const testing = std.testing;
const JavaVM = jni.JavaVM;
const JNIEnv = jni.JNIEnv;
test "JNI: check jvm" {
const env: *JNIEnv = get_testing_env();
var jvm: *JavaVM = undefined;
const get_java_vm_result = env.get_java_vm(&jvm);
try testing.expectEqual(jni.JNIResultType.ok, get_java_vm_result);
var vm_buf: [2]*jni.JavaVM = undefined;
var vm_len: jni.JSize = 0;
const get_created_java_vm_result = JavaVM.get_created_java_vm(
&vm_buf,
@intCast(vm_buf.len),
&vm_len,
);
try testing.expectEqual(jni.JNIResultType.ok, get_created_java_vm_result);
try testing.expect(vm_len == 1);
try testing.expectEqual(jvm, vm_buf[0]);
}
test "JNI: GetVersion" {
const env: *JNIEnv = get_testing_env();
const version = env.get_version();
try testing.expect(version >= jni.jni_version_10);
}
test "JNI: FindClass" {
const env: *JNIEnv = get_testing_env();
const object_class = env.find_class("java/lang/Object");
try testing.expect(object_class != null);
defer env.delete_local_ref(object_class);
const not_found = env.find_class("no/such/Class");
defer env.exception_clear();
try testing.expect(not_found == null);
try testing.expect(env.exception_check() == .jni_true);
}
test "JNI: GetSuperclass" {
const env: *JNIEnv = get_testing_env();
const object_class = env.find_class("java/lang/Object");
try testing.expect(object_class != null);
defer env.delete_local_ref(object_class);
try testing.expect(env.get_super_class(object_class) == null);
const string_class = env.find_class("java/lang/String");
try testing.expect(string_class != null);
defer env.delete_local_ref(string_class);
const super_class = env.get_super_class(string_class);
try testing.expect(super_class != null);
defer env.delete_local_ref(super_class);
try testing.expect(env.is_same_object(object_class, super_class) == .jni_true);
}
test "JNI: IsAssignableFrom" {
const env: *JNIEnv = get_testing_env();
const object_class = env.find_class("java/lang/Object");
try testing.expect(object_class != null);
defer env.delete_local_ref(object_class);
try testing.expect(env.get_super_class(object_class) == null);
const string_class = env.find_class("java/lang/String");
try testing.expect(string_class != null);
defer env.delete_local_ref(string_class);
const long_class = env.find_class("java/lang/Long");
try testing.expect(long_class != null);
defer env.delete_local_ref(long_class);
try testing.expect(env.is_assignable_from(long_class, object_class) == .jni_true);
try testing.expect(env.is_assignable_from(long_class, string_class) == .jni_false);
}
test "JNI: GetModule" {
const env: *JNIEnv = get_testing_env();
const exception_class = env.find_class("java/lang/Exception");
try testing.expect(exception_class != null);
defer env.delete_local_ref(exception_class);
const module = env.get_module(exception_class);
try testing.expect(module != null);
defer env.delete_local_ref(module);
}
test "JNI: Throw" {
const env: *JNIEnv = get_testing_env();
const exception_class = env.find_class("java/lang/Exception");
try testing.expect(exception_class != null);
defer env.delete_local_ref(exception_class);
const exception = env.alloc_object(exception_class);
try testing.expect(exception != null);
defer env.delete_local_ref(exception);
const throw_result = env.throw(exception);
try testing.expectEqual(jni.JNIResultType.ok, throw_result);
defer env.exception_clear();
try testing.expect(env.exception_check() == .jni_true);
}
test "JNI: ThrowNew" {
const env: *JNIEnv = get_testing_env();
const exception_class = env.find_class("java/lang/Exception");
try testing.expect(exception_class != null);
defer env.delete_local_ref(exception_class);
try testing.expect(env.exception_check() == .jni_false);
const throw_new_result = env.throw_new(exception_class, "");
try testing.expectEqual(jni.JNIResultType.ok, throw_new_result);
defer env.exception_clear();
try testing.expect(env.exception_check() == .jni_true);
}
test "JNI: ExceptionOccurred" {
const env: *JNIEnv = get_testing_env();
try testing.expect(env.exception_occurred() == null);
const exception_class = env.find_class("java/lang/Exception");
try testing.expect(exception_class != null);
defer env.delete_local_ref(exception_class);
const throw_new_result = env.throw_new(exception_class, "");
try testing.expectEqual(jni.JNIResultType.ok, throw_new_result);
const exception_occurred = env.exception_occurred();
try testing.expect(exception_occurred != null);
defer env.delete_local_ref(exception_occurred);
env.exception_clear();
try testing.expect(env.exception_occurred() == null);
}
test "JNI: ExceptionDescribe" {
const env: *JNIEnv = get_testing_env();
try testing.expect(env.exception_check() == .jni_false);
const exception_class = env.find_class("java/lang/Exception");
try testing.expect(exception_class != null);
defer env.delete_local_ref(exception_class);
const throw_new_result = env.throw_new(
exception_class,
"EXCEPTION DESCRIBED CORRECTLY",
);
try testing.expectEqual(jni.JNIResultType.ok, throw_new_result);
try testing.expect(env.exception_check() == .jni_true);
defer env.exception_clear();
env.exception_describe();
}
test "JNI: ExceptionClear" {
const env: *JNIEnv = get_testing_env();
// Asserting that calling it is a no-op here:
try testing.expect(env.exception_check() == .jni_false);
env.exception_clear();
try testing.expect(env.exception_check() == .jni_false);
const exception_class = env.find_class("java/lang/Exception");
try testing.expect(exception_class != null);
defer env.delete_local_ref(exception_class);
const throw_new_result = env.throw_new(exception_class, "");
try testing.expectEqual(jni.JNIResultType.ok, throw_new_result);
// Asserting that calling it clears the current exception:
try testing.expect(env.exception_check() == .jni_true);
env.exception_clear();
try testing.expect(env.exception_check() == .jni_false);
}
test "JNI: ExceptionCheck" {
const env: *JNIEnv = get_testing_env();
try testing.expect(env.exception_check() == .jni_false);
const object_class = env.find_class("java/lang/Object");
try testing.expect(object_class != null);
defer env.delete_local_ref(object_class);
const to_string = env.get_method_id(object_class, "toString", "()Ljava/lang/String;");
try testing.expect(to_string != null);
// Expected null reference exception:
const result = env.call_object_method(null, to_string, null);
try testing.expect(result == null);
try testing.expect(env.exception_check() == .jni_true);
env.exception_clear();
try testing.expect(env.exception_check() == .jni_false);
}
test "JNI: References" {
const env: *JNIEnv = get_testing_env();
const boolean_class = env.find_class("java/lang/Boolean");
try testing.expect(boolean_class != null);
defer env.delete_local_ref(boolean_class);
const obj = env.alloc_object(boolean_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
try testing.expect(env.get_object_ref_type(obj) == .local);
// Local ref:
{
const local_ref = env.new_local_ref(obj);
try testing.expect(local_ref != null);
try testing.expect(env.is_same_object(obj, local_ref) == .jni_true);
try testing.expect(env.get_object_ref_type(local_ref) == .local);
env.delete_local_ref(local_ref);
try testing.expect(env.new_local_ref(local_ref) == null);
}
// Global ref:
{
const global_ref = env.new_global_ref(obj);
try testing.expect(global_ref != null);
try testing.expect(env.is_same_object(obj, global_ref) == .jni_true);
try testing.expect(env.get_object_ref_type(global_ref) == .global);
env.delete_global_ref(global_ref);
try testing.expect(env.get_object_ref_type(global_ref) == .invalid);
}
// Weak global ref:
{
const weak_global_ref = env.new_weak_global_ref(obj);
try testing.expect(weak_global_ref != null);
try testing.expect(env.is_same_object(obj, weak_global_ref) == .jni_true);
try testing.expect(env.get_object_ref_type(weak_global_ref) == .weak_global);
env.delete_weak_global_ref(weak_global_ref);
try testing.expect(env.get_object_ref_type(weak_global_ref) == .invalid);
}
}
test "JNI: LocalFrame" {
const env: *JNIEnv = get_testing_env();
// Creating a new local frame.
const push_local_frame_result = env.push_local_frame(1);
try testing.expectEqual(jni.JNIResultType.ok, push_local_frame_result);
const ensure_local_capacity_result = env.ensure_local_capacity(10);
try testing.expectEqual(jni.JNIResultType.ok, ensure_local_capacity_result);
const boolean_class = env.find_class("java/lang/Boolean");
try testing.expect(boolean_class != null);
defer env.delete_local_ref(boolean_class);
const local_ref = env.alloc_object(boolean_class);
try testing.expect(local_ref != null);
// All local references must be invalidated after this frame being dropped,
// except by the frame result.
const pop_local_frame_result = env.pop_local_frame(local_ref);
try testing.expect(pop_local_frame_result != null);
defer env.delete_local_ref(pop_local_frame_result);
const valid_reference = env.get_object_ref_type(pop_local_frame_result);
try testing.expect(valid_reference == .local);
try testing.expect(pop_local_frame_result != local_ref);
}
test "JNI: AllocObject" {
const env: *JNIEnv = get_testing_env();
// Concrete type:
{
const boolean_class = env.find_class("java/lang/Boolean");
try testing.expect(boolean_class != null);
defer env.delete_local_ref(boolean_class);
const obj = env.alloc_object(boolean_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
}
// Interface:
{
const serializable_interface = env.find_class("java/io/Serializable");
try testing.expect(serializable_interface != null);
defer env.delete_local_ref(serializable_interface);
const obj = env.alloc_object(serializable_interface);
defer env.exception_clear();
try testing.expect(obj == null);
try testing.expect(env.exception_check() == .jni_true);
}
// Abstract class:
{
const calendar_abstract_class = env.find_class("java/util/Calendar");
try testing.expect(calendar_abstract_class != null);
defer env.delete_local_ref(calendar_abstract_class);
const obj = env.alloc_object(calendar_abstract_class);
defer env.exception_clear();
try testing.expect(obj == null);
try testing.expect(env.exception_check() == .jni_true);
}
}
test "JNI: NewObject" {
const env: *JNIEnv = get_testing_env();
const string_buffer_class = env.find_class("java/lang/StringBuffer");
try testing.expect(string_buffer_class != null);
defer env.delete_local_ref(string_buffer_class);
const capacity_ctor = env.get_method_id(string_buffer_class, "<init>", "(I)V");
try testing.expect(capacity_ctor != null);
const capacity: jni.JInt = 42;
const obj = env.new_object(
string_buffer_class,
capacity_ctor,
&[_]jni.JValue{jni.JValue.to_jvalue(capacity)},
);
try testing.expect(obj != null);
defer env.delete_local_ref(obj);
}
test "JNI: IsInstanceOf" {
const env: *JNIEnv = get_testing_env();
const boolean_class = env.find_class("java/lang/Boolean");
try testing.expect(boolean_class != null);
defer env.delete_local_ref(boolean_class);
const obj = env.alloc_object(boolean_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
try testing.expect(env.is_instance_of(obj, boolean_class) == .jni_true);
const long_class = env.find_class("java/lang/Long");
try testing.expect(long_class != null);
defer env.delete_local_ref(long_class);
try testing.expect(env.is_instance_of(obj, long_class) == .jni_false);
}
test "JNI: GetFieldId" {
const env: *JNIEnv = get_testing_env();
const boolean_class = env.find_class("java/lang/Boolean");
try testing.expect(boolean_class != null);
defer env.delete_local_ref(boolean_class);
const value_field_id = env.get_field_id(boolean_class, "value", "Z");
try testing.expect(value_field_id != null);
const invalid_field = env.get_field_id(boolean_class, "not_a_valid_field", "I");
defer env.exception_clear();
try testing.expect(invalid_field == null);
try testing.expect(env.exception_check() == .jni_true);
}
test "JNI: Get<Type>Field, Set<Type>Field" {
const env: *JNIEnv = get_testing_env();
// Boolean:
{
const boolean_class = env.find_class("java/lang/Boolean");
try testing.expect(boolean_class != null);
defer env.delete_local_ref(boolean_class);
const value_field_id = env.get_field_id(boolean_class, "value", "Z");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(boolean_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_boolean_field(obj, value_field_id);
try testing.expect(value_before == .jni_false);
env.set_boolean_field(obj, value_field_id, .jni_true);
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_boolean_field(obj, value_field_id);
try testing.expect(value_after == .jni_true);
}
// Byte:
{
const byte_class = env.find_class("java/lang/Byte");
try testing.expect(byte_class != null);
defer env.delete_local_ref(byte_class);
const value_field_id = env.get_field_id(byte_class, "value", "B");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(byte_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_byte_field(obj, value_field_id);
try testing.expect(value_before == 0);
env.set_byte_field(obj, value_field_id, 127);
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_byte_field(obj, value_field_id);
try testing.expect(value_after == 127);
}
// Char:
{
const char_class = env.find_class("java/lang/Character");
try testing.expect(char_class != null);
defer env.delete_local_ref(char_class);
const value_field_id = env.get_field_id(char_class, "value", "C");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(char_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_char_field(obj, value_field_id);
try testing.expect(value_before == 0);
env.set_char_field(obj, value_field_id, 'A');
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_char_field(obj, value_field_id);
try testing.expect(value_after == 'A');
}
// Short:
{
const short_class = env.find_class("java/lang/Short");
try testing.expect(short_class != null);
defer env.delete_local_ref(short_class);
const value_field_id = env.get_field_id(short_class, "value", "S");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(short_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_short_field(obj, value_field_id);
try testing.expect(value_before == 0);
env.set_short_field(obj, value_field_id, 9999);
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_short_field(obj, value_field_id);
try testing.expect(value_after == 9999);
}
// Int:
{
const int_class = env.find_class("java/lang/Integer");
try testing.expect(int_class != null);
defer env.delete_local_ref(int_class);
const value_field_id = env.get_field_id(int_class, "value", "I");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(int_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_int_field(obj, value_field_id);
try testing.expect(value_before == 0);
env.set_int_field(obj, value_field_id, 999_999);
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_int_field(obj, value_field_id);
try testing.expect(value_after == 999_999);
}
// Long:
{
const long_class = env.find_class("java/lang/Long");
try testing.expect(long_class != null);
defer env.delete_local_ref(long_class);
const value_field_id = env.get_field_id(long_class, "value", "J");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(long_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_long_field(obj, value_field_id);
try testing.expect(value_before == 0);
env.set_long_field(obj, value_field_id, 9_999_999_999);
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_long_field(obj, value_field_id);
try testing.expect(value_after == 9_999_999_999);
}
// Float:
{
const float_class = env.find_class("java/lang/Float");
try testing.expect(float_class != null);
defer env.delete_local_ref(float_class);
const value_field_id = env.get_field_id(float_class, "value", "F");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(float_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_float_field(obj, value_field_id);
try testing.expect(value_before == 0);
env.set_float_field(obj, value_field_id, 9.99);
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_float_field(obj, value_field_id);
try testing.expect(value_after == 9.99);
}
// Double:
{
const double_class = env.find_class("java/lang/Double");
try testing.expect(double_class != null);
defer env.delete_local_ref(double_class);
const value_field_id = env.get_field_id(double_class, "value", "D");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(double_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_double_field(obj, value_field_id);
try testing.expect(value_before == 0);
env.set_double_field(obj, value_field_id, 9.99);
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_double_field(obj, value_field_id);
try testing.expect(value_after == 9.99);
}
// Object:
{
const object_class = env.find_class("java/lang/Throwable");
try testing.expect(object_class != null);
defer env.delete_local_ref(object_class);
const value_field_id = env.get_field_id(object_class, "cause", "Ljava/lang/Throwable;");
try testing.expect(value_field_id != null);
const obj = env.alloc_object(object_class);
defer env.delete_local_ref(obj);
try testing.expect(obj != null);
const value_before = env.get_object_field(obj, value_field_id);
try testing.expect(value_before == null);
env.set_object_field(obj, value_field_id, obj);
try testing.expect(env.exception_check() == .jni_false);
const value_after = env.get_object_field(obj, value_field_id);
try testing.expect(value_after != null);
}
}
test "JNI: GetMethodId" {
const env: *JNIEnv = get_testing_env();
const object_class = env.find_class("java/lang/Throwable");
try testing.expect(object_class != null);
defer env.delete_local_ref(object_class);
const method_id = env.get_method_id(object_class, "toString", "()Ljava/lang/String;");
try testing.expect(method_id != null);
const invalid_method = env.get_method_id(object_class, "invalid_method", "()V");
defer env.exception_clear();
try testing.expect(invalid_method == null);
try testing.expect(env.exception_check() == .jni_true);
}
test "JNI: Call<Type>Method,CallNonVirtual<Type>Method" {
const env: *JNIEnv = get_testing_env();
const buffer_class = env.find_class("java/nio/ByteBuffer");
try testing.expect(buffer_class != null);
defer env.delete_local_ref(buffer_class);
const direct_buffer_class = env.find_class("java/nio/DirectByteBuffer");
try testing.expect(direct_buffer_class != null);
defer env.delete_local_ref(direct_buffer_class);
const element: u8 = 42;
var native_buffer = [_]u8{element} ** 256;
const buffer = env.new_direct_byte_buffer(&native_buffer, @intCast(native_buffer.len));
try testing.expect(buffer != null);
defer env.delete_local_ref(buffer);
// Byte:
{
const method_id = env.get_method_id(buffer_class, "get", "()B");
try testing.expect(method_id != null);
const non_virtual_method_id = env.get_method_id(direct_buffer_class, "get", "()B");
try testing.expect(non_virtual_method_id != null);
const expected: jni.JByte = @bitCast(element);
const read = env.call_byte_method(buffer, method_id, null);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read);
const read_non_virtual = env.call_nonvirtual_byte_method(
buffer,
direct_buffer_class,
non_virtual_method_id,
null,
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read_non_virtual);
}
// Short:
{
const method_id = env.get_method_id(buffer_class, "getShort", "()S");
try testing.expect(method_id != null);
const non_virtual_method_id = env.get_method_id(direct_buffer_class, "getShort", "()S");
try testing.expect(non_virtual_method_id != null);
const Packed = packed struct { a: u8, b: u8 };
const expected: jni.JShort = @bitCast(Packed{
.a = element,
.b = element,
});
const read = env.call_short_method(buffer, method_id, null);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read);
const read_non_virtual = env.call_nonvirtual_short_method(
buffer,
direct_buffer_class,
non_virtual_method_id,
null,
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read_non_virtual);
}
// Char:
{
const method_id = env.get_method_id(buffer_class, "getChar", "()C");
try testing.expect(method_id != null);
const non_virtual_method_id = env.get_method_id(direct_buffer_class, "getChar", "()C");
try testing.expect(non_virtual_method_id != null);
const Packed = packed struct { a: u8, b: u8 };
const expected: jni.JChar = @bitCast(Packed{
.a = element,
.b = element,
});
const read = env.call_char_method(buffer, method_id, null);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read);
const read_non_virtual = env.call_nonvirtual_char_method(
buffer,
direct_buffer_class,
non_virtual_method_id,
null,
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read_non_virtual);
}
// Int:
{
const method_id = env.get_method_id(buffer_class, "getInt", "()I");
try testing.expect(method_id != null);
const non_virtual_method_id = env.get_method_id(direct_buffer_class, "getInt", "()I");
try testing.expect(non_virtual_method_id != null);
const Packed = packed struct { a: u8, b: u8, c: u8, d: u8 };
const expected: jni.JInt = @bitCast(Packed{
.a = element,
.b = element,
.c = element,
.d = element,
});
const read = env.call_int_method(buffer, method_id, null);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read);
const read_non_virtual = env.call_nonvirtual_int_method(
buffer,
direct_buffer_class,
non_virtual_method_id,
null,
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read_non_virtual);
}
// Long:
{
const method_id = env.get_method_id(buffer_class, "getLong", "()J");
try testing.expect(method_id != null);
const non_virtual_method_id = env.get_method_id(direct_buffer_class, "getLong", "()J");
try testing.expect(non_virtual_method_id != null);
const Packed = packed struct { a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8, h: u8 };
const expected: jni.JLong = @bitCast(Packed{
.a = element,
.b = element,
.c = element,
.d = element,
.e = element,
.f = element,
.g = element,
.h = element,
});
const read = env.call_long_method(buffer, method_id, null);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read);
const read_non_virtual = env.call_nonvirtual_long_method(
buffer,
direct_buffer_class,
non_virtual_method_id,
null,
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read_non_virtual);
}
// Float:
{
const method_id = env.get_method_id(buffer_class, "getFloat", "()F");
try testing.expect(method_id != null);
const non_virtual_method_id = env.get_method_id(direct_buffer_class, "getFloat", "()F");
try testing.expect(non_virtual_method_id != null);
const Packed = packed struct { a: u8, b: u8, c: u8, d: u8 };
const expected: jni.JFloat = @bitCast(Packed{
.a = element,
.b = element,
.c = element,
.d = element,
});
const read = env.call_float_method(buffer, method_id, null);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read);
const read_non_virtual = env.call_nonvirtual_float_method(
buffer,
direct_buffer_class,
non_virtual_method_id,
null,
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read_non_virtual);
}
// Double:
{
const method_id = env.get_method_id(buffer_class, "getDouble", "()D");
try testing.expect(method_id != null);
const non_virtual_method_id = env.get_method_id(direct_buffer_class, "getDouble", "()D");
try testing.expect(non_virtual_method_id != null);
const Packed = packed struct { a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8, h: u8 };
const expected: jni.JDouble = @bitCast(Packed{
.a = element,
.b = element,
.c = element,
.d = element,
.e = element,
.f = element,
.g = element,
.h = element,
});
const read = env.call_double_method(buffer, method_id, null);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read);
const read_non_virtual = env.call_nonvirtual_double_method(
buffer,
direct_buffer_class,
non_virtual_method_id,
null,
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqual(expected, read_non_virtual);
}
// Object:
{
const method_id = env.get_method_id(buffer_class, "put", "(B)Ljava/nio/ByteBuffer;");
try testing.expect(method_id != null);
const non_virtual_method_id = env.get_method_id(
direct_buffer_class,
"put",
"(B)Ljava/nio/ByteBuffer;",
);
try testing.expect(non_virtual_method_id != null);
const put = env.call_object_method(buffer, method_id, &[_]jni.JValue{
jni.JValue.to_jvalue(@as(jni.JByte, 0)),
});
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(env.is_same_object(buffer, put) == .jni_true);
defer env.delete_local_ref(put);
const put_non_virtual = env.call_nonvirtual_object_method(
buffer,
direct_buffer_class,
non_virtual_method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(@as(jni.JByte, 0))},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(env.is_same_object(buffer, put_non_virtual) == .jni_true);
defer env.delete_local_ref(put_non_virtual);
}
}
test "JNI: GetStaticFieldId" {
const env: *JNIEnv = get_testing_env();
const boolean_class = env.find_class("java/lang/Boolean");
try testing.expect(boolean_class != null);
defer env.delete_local_ref(boolean_class);
const field_id = env.get_static_field_id(boolean_class, "serialVersionUID", "J");
try testing.expect(field_id != null);
const invalid_field_id = env.get_static_field_id(boolean_class, "invalid_field", "J");
defer env.exception_clear();
try testing.expect(invalid_field_id == null);
try testing.expect(env.exception_check() == .jni_true);
}
test "JNI: GetStatic<Type>Field, SetStatic<Type>Field" {
const env: *JNIEnv = get_testing_env();
// Byte:
{
const class = env.find_class("java/lang/Byte");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const field_id = env.get_static_field_id(class, "MIN_VALUE", "B");
try testing.expect(field_id != null);
const before = env.get_static_byte_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(before == -128);
env.set_static_byte_field(class, field_id, -127);
try testing.expect(env.exception_check() == .jni_false);
const after = env.get_static_byte_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(after == -127);
}
// Char:
{
const class = env.find_class("java/lang/Character");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const field_id = env.get_static_field_id(class, "MIN_VALUE", "C");
try testing.expect(field_id != null);
const before = env.get_static_char_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(before == 0);
env.set_static_char_field(class, field_id, 1);
try testing.expect(env.exception_check() == .jni_false);
const after = env.get_static_char_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(after == 1);
}
// Short:
{
const class = env.find_class("java/lang/Short");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const field_id = env.get_static_field_id(class, "MIN_VALUE", "S");
try testing.expect(field_id != null);
const before = env.get_static_short_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(before == -32768);
env.set_static_short_field(class, field_id, -32767);
try testing.expect(env.exception_check() == .jni_false);
const after = env.get_static_short_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(after == -32767);
}
// Int:
{
const class = env.find_class("java/lang/Integer");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const field_id = env.get_static_field_id(class, "MIN_VALUE", "I");
try testing.expect(field_id != null);
const before = env.get_static_int_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(before == -2147483648);
env.set_static_int_field(class, field_id, -2147483647);
try testing.expect(env.exception_check() == .jni_false);
const after = env.get_static_int_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(after == -2147483647);
}
// Long:
{
const class = env.find_class("java/lang/Long");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const field_id = env.get_static_field_id(class, "MIN_VALUE", "J");
try testing.expect(field_id != null);
const before = env.get_static_long_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(before == -9223372036854775808);
env.set_static_long_field(class, field_id, -9223372036854775807);
try testing.expect(env.exception_check() == .jni_false);
const after = env.get_static_long_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(after == -9223372036854775807);
}
// Float:
{
const class = env.find_class("java/lang/Float");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const field_id = env.get_static_field_id(class, "MIN_VALUE", "F");
try testing.expect(field_id != null);
const before = env.get_static_float_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(before == 1.4E-45);
env.set_static_float_field(class, field_id, 1.4E-44);
try testing.expect(env.exception_check() == .jni_false);
const after = env.get_static_float_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(after == 1.4E-44);
}
// Double:
{
const class = env.find_class("java/lang/Double");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const field_id = env.get_static_field_id(class, "MIN_VALUE", "D");
try testing.expect(field_id != null);
const before = env.get_static_double_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(before == 4.9E-324);
env.set_static_double_field(class, field_id, 4.9E-323);
try testing.expect(env.exception_check() == .jni_false);
const after = env.get_static_double_field(class, field_id);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(after == 4.9E-323);
}
}
test "JNI: GetStaticMethodId" {
const env: *JNIEnv = get_testing_env();
const boolean_class = env.find_class("java/lang/Boolean");
try testing.expect(boolean_class != null);
defer env.delete_local_ref(boolean_class);
const method_id = env.get_static_method_id(boolean_class, "valueOf", "(Z)Ljava/lang/Boolean;");
try testing.expect(method_id != null);
const invalid_method_id = env.get_static_method_id(boolean_class, "invalid_method", "()J");
defer env.exception_clear();
try testing.expect(invalid_method_id == null);
try testing.expect(env.exception_check() == .jni_true);
}
test "JNI: CallStatic<Type>Method" {
const env: *JNIEnv = get_testing_env();
const str = env.new_string_utf("1");
try testing.expect(str != null);
defer env.delete_local_ref(str);
// Boolean:
{
const class = env.find_class("java/lang/Boolean");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "parseBoolean", "(Ljava/lang/String;)Z");
try testing.expect(method_id != null);
const ret = env.call_static_boolean_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(str)},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(ret == .jni_false);
}
// Byte:
{
const class = env.find_class("java/lang/Byte");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "parseByte", "(Ljava/lang/String;)B");
try testing.expect(method_id != null);
const ret = env.call_static_byte_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(str)},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(ret == 1);
}
// Char:
{
const class = env.find_class("java/lang/Character");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "toLowerCase", "(C)C");
try testing.expect(method_id != null);
const ret = env.call_static_char_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(@as(jni.JChar, 'A'))},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(ret == 'a');
}
// Short:
{
const class = env.find_class("java/lang/Short");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "parseShort", "(Ljava/lang/String;)S");
try testing.expect(method_id != null);
const ret = env.call_static_short_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(str)},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(ret == 1);
}
// Int:
{
const class = env.find_class("java/lang/Integer");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "parseInt", "(Ljava/lang/String;)I");
try testing.expect(method_id != null);
const ret = env.call_static_int_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(str)},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(ret == 1);
}
// Long:
{
const class = env.find_class("java/lang/Long");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "parseLong", "(Ljava/lang/String;)J");
try testing.expect(method_id != null);
const ret = env.call_static_long_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(str)},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(ret == 1);
}
// Float:
{
const class = env.find_class("java/lang/Float");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "parseFloat", "(Ljava/lang/String;)F");
try testing.expect(method_id != null);
const ret = env.call_static_float_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(str)},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(ret == 1.0);
}
// Double:
{
const class = env.find_class("java/lang/Double");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "parseDouble", "(Ljava/lang/String;)D");
try testing.expect(method_id != null);
const ret = env.call_static_double_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(str)},
);
try testing.expect(env.exception_check() == .jni_false);
try testing.expect(ret == 1.0);
}
// Object:
{
const class = env.find_class("java/lang/String");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(
class,
"valueOf",
"(Ljava/lang/Object;)Ljava/lang/String;",
);
try testing.expect(method_id != null);
const ret = env.call_static_object_method(
class,
method_id,
&[_]jni.JValue{jni.JValue.to_jvalue(str)},
);
try testing.expect(env.exception_check() == .jni_false);
defer env.delete_local_ref(ret);
try testing.expect(env.is_instance_of(ret, class) == .jni_true);
}
// Void:
{
const class = env.find_class("java/lang/System");
try testing.expect(class != null);
defer env.delete_local_ref(class);
const method_id = env.get_static_method_id(class, "gc", "()V");
try testing.expect(method_id != null);
env.call_static_void_method(class, method_id, null);
try testing.expect(env.exception_check() == .jni_false);
}
}
test "JNI: strings" {
const env: *JNIEnv = get_testing_env();
const content: []const u16 = std.unicode.utf8ToUtf16LeStringLiteral("Hello utf16")[0..];
const string = env.new_string(
content.ptr,
@intCast(content.len),
);
try testing.expect(string != null);
defer env.delete_local_ref(string);
const len = env.get_string_length(string);
try testing.expectEqual(content.len, @as(usize, @intCast(len)));
const address = env.get_string_chars(string, null) orelse {
try testing.expect(false);
unreachable;
};
defer env.release_string_chars(string, address);
try testing.expectEqualSlices(u16, content[0..], address[0..@as(usize, @intCast(len))]);
}
test "JNI: strings utf" {
const env: *JNIEnv = get_testing_env();
const content = "Hello utf8";
const string = env.new_string_utf(content);
try testing.expect(string != null);
defer env.delete_local_ref(string);
const len = env.get_string_utf_length(string);
try testing.expectEqual(content.len, @as(usize, @intCast(len)));
const address = env.get_string_utf_chars(string, null) orelse {
try testing.expect(false);
unreachable;
};
defer env.release_string_utf_chars(string, address);
try testing.expectEqualSlices(u8, content[0..], address[0..@as(usize, @intCast(len))]);
}
test "JNI: GetStringRegion" {
const env: *JNIEnv = get_testing_env();
const content: []const u16 =
std.unicode.utf8ToUtf16LeStringLiteral("ABCDEFGHIJKLMNOPQRSTUVXYZ")[0..];
const string = env.new_string(
content.ptr,
@intCast(content.len),
);
try testing.expect(string != null);
defer env.delete_local_ref(string);
var buff: [10]jni.JChar = undefined;
env.get_string_region(string, 5, 10, &buff);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqualSlices(u16, content[5..][0..10], &buff);
}
test "JNI: GetStringUTFRegion" {
const env: *JNIEnv = get_testing_env();
const content = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
const string = env.new_string_utf(content);
try testing.expect(string != null);
defer env.delete_local_ref(string);
// From: https://docs.oracle.com/en/java/javase/17/docs/specs/jni/functions.html#getstringutfregion.
// The resulting number modified UTF-8 encoding characters may be greater than
// the given len argument. GetStringUTFLength() may be used to determine the
// maximum size of the required character buffer.
var buff: [content.len]u8 = undefined;
env.get_string_utf_region(string, 5, 10, &buff);
try testing.expect(env.exception_check() == .jni_false);
try testing.expectEqualSlices(u8, content[5..][0..10], buff[0..10]);
}
test "JNI: GetStringCritical" {
const env: *JNIEnv = get_testing_env();
const content: []const u16 =
std.unicode.utf8ToUtf16LeStringLiteral("ABCDEFGHIJKLMNOPQRSTUVXYZ")[0..];
const str = env.new_string(content.ptr, @intCast(content.len));
try testing.expect(str != null);
defer env.delete_local_ref(str);
const len = env.get_string_length(str);
try testing.expectEqual(content.len, @as(usize, @intCast(len)));
const region = env.get_string_critical(str, null) orelse {
try testing.expect(false);
unreachable;
};
defer env.release_string_critical(str, region);
try testing.expectEqualSlices(u16, content, region[0..@as(usize, @intCast(len))]);
}
test "JNI: DirectByteBuffer" {
const env: *JNIEnv = get_testing_env();
var native_buffer = blk: {
var array: [32]u8 = undefined;
var value: u8 = array.len;
for (&array) |*byte| {
value -= 1;
byte.* = value;
}
break :blk array;
};
const buffer = env.new_direct_byte_buffer(&native_buffer, native_buffer.len);
try testing.expect(buffer != null);
defer env.delete_local_ref(buffer);
const capacity = env.get_direct_buffer_capacity(buffer);
try testing.expect(capacity == native_buffer.len);
const address = env.get_direct_buffer_address(buffer) orelse {
try testing.expect(false);
unreachable;
};
try testing.expectEqualSlices(u8, &native_buffer, address[0..@as(usize, @intCast(capacity))]);
}
test "JNI: object array" {
const env: *JNIEnv = get_testing_env();
const object_class = env.find_class("java/lang/Object");
try testing.expect(object_class != null);
defer env.delete_local_ref(object_class);
const array = env.new_object_array(32, object_class, null);
try testing.expect(array != null);
defer env.delete_local_ref(array);
// ArrayIndexOutOfBoundsException:
env.set_object_array_element(array, -1, null);
try testing.expect(env.exception_check() == .jni_true);
env.exception_clear();
env.set_object_array_element(array, 32, null);
try testing.expect(env.exception_check() == .jni_true);
env.exception_clear();
// Valid indexes:
var index: jni.JInt = 0;
while (index < 32) : (index += 1) {
const obj_before = env.get_object_array_element(array, index);
try testing.expect(obj_before == null);
const obj = env.alloc_object(object_class);
try testing.expect(obj != null);
defer env.delete_local_ref(obj);
env.set_object_array_element(array, index, obj);
try testing.expect(env.exception_check() == .jni_false);
const obj_after = env.get_object_array_element(array, index);
try testing.expect(obj_after != null);
defer env.delete_local_ref(obj_after);
try testing.expect(env.is_same_object(obj, obj_after) == .jni_true);
}
}
test "JNI: primitive arrays" {
const ArrayTest = struct {
fn ArrayTestType(comptime PrimitiveType: type) type {
return struct {
fn cast(value: anytype) PrimitiveType {
return switch (PrimitiveType) {
jni.JBoolean => switch (value) {
0 => jni.JBoolean.jni_false,
else => jni.JBoolean.jni_true,
},
jni.JFloat, jni.JDouble => @floatFromInt(value),
else => @intCast(value),
};
}
fn get_array_elements(env: *jni.JNIEnv, array: jni.JArray) ?[*]PrimitiveType {
return switch (PrimitiveType) {
jni.JBoolean => env.get_boolean_array_elements(array, null),
jni.JByte => env.get_byte_array_elements(array, null),
jni.JShort => env.get_short_array_elements(array, null),
jni.JChar => env.get_char_array_elements(array, null),
jni.JInt => env.get_int_array_elements(array, null),
jni.JLong => env.get_long_array_elements(array, null),
jni.JFloat => env.get_float_array_elements(array, null),
jni.JDouble => env.get_double_array_elements(array, null),
else => unreachable,
};
}
fn release_array_elements(
env: *jni.JNIEnv,
array: jni.JArray,
elements: [*]PrimitiveType,
) void {
switch (PrimitiveType) {
jni.JBoolean => env.release_boolean_array_elements(
array,
elements,
.default,
),
jni.JByte => env.release_byte_array_elements(
array,
elements,
.default,
),
jni.JShort => env.release_short_array_elements(
array,
elements,
.default,
),
jni.JChar => env.release_char_array_elements(
array,
elements,
.default,
),
jni.JInt => env.release_int_array_elements(
array,
elements,
.default,
),
jni.JLong => env.release_long_array_elements(
array,
elements,
.default,
),
jni.JFloat => env.release_float_array_elements(
array,
elements,
.default,
),
jni.JDouble => env.release_double_array_elements(
array,
elements,
.default,
),
else => unreachable,
}
}
fn get_array_region(
env: *jni.JNIEnv,
array: jni.JArray,
start: jni.JSize,
len: jni.JSize,
buf: [*]PrimitiveType,
) void {
switch (PrimitiveType) {
jni.JBoolean => env.get_boolean_array_region(array, start, len, buf),
jni.JByte => env.get_byte_array_region(array, start, len, buf),
jni.JShort => env.get_short_array_region(array, start, len, buf),
jni.JChar => env.get_char_array_region(array, start, len, buf),
jni.JInt => env.get_int_array_region(array, start, len, buf),
jni.JLong => env.get_long_array_region(array, start, len, buf),
jni.JFloat => env.get_float_array_region(array, start, len, buf),
jni.JDouble => env.get_double_array_region(array, start, len, buf),
else => unreachable,
}
}
fn set_array_region(
env: *jni.JNIEnv,
array: jni.JArray,
start: jni.JSize,
len: jni.JSize,
buf: [*]PrimitiveType,
) void {
switch (PrimitiveType) {
jni.JBoolean => env.set_boolean_array_region(array, start, len, buf),
jni.JByte => env.set_byte_array_region(array, start, len, buf),
jni.JShort => env.set_short_array_region(array, start, len, buf),
jni.JChar => env.set_char_array_region(array, start, len, buf),
jni.JInt => env.set_int_array_region(array, start, len, buf),
jni.JLong => env.set_long_array_region(array, start, len, buf),
jni.JFloat => env.set_float_array_region(array, start, len, buf),
jni.JDouble => env.set_double_array_region(array, start, len, buf),
else => unreachable,
}
}
pub fn assert(env: *JNIEnv) !void {
const length = 32;
const array = switch (PrimitiveType) {
jni.JBoolean => env.new_boolean_array(length),
jni.JByte => env.new_byte_array(length),
jni.JChar => env.new_char_array(length),
jni.JShort => env.new_short_array(length),
jni.JInt => env.new_int_array(length),
jni.JLong => env.new_long_array(length),
jni.JFloat => env.new_float_array(length),
jni.JDouble => env.new_double_array(length),
else => unreachable,
};
try testing.expect(array != null);
defer env.delete_local_ref(array);
const len = env.get_array_length(array);
try testing.expect(len == length);
// Change the array:
{
const elements = get_array_elements(env, array) orelse {
try testing.expect(false);
unreachable;
};
defer release_array_elements(env, array, elements);
for (elements[0..@as(usize, @intCast(len))], 0..) |*element, i| {
try testing.expectEqual(cast(0), element.*);
element.* = cast(i);
}
}
// Check changes:
{
const elements = get_array_elements(env, array) orelse {
try testing.expect(false);
unreachable;
};
defer release_array_elements(env, array, elements);
for (elements[0..@as(usize, @intCast(len))], 0..) |element, i| {
try testing.expectEqual(cast(i), element);
}
}
// ArrayRegion:
{
var buffer: [10]PrimitiveType = undefined;
// ArrayIndexOutOfBoundsException:
get_array_region(env, array, -1, 10, &buffer);
try testing.expect(env.exception_check() == .jni_true);
env.exception_clear();
get_array_region(env, array, 0, 200, &buffer);
try testing.expect(env.exception_check() == .jni_true);
env.exception_clear();
// Correct bounds:
get_array_region(env, array, 5, 10, &buffer);
try testing.expect(env.exception_check() == .jni_false);
for (&buffer, 0..) |*element, i| {
try testing.expectEqual(cast(i + 5), element.*);
element.* = cast(i);
}
// ArrayIndexOutOfBoundsException:
set_array_region(env, array, -1, 10, &buffer);
try testing.expect(env.exception_check() == .jni_true);
env.exception_clear();
set_array_region(env, array, 0, 200, &buffer);
try testing.expect(env.exception_check() == .jni_true);
env.exception_clear();
// Correct bounds:
set_array_region(env, array, 5, 10, &buffer);
}
// Check changes
{
var buffer: [10]PrimitiveType = undefined;
get_array_region(env, array, 5, 10, &buffer);
try testing.expect(env.exception_check() == .jni_false);
for (buffer, 0..) |element, i| {
try testing.expectEqual(cast(i), element);
}
}
// Critical
{
const critical = env.get_primitive_array_critical(array, null) orelse {
try testing.expect(false);
unreachable;
};
defer env.release_primitive_array_critical(array, critical, .default);
const elements: [*]PrimitiveType = @ptrCast(@alignCast(critical));
for (elements[0..@intCast(len)], 0..) |*element, i| {
element.* = cast(i + 10);
}
}
// Check changes
{
const critical = env.get_primitive_array_critical(array, null) orelse {
try testing.expect(false);
unreachable;
};
defer env.release_primitive_array_critical(array, critical, .default);
const elements: [*]PrimitiveType = @ptrCast(@alignCast(critical));
for (elements[0..@intCast(len)], 0..) |element, i| {
try testing.expectEqual(cast(i + 10), element);
}
}
}
};
}
}.ArrayTestType;
const env: *JNIEnv = get_testing_env();
try ArrayTest(jni.JBoolean).assert(env);
try ArrayTest(jni.JByte).assert(env);
try ArrayTest(jni.JChar).assert(env);
try ArrayTest(jni.JShort).assert(env);
try ArrayTest(jni.JInt).assert(env);
try ArrayTest(jni.JLong).assert(env);
try ArrayTest(jni.JFloat).assert(env);
try ArrayTest(jni.JDouble).assert(env);
}
const get_testing_env = struct {
var init = std.once(jvm_create);
var env: *JNIEnv = undefined;
fn jvm_create() void {
var jvm: *jni.JavaVM = undefined;
var args = jni.JavaVMInitArgs{
.version = jni.jni_version_10,
.options_len = 0,
.options = null,
.ignore_unrecognized = .jni_true,
};
const jni_result = JavaVM.create_java_vm(&jvm, &env, &args);
std.debug.assert(jni_result == .ok);
}
pub fn get_env() *JNIEnv {
init.call();
return env;
}
}.get_env;
|
0 | repos/tigerbeetle/src/clients/java | repos/tigerbeetle/src/clients/java/src/client.zig | ///! Java Native Interfaces for TigerBeetle Client
///! Please refer to the JNI Best Practices Guide:
///! https://developer.ibm.com/articles/j-jni/
// IMPORTANT: Running code from a native thread, the JVM will
// never automatically free local references until the thread detaches.
// To avoid leaks, we *ALWAYS* free all references we acquire,
// even local references, so we don't need to distinguish if the code
// is called from the JVM or the native thread via callback.
const std = @import("std");
const builtin = @import("builtin");
const jni = @import("jni.zig");
const tb = @import("vsr").tb_client;
const log = std.log.scoped(.tb_client_jni);
const assert = std.debug.assert;
const jni_version = jni.jni_version_10;
const global_allocator = if (builtin.link_libc)
std.heap.c_allocator
else
@compileError("tb_client must be built with libc");
/// Context for a client instance.
const Context = struct {
jvm: *jni.JavaVM,
client: tb.tb_client_t,
};
/// NativeClient implementation.
const NativeClient = struct {
/// On JVM loads this library.
fn on_load(vm: *jni.JavaVM) jni.JInt {
const env = JNIHelper.get_env(vm);
ReflectionHelper.load(env);
return jni_version;
}
/// On JVM unloads this library.
fn on_unload(vm: *jni.JavaVM) void {
const env = JNIHelper.get_env(vm);
ReflectionHelper.unload(env);
}
/// Native clientInit and clientInitEcho implementation.
fn client_init(
comptime echo_client: bool,
env: *jni.JNIEnv,
cluster_id: u128,
addresses_obj: jni.JString,
) ?*Context {
const addresses = JNIHelper.get_string_utf(env, addresses_obj) orelse {
ReflectionHelper.initialization_exception_throw(
env,
tb.tb_status_t.address_invalid,
);
return null;
};
defer env.release_string_utf_chars(addresses_obj, addresses.ptr);
const context = global_allocator.create(Context) catch {
ReflectionHelper.initialization_exception_throw(env, tb.tb_status_t.out_of_memory);
return null;
};
errdefer global_allocator.destroy(context);
const init_fn = if (echo_client) tb.init_echo else tb.init;
const client = init_fn(
global_allocator,
cluster_id,
addresses,
@intFromPtr(context),
on_completion,
) catch |err| {
const status = tb.init_error_to_status(err);
ReflectionHelper.initialization_exception_throw(env, status);
return null;
};
context.* = .{
.jvm = JNIHelper.get_java_vm(env),
.client = client,
};
return context;
}
/// Native clientDeinit implementation.
fn client_deinit(context: *Context) void {
defer global_allocator.destroy(context);
tb.deinit(context.client);
}
/// Native submit implementation.
fn submit(
env: *jni.JNIEnv,
context: *Context,
request_obj: jni.JObject,
) void {
assert(request_obj != null);
const operation = ReflectionHelper.get_request_operation(env, request_obj);
const send_buffer: []u8 = ReflectionHelper.get_send_buffer_slice(env, request_obj) orelse {
ReflectionHelper.assertion_error_throw(
env,
"Request.sendBuffer is null or invalid",
);
return undefined;
};
const packet = global_allocator.create(tb.tb_packet_t) catch {
ReflectionHelper.assertion_error_throw(env, "Request could not allocate a packet");
return undefined;
};
// Holds a global reference to prevent GC before the callback.
const global_ref = JNIHelper.new_global_reference(env, request_obj);
packet.operation = operation;
packet.user_data = global_ref;
packet.data = send_buffer.ptr;
packet.data_size = @intCast(send_buffer.len);
packet.next = null;
packet.status = .ok;
tb.submit(context.client, packet);
}
/// Completion callback, always called from the native thread.
fn on_completion(
context_ptr: usize,
client: tb.tb_client_t,
packet: *tb.tb_packet_t,
result_ptr: ?[*]const u8,
result_len: u32,
) callconv(.C) void {
_ = client;
const context: *Context = @ptrFromInt(context_ptr);
var env = JNIHelper.attach_current_thread(context.jvm);
// Retrieves the request instance, and drops the GC reference.
assert(packet.user_data != null);
const request_obj: jni.JObject = @ptrCast(packet.user_data);
defer env.delete_global_ref(request_obj);
// Extract the packet details before freeing it.
const packet_operation = packet.operation;
const packet_status = packet.status;
global_allocator.destroy(packet);
if (result_len > 0) {
switch (packet_status) {
.ok => if (result_ptr) |ptr| {
// Copying the reply before returning from the callback.
ReflectionHelper.set_reply_buffer(
env,
request_obj,
ptr[0..@as(usize, @intCast(result_len))],
);
},
else => {},
}
}
ReflectionHelper.end_request(
env,
request_obj,
packet_operation,
packet_status,
);
}
};
// Declares and exports all functions using the JNI naming/calling convention.
comptime {
// https://docs.oracle.com/en/java/javase/17/docs/specs/jni/design.html#compiling-loading-and-linking-native-methods.
const prefix = "Java_com_tigerbeetle_NativeClient_";
const Exports = struct {
fn on_load(vm: *jni.JavaVM) callconv(jni.JNICALL) jni.JInt {
return NativeClient.on_load(vm);
}
fn on_unload(vm: *jni.JavaVM) callconv(jni.JNICALL) void {
NativeClient.on_unload(vm);
}
fn client_init(
env: *jni.JNIEnv,
class: jni.JClass,
cluster_id: jni.JByteArray,
addresses: jni.JString,
) callconv(jni.JNICALL) jni.JLong {
_ = class;
assert(env.get_array_length(cluster_id) == 16);
const cluster_id_elements = env.get_byte_array_elements(cluster_id, null).?;
defer env.release_byte_array_elements(cluster_id, cluster_id_elements, .abort);
const context = NativeClient.client_init(
false,
env,
@bitCast(cluster_id_elements[0..16].*),
addresses,
);
return @bitCast(@intFromPtr(context));
}
fn client_init_echo(
env: *jni.JNIEnv,
class: jni.JClass,
cluster_id: jni.JByteArray,
addresses: jni.JString,
) callconv(jni.JNICALL) jni.JLong {
_ = class;
assert(env.get_array_length(cluster_id) == 16);
const cluster_id_elements = env.get_byte_array_elements(cluster_id, null).?;
defer env.release_byte_array_elements(cluster_id, cluster_id_elements, .abort);
const context = NativeClient.client_init(
true,
env,
@as(u128, @bitCast(cluster_id_elements[0..16].*)),
addresses,
);
return @bitCast(@intFromPtr(context));
}
fn client_deinit(
env: *jni.JNIEnv,
class: jni.JClass,
context_handle: jni.JLong,
) callconv(jni.JNICALL) void {
_ = env;
_ = class;
NativeClient.client_deinit(@ptrFromInt(@as(usize, @bitCast(context_handle))));
}
fn submit(
env: *jni.JNIEnv,
class: jni.JClass,
context_handle: jni.JLong,
request_obj: jni.JObject,
) callconv(jni.JNICALL) void {
_ = class;
assert(context_handle != 0);
NativeClient.submit(
env,
@ptrFromInt(@as(usize, @bitCast(context_handle))),
request_obj,
);
}
};
@export(Exports.on_load, .{ .name = "JNI_OnLoad", .linkage = .strong });
@export(Exports.on_unload, .{ .name = "JNI_OnUnload", .linkage = .strong });
@export(Exports.client_init, .{ .name = prefix ++ "clientInit", .linkage = .strong });
@export(Exports.client_init_echo, .{ .name = prefix ++ "clientInitEcho", .linkage = .strong });
@export(Exports.client_deinit, .{ .name = prefix ++ "clientDeinit", .linkage = .strong });
@export(Exports.submit, .{ .name = prefix ++ "submit", .linkage = .strong });
}
/// Reflection helper and metadata cache.
const ReflectionHelper = struct {
var initialization_exception_class: jni.JClass = null;
var initialization_exception_ctor_id: jni.JMethodID = null;
var assertion_error_class: jni.JClass = null;
var request_class: jni.JClass = null;
var request_send_buffer_field_id: jni.JFieldID = null;
var request_send_buffer_len_field_id: jni.JFieldID = null;
var request_reply_buffer_field_id: jni.JFieldID = null;
var request_operation_method_id: jni.JMethodID = null;
var request_end_request_method_id: jni.JMethodID = null;
pub fn load(env: *jni.JNIEnv) void {
// Asserting we are not initialized yet:
assert(initialization_exception_class == null);
assert(initialization_exception_ctor_id == null);
assert(assertion_error_class == null);
assert(request_class == null);
assert(request_send_buffer_field_id == null);
assert(request_send_buffer_len_field_id == null);
assert(request_reply_buffer_field_id == null);
assert(request_operation_method_id == null);
assert(request_end_request_method_id == null);
initialization_exception_class = JNIHelper.find_class(
env,
"com/tigerbeetle/InitializationException",
);
initialization_exception_ctor_id = JNIHelper.find_method(
env,
initialization_exception_class,
"<init>",
"(I)V",
);
assertion_error_class = JNIHelper.find_class(
env,
"com/tigerbeetle/AssertionError",
);
request_class = JNIHelper.find_class(
env,
"com/tigerbeetle/Request",
);
request_send_buffer_field_id = JNIHelper.find_field(
env,
request_class,
"sendBuffer",
"Ljava/nio/ByteBuffer;",
);
request_send_buffer_len_field_id = JNIHelper.find_field(
env,
request_class,
"sendBufferLen",
"J",
);
request_reply_buffer_field_id = JNIHelper.find_field(
env,
request_class,
"replyBuffer",
"[B",
);
request_operation_method_id = JNIHelper.find_method(
env,
request_class,
"getOperation",
"()B",
);
request_end_request_method_id = JNIHelper.find_method(
env,
request_class,
"endRequest",
"(BB)V",
);
// Asserting we are full initialized:
assert(initialization_exception_class != null);
assert(initialization_exception_ctor_id != null);
assert(assertion_error_class != null);
assert(request_class != null);
assert(request_send_buffer_field_id != null);
assert(request_send_buffer_len_field_id != null);
assert(request_reply_buffer_field_id != null);
assert(request_operation_method_id != null);
assert(request_end_request_method_id != null);
}
pub fn unload(env: *jni.JNIEnv) void {
env.delete_global_ref(initialization_exception_class);
env.delete_global_ref(assertion_error_class);
env.delete_global_ref(request_class);
initialization_exception_class = null;
initialization_exception_ctor_id = null;
assertion_error_class = null;
request_class = null;
request_send_buffer_field_id = null;
request_send_buffer_len_field_id = null;
request_reply_buffer_field_id = null;
request_operation_method_id = null;
request_end_request_method_id = null;
}
pub fn initialization_exception_throw(env: *jni.JNIEnv, status: tb.tb_status_t) void {
assert(initialization_exception_class != null);
assert(initialization_exception_ctor_id != null);
const exception = env.new_object(
initialization_exception_class,
initialization_exception_ctor_id,
&[_]jni.JValue{jni.JValue.to_jvalue(@as(jni.JInt, @bitCast(@intFromEnum(status))))},
) orelse {
// It's unexpected here: we did not initialize correctly or the JVM is out of memory.
JNIHelper.vm_panic(
env,
"Unexpected error creating a new InitializationException.",
.{},
);
};
defer env.delete_local_ref(exception);
const jni_result = env.throw(exception);
JNIHelper.check_jni_result(
env,
jni_result,
"Unexpected error throwing InitializationException.",
.{},
);
assert(env.exception_check() == .jni_true);
}
pub fn assertion_error_throw(env: *jni.JNIEnv, message: [:0]const u8) void {
assert(assertion_error_class != null);
const jni_result = env.throw_new(assertion_error_class, message.ptr);
JNIHelper.check_jni_result(
env,
jni_result,
"Unexpected error throwing AssertionError.",
.{},
);
assert(env.exception_check() == .jni_true);
}
pub fn get_send_buffer_slice(env: *jni.JNIEnv, this_obj: jni.JObject) ?[]u8 {
assert(this_obj != null);
assert(request_send_buffer_field_id != null);
assert(request_send_buffer_len_field_id != null);
const buffer_obj = env.get_object_field(this_obj, request_send_buffer_field_id) orelse
return null;
defer env.delete_local_ref(buffer_obj);
const direct_buffer: []u8 = JNIHelper.get_direct_buffer(env, buffer_obj) orelse
return null;
const buffer_len = env.get_long_field(this_obj, request_send_buffer_len_field_id);
if (buffer_len < 0 or buffer_len > direct_buffer.len)
return null;
return direct_buffer[0..@as(usize, @intCast(buffer_len))];
}
pub fn set_reply_buffer(env: *jni.JNIEnv, this_obj: jni.JObject, reply: []const u8) void {
assert(this_obj != null);
assert(request_reply_buffer_field_id != null);
assert(reply.len > 0);
const reply_buffer_obj = env.new_byte_array(
@intCast(reply.len),
) orelse {
// Cannot allocate an array, it's likely the JVM has run out of resources.
// Printing the buffer size here just to help diagnosing how much memory was required.
JNIHelper.vm_panic(
env,
"Unexpected error calling NewByteArray len={}",
.{reply.len},
);
};
defer env.delete_local_ref(reply_buffer_obj);
env.set_byte_array_region(
reply_buffer_obj,
0,
@intCast(reply.len),
@ptrCast(reply.ptr),
);
if (env.exception_check() == .jni_true) {
// Since out-of-bounds isn't expected here, we can only panic if it fails.
JNIHelper.vm_panic(
env,
"Unexpected exception calling JNIEnv.SetByteArrayRegion len={}",
.{reply.len},
);
}
// Setting the request with the reply.
env.set_object_field(
this_obj,
request_reply_buffer_field_id,
reply_buffer_obj,
);
}
pub fn get_request_operation(env: *jni.JNIEnv, this_obj: jni.JObject) u8 {
assert(this_obj != null);
assert(request_class != null);
assert(request_operation_method_id != null);
const value = env.call_nonvirtual_byte_method(
this_obj,
request_class,
request_operation_method_id,
null,
);
if (env.exception_check() == .jni_true) {
// This method isn't expected to throw any exception.
JNIHelper.vm_panic(
env,
"Unexpected exception calling NativeClient.getOperation",
.{},
);
}
return @bitCast(value);
}
pub fn end_request(
env: *jni.JNIEnv,
this_obj: jni.JObject,
packet_operation: u8,
packet_status: tb.tb_packet_status_t,
) void {
assert(this_obj != null);
assert(request_class != null);
assert(request_end_request_method_id != null);
env.call_nonvirtual_void_method(
this_obj,
request_class,
request_end_request_method_id,
&[_]jni.JValue{
jni.JValue.to_jvalue(@as(jni.JByte, @bitCast(packet_operation))),
jni.JValue.to_jvalue(@as(jni.JByte, @bitCast(@intFromEnum(packet_status)))),
},
);
if (env.exception_check() == .jni_true) {
// The "endRequest" method isn't expected to throw any exception,
// We can't rethrow here, since this function is called from the native callback.
JNIHelper.vm_panic(
env,
"Unexpected exception calling NativeClient.endRequest",
.{},
);
}
}
};
/// Common functions for handling errors and results in JNI calls.
const JNIHelper = struct {
pub inline fn get_env(vm: *jni.JavaVM) *jni.JNIEnv {
var env: *jni.JNIEnv = undefined;
const jni_result = vm.get_env(&env, jni_version);
if (jni_result != .ok) {
const message = "Unexpected result calling JavaVM.GetEnv";
log.err(
message ++ "; Error = {} ({s})",
.{ @intFromEnum(jni_result), @tagName(jni_result) },
);
@panic("JNI: " ++ message);
}
return env;
}
pub inline fn attach_current_thread(jvm: *jni.JavaVM) *jni.JNIEnv {
var env: *jni.JNIEnv = undefined;
const jni_result = jvm.attach_current_thread_as_daemon(&env, null);
if (jni_result != .ok) {
const message = "Unexpected result calling JavaVM.AttachCurrentThreadAsDaemon";
log.err(
message ++ "; Error = {} ({s})",
.{ @intFromEnum(jni_result), @tagName(jni_result) },
);
@panic("JNI: " ++ message);
}
return env;
}
pub inline fn get_java_vm(env: *jni.JNIEnv) *jni.JavaVM {
var jvm: *jni.JavaVM = undefined;
const jni_result = env.get_java_vm(&jvm);
check_jni_result(
env,
jni_result,
"Unexpected result calling JNIEnv.GetJavaVM",
.{},
);
return jvm;
}
pub inline fn vm_panic(
env: *jni.JNIEnv,
comptime fmt: []const u8,
args: anytype,
) noreturn {
env.exception_describe();
log.err(fmt, args);
var buf: [256]u8 = undefined;
const message: [:0]const u8 = std.fmt.bufPrintZ(&buf, fmt, args) catch |err| switch (err) {
error.NoSpaceLeft => blk: {
buf[255] = 0;
break :blk @ptrCast(buf[0..255]);
},
};
env.fatal_error(message.ptr);
}
pub inline fn check_jni_result(
env: *jni.JNIEnv,
jni_result: jni.JNIResultType,
comptime fmt: []const u8,
args: anytype,
) void {
if (jni_result != .ok) {
vm_panic(
env,
fmt ++ "; Error = {} ({s})",
args ++ .{ @intFromEnum(jni_result), @tagName(jni_result) },
);
}
}
pub inline fn find_class(env: *jni.JNIEnv, comptime class_name: [:0]const u8) jni.JClass {
const class_obj = env.find_class(class_name.ptr) orelse {
vm_panic(
env,
"Unexpected result calling JNIEnv.FindClass for {s}",
.{class_name},
);
};
defer env.delete_local_ref(class_obj);
return env.new_global_ref(class_obj) orelse {
vm_panic(
env,
"Unexpected result calling JNIEnv.NewGlobalRef for {s}",
.{class_name},
);
};
}
pub inline fn find_field(
env: *jni.JNIEnv,
class: jni.JClass,
comptime name: [:0]const u8,
comptime signature: [:0]const u8,
) jni.JFieldID {
return env.get_field_id(class, name.ptr, signature.ptr) orelse
vm_panic(
env,
"Field could not be found {s} {s}",
.{ name, signature },
);
}
pub inline fn find_method(
env: *jni.JNIEnv,
class: jni.JClass,
comptime name: [:0]const u8,
comptime signature: [:0]const u8,
) jni.JMethodID {
return env.get_method_id(class, name.ptr, signature.ptr) orelse
vm_panic(
env,
"Method could not be found {s} {s}",
.{ name, signature },
);
}
pub inline fn get_direct_buffer(
env: *jni.JNIEnv,
buffer_obj: jni.JObject,
) ?[]u8 {
const buffer_capacity = env.get_direct_buffer_capacity(buffer_obj);
if (buffer_capacity < 0) return null;
const buffer_address = env.get_direct_buffer_address(buffer_obj) orelse return null;
return buffer_address[0..@as(u32, @intCast(buffer_capacity))];
}
pub inline fn new_global_reference(env: *jni.JNIEnv, obj: jni.JObject) jni.JObject {
return env.new_global_ref(obj) orelse {
// NewGlobalRef fails only when the JVM runs out of memory.
JNIHelper.vm_panic(env, "Unexpected result calling JNIEnv.NewGlobalRef", .{});
};
}
pub inline fn get_string_utf(env: *jni.JNIEnv, string: jni.JString) ?[:0]const u8 {
if (string == null) return null;
const address = env.get_string_utf_chars(string, null) orelse return null;
const length = env.get_string_utf_length(string);
if (length < 0) return null;
return @ptrCast(address[0..@as(usize, @intCast(length))]);
}
};
|
0 | repos/tigerbeetle/src/clients/java/src/main | repos/tigerbeetle/src/clients/java/src/main/java/module-info.java | module com.tigerbeetle {
exports com.tigerbeetle;
} |
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/QueryFilter.java | package com.tigerbeetle;
public final class QueryFilter {
// @formatter:off
/*
* Summary:
*
* Wraps the `QueryFilterBatch` auto-generated binding in a single-item batch.
* Since `queryAccounts()` and `queryTransfers()` expects only one item, we avoid
* exposing the `Batch` class externally.
*
* This is an ad-hoc feature meant to be replaced by a proper querying API shortly,
* therefore, it is not worth the effort to modify the binding generator to emit single-item batchs.
*
*/
// @formatter:on
QueryFilterBatch batch;
public QueryFilter() {
this.batch = new QueryFilterBatch(1);
this.batch.add();
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_128">user_data_128</a>
*/
public byte[] getUserData128() {
return this.batch.getUserData128();
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value is to be
* retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_128">user_data_128</a>
*/
public long getUserData128(final UInt128 part) {
return this.batch.getUserData128(part);
}
/**
* @param userData128 an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code userData128} is not 16 bytes long.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_128">user_data_128</a>
*/
public void setUserData128(final byte[] userData128) {
this.batch.setUserData128(userData128);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_128">user_data_128</a>
*/
public void setUserData128(final long leastSignificant, final long mostSignificant) {
this.batch.setUserData128(leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_128">user_data_128</a>
*/
public void setUserData128(final long leastSignificant) {
this.batch.setUserData128(leastSignificant);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_64">user_data_64</a>
*/
public long getUserData64() {
return this.batch.getUserData64();
}
/**
* @param userData64
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_64">user_data_64</a>
*/
public void setUserData64(final long userData64) {
this.batch.setUserData64(userData64);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_32">user_data_32</a>
*/
public int getUserData32() {
return this.batch.getUserData32();
}
/**
* @param userData32
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter#user_data_32">user_data_32</a>
*/
public void setUserData32(final int userData32) {
this.batch.setUserData32(userData32);
}
/**
* @see <a href="https://docs.tigerbeetle.com/reference/query_filter#ledger">ledger</a>
*/
public int getLedger() {
return this.batch.getLedger();
}
/**
* @param ledger
* @see <a href="https://docs.tigerbeetle.com/reference/query_filter#ledger">ledger</a>
*/
public void setLedger(final int ledger) {
this.batch.setLedger(ledger);
}
/**
* @see <a href="https://docs.tigerbeetle.com/reference/query_filter#code">code</a>
*/
public int getCode() {
return this.batch.getCode();
}
/**
* @param code
* @see <a href="https://docs.tigerbeetle.com/reference/query_filter#code">code</a>
*/
public void setCode(final int code) {
this.batch.setCode(code);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter-filter#timestamp_min">timestamp_min</a>
*/
public long getTimestampMin() {
return batch.getTimestampMin();
}
/**
* @param timestamp
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter-filter#timestamp_min">timestamp_min</a>
*/
public void setTimestampMin(final long timestamp) {
batch.setTimestampMin(timestamp);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter-filter#timestamp_max">timestamp_max</a>
*/
public long getTimestampMax() {
return batch.getTimestampMax();
}
/**
* @param timestamp
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter-filter#timestamp_max">timestamp_max</a>
*/
public void setTimestampMax(final long timestamp) {
batch.setTimestampMax(timestamp);
}
/**
* @see <a href= "https://docs.tigerbeetle.com/reference/query_filter-filter#limit">limit</a>
*/
public int getLimit() {
return batch.getLimit();
}
/**
* @param limit
* @see <a href= "https://docs.tigerbeetle.com/reference/query_filter-filter#limit">limit</a>
*/
public void setLimit(final int limit) {
batch.setLimit(limit);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter-filter#flagsreversed">reversed</a>
*/
public boolean getReversed() {
return getFlags(QueryFilterFlags.REVERSED);
}
/**
* @param value
* @see <a href=
* "https://docs.tigerbeetle.com/reference/query_filter-filter#flagsreversed">reversed</a>
*/
public void setReversed(boolean value) {
setFlags(QueryFilterFlags.REVERSED, value);
}
boolean getFlags(final int flag) {
final var value = batch.getFlags();
return (value & flag) != 0;
}
void setFlags(final int flag, final boolean enabled) {
var value = batch.getFlags();
if (enabled)
value |= flag;
else
value &= ~flag;
batch.setFlags(value);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/Request.java | package com.tigerbeetle;
import java.lang.annotation.Native;
import java.nio.ByteBuffer;
import java.util.Objects;
abstract class Request<TResponse extends Batch> {
// @formatter:off
/*
* Overview:
*
* Implements a context that will be used to submit the request and to signal the completion.
* A reference to this class is stored by the JNI side in the "user_data" field when calling "tb_client_submit",
* meaning that no GC will occur before the callback completion
*
* Memory:
*
* - Holds the request body until the completion to be accessible by the C client.
* - Copies the response body to be exposed to the application.
*
* Completion:
*
* - See AsyncRequest.java and BlockingRequest.java
*
*/
// @formatter:on
enum Operations {
// TODO Auto-generate these.
PULSE(128),
CREATE_ACCOUNTS(129),
CREATE_TRANSFERS(130),
LOOKUP_ACCOUNTS(131),
LOOKUP_TRANSFERS(132),
GET_ACCOUNT_TRANSFERS(133),
GET_ACCOUNT_BALANCES(134),
QUERY_ACCOUNTS(135),
QUERY_TRANSFERS(136),
ECHO_ACCOUNTS(129),
ECHO_TRANSFERS(130);
byte value;
Operations(int value) {
this.value = (byte) value;
}
}
// Used only by the JNI side
@Native
private final ByteBuffer sendBuffer;
@Native
private final long sendBufferLen;
@Native
private byte[] replyBuffer;
private final NativeClient nativeClient;
private final Operations operation;
private final int requestLen;
protected Request(final NativeClient nativeClient, final Operations operation,
final Batch batch) {
Objects.requireNonNull(nativeClient, "Client cannot be null");
Objects.requireNonNull(batch, "Batch cannot be null");
this.nativeClient = nativeClient;
this.operation = operation;
this.requestLen = batch.getLength();
this.sendBuffer = batch.getBuffer();
this.sendBufferLen = batch.getBufferLen();
this.replyBuffer = null;
if (this.sendBufferLen == 0 || this.requestLen == 0)
throw new IllegalArgumentException("Empty batch");
}
public void beginRequest() {
nativeClient.submit(this);
}
// Unchecked: Since we just support a limited set of operations, it is safe to cast the
// result to T[]
@SuppressWarnings("unchecked")
void endRequest(final byte receivedOperation, final byte status) {
// This method is called from the JNI side, on the tb_client thread
// We CAN'T throw any exception here, any event must be stored and
// handled from the user's thread on the completion.
Batch result = null;
Throwable exception = null;
try {
if (receivedOperation != operation.value) {
exception =
new AssertionError("Unexpected callback operation: expected=%d, actual=%d",
operation.value, receivedOperation);
} else if (status != PacketStatus.Ok.value) {
if (status == PacketStatus.ClientShutdown.value) {
exception = new IllegalStateException("Client is closed");
} else {
exception = new RequestException(status);
}
} else {
switch (operation) {
case CREATE_ACCOUNTS: {
result = replyBuffer == null ? CreateAccountResultBatch.EMPTY
: new CreateAccountResultBatch(ByteBuffer.wrap(replyBuffer));
exception = checkResultLength(result);
break;
}
case CREATE_TRANSFERS: {
result = replyBuffer == null ? CreateTransferResultBatch.EMPTY
: new CreateTransferResultBatch(ByteBuffer.wrap(replyBuffer));
exception = checkResultLength(result);
break;
}
case ECHO_ACCOUNTS:
case LOOKUP_ACCOUNTS: {
result = replyBuffer == null ? AccountBatch.EMPTY
: new AccountBatch(ByteBuffer.wrap(replyBuffer));
exception = checkResultLength(result);
break;
}
case ECHO_TRANSFERS:
case LOOKUP_TRANSFERS: {
result = replyBuffer == null ? TransferBatch.EMPTY
: new TransferBatch(ByteBuffer.wrap(replyBuffer));
exception = checkResultLength(result);
break;
}
case GET_ACCOUNT_TRANSFERS: {
result = replyBuffer == null ? TransferBatch.EMPTY
: new TransferBatch(ByteBuffer.wrap(replyBuffer));
break;
}
case GET_ACCOUNT_BALANCES: {
result = replyBuffer == null ? AccountBalanceBatch.EMPTY
: new AccountBalanceBatch(ByteBuffer.wrap(replyBuffer));
break;
}
case QUERY_ACCOUNTS: {
result = replyBuffer == null ? AccountBatch.EMPTY
: new AccountBatch(ByteBuffer.wrap(replyBuffer));
break;
}
case QUERY_TRANSFERS: {
result = replyBuffer == null ? TransferBatch.EMPTY
: new TransferBatch(ByteBuffer.wrap(replyBuffer));
break;
}
default: {
exception = new AssertionError("Unknown operation %d", operation);
break;
}
}
}
} catch (Throwable any) {
exception = any;
}
if (exception == null) {
setResult((TResponse) result);
} else {
setException(exception);
}
}
private AssertionError checkResultLength(Batch result) {
if (result.getLength() > requestLen) {
return new AssertionError(
"Amount of results is greater than the amount of requests: resultLen=%d, requestLen=%d",
result.getLength(), requestLen);
} else {
return null;
}
}
// Unused: Used by unit tests.
@SuppressWarnings("unused")
void setReplyBuffer(byte[] buffer) {
this.replyBuffer = buffer;
}
// Unused: Used by the JNI side.
@SuppressWarnings("unused")
byte getOperation() {
return this.operation.value;
}
protected abstract void setResult(final TResponse result);
protected abstract void setException(final Throwable exception);
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/AccountFilterFlags.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
interface AccountFilterFlags {
int NONE = (int) 0;
int DEBITS = (int) (1 << 0);
int CREDITS = (int) (1 << 1);
int REVERSED = (int) (1 << 2);
static boolean hasDebits(final int flags) {
return (flags & DEBITS) == DEBITS;
}
static boolean hasCredits(final int flags) {
return (flags & CREDITS) == CREDITS;
}
static boolean hasReversed(final int flags) {
return (flags & REVERSED) == REVERSED;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/CreateAccountResultBatch.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
import java.nio.ByteBuffer;
public final class CreateAccountResultBatch extends Batch {
interface Struct {
int SIZE = 8;
int Index = 0;
int Result = 4;
}
static final CreateAccountResultBatch EMPTY = new CreateAccountResultBatch(0);
/**
* Creates an empty batch with the desired maximum capacity.
* <p>
* Once created, an instance cannot be resized, however it may contain any number of elements
* between zero and its {@link #getCapacity capacity}.
*
* @param capacity the maximum capacity.
* @throws IllegalArgumentException if capacity is negative.
*/
public CreateAccountResultBatch(final int capacity) {
super(capacity, Struct.SIZE);
}
CreateAccountResultBatch(final ByteBuffer buffer) {
super(buffer, Struct.SIZE);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getIndex() {
final var value = getUInt32(at(Struct.Index));
return value;
}
/**
* @param index
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
void setIndex(final int index) {
putUInt32(at(Struct.Index), index);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public CreateAccountResult getResult() {
final var value = getUInt32(at(Struct.Result));
return CreateAccountResult.fromValue(value);
}
/**
* @param result
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
void setResult(final CreateAccountResult result) {
putUInt32(at(Struct.Result), result.value);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/TransferBatch.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
import java.nio.ByteBuffer;
import java.math.BigInteger;
public final class TransferBatch extends Batch {
public static final BigInteger AMOUNT_MAX =
UInt128.asBigInteger(Long.MIN_VALUE, Long.MIN_VALUE);
interface Struct {
int SIZE = 128;
int Id = 0;
int DebitAccountId = 16;
int CreditAccountId = 32;
int Amount = 48;
int PendingId = 64;
int UserData128 = 80;
int UserData64 = 96;
int UserData32 = 104;
int Timeout = 108;
int Ledger = 112;
int Code = 116;
int Flags = 118;
int Timestamp = 120;
}
static final TransferBatch EMPTY = new TransferBatch(0);
/**
* Creates an empty batch with the desired maximum capacity.
* <p>
* Once created, an instance cannot be resized, however it may contain any number of elements
* between zero and its {@link #getCapacity capacity}.
*
* @param capacity the maximum capacity.
* @throws IllegalArgumentException if capacity is negative.
*/
public TransferBatch(final int capacity) {
super(capacity, Struct.SIZE);
}
TransferBatch(final ByteBuffer buffer) {
super(buffer, Struct.SIZE);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#id">id</a>
*/
public byte[] getId() {
return getUInt128(at(Struct.Id));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#id">id</a>
*/
public long getId(final UInt128 part) {
return getUInt128(at(Struct.Id), part);
}
/**
* @param id an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code id} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#id">id</a>
*/
public void setId(final byte[] id) {
putUInt128(at(Struct.Id), id);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#id">id</a>
*/
public void setId(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.Id), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#id">id</a>
*/
public void setId(final long leastSignificant) {
putUInt128(at(Struct.Id), leastSignificant, 0);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#debit_account_id">debit_account_id</a>
*/
public byte[] getDebitAccountId() {
return getUInt128(at(Struct.DebitAccountId));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#debit_account_id">debit_account_id</a>
*/
public long getDebitAccountId(final UInt128 part) {
return getUInt128(at(Struct.DebitAccountId), part);
}
/**
* @param debitAccountId an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code debitAccountId} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#debit_account_id">debit_account_id</a>
*/
public void setDebitAccountId(final byte[] debitAccountId) {
putUInt128(at(Struct.DebitAccountId), debitAccountId);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#debit_account_id">debit_account_id</a>
*/
public void setDebitAccountId(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.DebitAccountId), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#debit_account_id">debit_account_id</a>
*/
public void setDebitAccountId(final long leastSignificant) {
putUInt128(at(Struct.DebitAccountId), leastSignificant, 0);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#credit_account_id">credit_account_id</a>
*/
public byte[] getCreditAccountId() {
return getUInt128(at(Struct.CreditAccountId));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#credit_account_id">credit_account_id</a>
*/
public long getCreditAccountId(final UInt128 part) {
return getUInt128(at(Struct.CreditAccountId), part);
}
/**
* @param creditAccountId an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code creditAccountId} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#credit_account_id">credit_account_id</a>
*/
public void setCreditAccountId(final byte[] creditAccountId) {
putUInt128(at(Struct.CreditAccountId), creditAccountId);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#credit_account_id">credit_account_id</a>
*/
public void setCreditAccountId(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.CreditAccountId), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#credit_account_id">credit_account_id</a>
*/
public void setCreditAccountId(final long leastSignificant) {
putUInt128(at(Struct.CreditAccountId), leastSignificant, 0);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#amount">amount</a>
*/
public BigInteger getAmount() {
final var index = at(Struct.Amount);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#amount">amount</a>
*/
public long getAmount(final UInt128 part) {
return getUInt128(at(Struct.Amount), part);
}
/**
* @param amount a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#amount">amount</a>
*/
public void setAmount(final BigInteger amount) {
putUInt128(at(Struct.Amount), UInt128.asBytes(amount));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#amount">amount</a>
*/
public void setAmount(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.Amount), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#amount">amount</a>
*/
public void setAmount(final long leastSignificant) {
putUInt128(at(Struct.Amount), leastSignificant, 0);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#pending_id">pending_id</a>
*/
public byte[] getPendingId() {
return getUInt128(at(Struct.PendingId));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#pending_id">pending_id</a>
*/
public long getPendingId(final UInt128 part) {
return getUInt128(at(Struct.PendingId), part);
}
/**
* @param pendingId an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code pendingId} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#pending_id">pending_id</a>
*/
public void setPendingId(final byte[] pendingId) {
putUInt128(at(Struct.PendingId), pendingId);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#pending_id">pending_id</a>
*/
public void setPendingId(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.PendingId), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#pending_id">pending_id</a>
*/
public void setPendingId(final long leastSignificant) {
putUInt128(at(Struct.PendingId), leastSignificant, 0);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_128">user_data_128</a>
*/
public byte[] getUserData128() {
return getUInt128(at(Struct.UserData128));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_128">user_data_128</a>
*/
public long getUserData128(final UInt128 part) {
return getUInt128(at(Struct.UserData128), part);
}
/**
* @param userData128 an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code userData128} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_128">user_data_128</a>
*/
public void setUserData128(final byte[] userData128) {
putUInt128(at(Struct.UserData128), userData128);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_128">user_data_128</a>
*/
public void setUserData128(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.UserData128), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_128">user_data_128</a>
*/
public void setUserData128(final long leastSignificant) {
putUInt128(at(Struct.UserData128), leastSignificant, 0);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_64">user_data_64</a>
*/
public long getUserData64() {
final var value = getUInt64(at(Struct.UserData64));
return value;
}
/**
* @param userData64
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_64">user_data_64</a>
*/
public void setUserData64(final long userData64) {
putUInt64(at(Struct.UserData64), userData64);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_32">user_data_32</a>
*/
public int getUserData32() {
final var value = getUInt32(at(Struct.UserData32));
return value;
}
/**
* @param userData32
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#user_data_32">user_data_32</a>
*/
public void setUserData32(final int userData32) {
putUInt32(at(Struct.UserData32), userData32);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#timeout">timeout</a>
*/
public int getTimeout() {
final var value = getUInt32(at(Struct.Timeout));
return value;
}
/**
* @param timeout
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#timeout">timeout</a>
*/
public void setTimeout(final int timeout) {
putUInt32(at(Struct.Timeout), timeout);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#ledger">ledger</a>
*/
public int getLedger() {
final var value = getUInt32(at(Struct.Ledger));
return value;
}
/**
* @param ledger
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#ledger">ledger</a>
*/
public void setLedger(final int ledger) {
putUInt32(at(Struct.Ledger), ledger);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#code">code</a>
*/
public int getCode() {
final var value = getUInt16(at(Struct.Code));
return value;
}
/**
* @param code
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#code">code</a>
*/
public void setCode(final int code) {
putUInt16(at(Struct.Code), code);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flags">flags</a>
*/
public int getFlags() {
final var value = getUInt16(at(Struct.Flags));
return value;
}
/**
* @param flags
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flags">flags</a>
*/
public void setFlags(final int flags) {
putUInt16(at(Struct.Flags), flags);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#timestamp">timestamp</a>
*/
public long getTimestamp() {
final var value = getUInt64(at(Struct.Timestamp));
return value;
}
/**
* @param timestamp
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#timestamp">timestamp</a>
*/
public void setTimestamp(final long timestamp) {
putUInt64(at(Struct.Timestamp), timestamp);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/CreateTransferResultBatch.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
import java.nio.ByteBuffer;
public final class CreateTransferResultBatch extends Batch {
interface Struct {
int SIZE = 8;
int Index = 0;
int Result = 4;
}
static final CreateTransferResultBatch EMPTY = new CreateTransferResultBatch(0);
/**
* Creates an empty batch with the desired maximum capacity.
* <p>
* Once created, an instance cannot be resized, however it may contain any number of elements
* between zero and its {@link #getCapacity capacity}.
*
* @param capacity the maximum capacity.
* @throws IllegalArgumentException if capacity is negative.
*/
public CreateTransferResultBatch(final int capacity) {
super(capacity, Struct.SIZE);
}
CreateTransferResultBatch(final ByteBuffer buffer) {
super(buffer, Struct.SIZE);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getIndex() {
final var value = getUInt32(at(Struct.Index));
return value;
}
/**
* @param index
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
void setIndex(final int index) {
putUInt32(at(Struct.Index), index);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public CreateTransferResult getResult() {
final var value = getUInt32(at(Struct.Result));
return CreateTransferResult.fromValue(value);
}
/**
* @param result
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
void setResult(final CreateTransferResult result) {
putUInt32(at(Struct.Result), result.value);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/PacketStatus.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
public enum PacketStatus {
Ok((byte) 0),
TooMuchData((byte) 1),
ClientShutdown((byte) 2),
InvalidOperation((byte) 3),
InvalidDataSize((byte) 4);
public final byte value;
static final PacketStatus[] enumByValue;
static {
final var values = values();
enumByValue = new PacketStatus[values.length];
for (final var item : values) {
enumByValue[item.value] = item;
}
}
PacketStatus(byte value) {
this.value = value;
}
public static PacketStatus fromValue(byte value) {
if (value < 0 || value >= enumByValue.length)
throw new IllegalArgumentException(
String.format("Invalid PacketStatus value=%d", value));
final var item = enumByValue[value];
AssertionError.assertTrue(item.value == value,
"Unexpected PacketStatus: found=%d expected=%d", item.value, value);
return item;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/QueryFilterFlags.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
interface QueryFilterFlags {
int NONE = (int) 0;
int REVERSED = (int) (1 << 0);
static boolean hasReversed(final int flags) {
return (flags & REVERSED) == REVERSED;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/AsyncRequest.java | package com.tigerbeetle;
import java.util.concurrent.CompletableFuture;
final class AsyncRequest<TResponse extends Batch> extends Request<TResponse> {
// @formatter:off
/*
* Overview:
*
* Implements a Request to be used when invoked asynchronously.
* Exposes a CompletableFuture<T> to be awaited by an executor or thread pool until signaled as completed by the TB's callback.
*
* See BlockingRequest.java for the sync implementation.
*
*/
// @formatter:on
private final CompletableFuture<TResponse> future;
AsyncRequest(final NativeClient nativeClient, final Operations operation, final Batch batch) {
super(nativeClient, operation, batch);
future = new CompletableFuture<TResponse>();
}
public static AsyncRequest<CreateAccountResultBatch> createAccounts(
final NativeClient nativeClient, final AccountBatch batch) {
return new AsyncRequest<CreateAccountResultBatch>(nativeClient,
Request.Operations.CREATE_ACCOUNTS, batch);
}
public static AsyncRequest<AccountBatch> lookupAccounts(final NativeClient nativeClient,
final IdBatch batch) {
return new AsyncRequest<AccountBatch>(nativeClient, Request.Operations.LOOKUP_ACCOUNTS,
batch);
}
public static AsyncRequest<CreateTransferResultBatch> createTransfers(
final NativeClient nativeClient, final TransferBatch batch) {
return new AsyncRequest<CreateTransferResultBatch>(nativeClient,
Request.Operations.CREATE_TRANSFERS, batch);
}
public static AsyncRequest<TransferBatch> lookupTransfers(final NativeClient nativeClient,
final IdBatch batch) {
return new AsyncRequest<TransferBatch>(nativeClient, Request.Operations.LOOKUP_TRANSFERS,
batch);
}
public static AsyncRequest<TransferBatch> getAccountTransfers(final NativeClient nativeClient,
final AccountFilter filter) {
return new AsyncRequest<TransferBatch>(nativeClient,
Request.Operations.GET_ACCOUNT_TRANSFERS, filter.batch);
}
public static AsyncRequest<AccountBalanceBatch> getAccountBalances(
final NativeClient nativeClient, final AccountFilter filter) {
return new AsyncRequest<AccountBalanceBatch>(nativeClient,
Request.Operations.GET_ACCOUNT_BALANCES, filter.batch);
}
public static AsyncRequest<AccountBatch> queryAccounts(final NativeClient nativeClient,
final QueryFilter filter) {
return new AsyncRequest<AccountBatch>(nativeClient, Request.Operations.QUERY_ACCOUNTS,
filter.batch);
}
public static AsyncRequest<TransferBatch> queryTransfers(final NativeClient nativeClient,
final QueryFilter filter) {
return new AsyncRequest<TransferBatch>(nativeClient, Request.Operations.QUERY_TRANSFERS,
filter.batch);
}
public static AsyncRequest<AccountBatch> echo(final NativeClient nativeClient,
final AccountBatch batch) {
return new AsyncRequest<AccountBatch>(nativeClient, Request.Operations.ECHO_ACCOUNTS,
batch);
}
public static AsyncRequest<TransferBatch> echo(final NativeClient nativeClient,
final TransferBatch batch) {
return new AsyncRequest<TransferBatch>(nativeClient, Request.Operations.ECHO_TRANSFERS,
batch);
}
public CompletableFuture<TResponse> getFuture() {
return future;
}
@Override
protected void setResult(final TResponse result) {
final var completed = future.complete(result);
AssertionError.assertTrue(completed, "CompletableFuture already completed");
}
@Override
protected void setException(final Throwable exception) {
final var completed = future.completeExceptionally(exception);
AssertionError.assertTrue(completed, "CompletableFuture already completed");
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/EchoClient.java | package com.tigerbeetle;
import java.util.concurrent.CompletableFuture;
public final class EchoClient implements AutoCloseable {
private final NativeClient nativeClient;
public EchoClient(final byte[] clusterID, final String replicaAddresses) {
this.nativeClient = NativeClient.initEcho(clusterID, replicaAddresses);
}
public AccountBatch echo(final AccountBatch batch) throws Exception {
final var request = BlockingRequest.echo(this.nativeClient, batch);
request.beginRequest();
return request.waitForResult();
}
public TransferBatch echo(final TransferBatch batch) throws Exception {
final var request = BlockingRequest.echo(this.nativeClient, batch);
request.beginRequest();
return request.waitForResult();
}
public CompletableFuture<AccountBatch> echoAsync(final AccountBatch batch) throws Exception {
final var request = AsyncRequest.echo(this.nativeClient, batch);
request.beginRequest();
return request.getFuture();
}
public CompletableFuture<TransferBatch> echoAsync(final TransferBatch batch) throws Exception {
final var request = AsyncRequest.echo(this.nativeClient, batch);
request.beginRequest();
return request.getFuture();
}
public void close() throws Exception {
nativeClient.close();
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/AccountFilterBatch.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
import java.nio.ByteBuffer;
final class AccountFilterBatch extends Batch {
interface Struct {
int SIZE = 64;
int AccountId = 0;
int TimestampMin = 16;
int TimestampMax = 24;
int Limit = 32;
int Flags = 36;
int Reserved = 40;
}
static final AccountFilterBatch EMPTY = new AccountFilterBatch(0);
/**
* Creates an empty batch with the desired maximum capacity.
* <p>
* Once created, an instance cannot be resized, however it may contain any number of elements
* between zero and its {@link #getCapacity capacity}.
*
* @param capacity the maximum capacity.
* @throws IllegalArgumentException if capacity is negative.
*/
public AccountFilterBatch(final int capacity) {
super(capacity, Struct.SIZE);
}
AccountFilterBatch(final ByteBuffer buffer) {
super(buffer, Struct.SIZE);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public byte[] getAccountId() {
return getUInt128(at(Struct.AccountId));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public long getAccountId(final UInt128 part) {
return getUInt128(at(Struct.AccountId), part);
}
/**
* @param accountId an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code accountId} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setAccountId(final byte[] accountId) {
putUInt128(at(Struct.AccountId), accountId);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setAccountId(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.AccountId), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setAccountId(final long leastSignificant) {
putUInt128(at(Struct.AccountId), leastSignificant, 0);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public long getTimestampMin() {
final var value = getUInt64(at(Struct.TimestampMin));
return value;
}
/**
* @param timestampMin
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setTimestampMin(final long timestampMin) {
putUInt64(at(Struct.TimestampMin), timestampMin);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public long getTimestampMax() {
final var value = getUInt64(at(Struct.TimestampMax));
return value;
}
/**
* @param timestampMax
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setTimestampMax(final long timestampMax) {
putUInt64(at(Struct.TimestampMax), timestampMax);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getLimit() {
final var value = getUInt32(at(Struct.Limit));
return value;
}
/**
* @param limit
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setLimit(final int limit) {
putUInt32(at(Struct.Limit), limit);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getFlags() {
final var value = getUInt32(at(Struct.Flags));
return value;
}
/**
* @param flags
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setFlags(final int flags) {
putUInt32(at(Struct.Flags), flags);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
byte[] getReserved() {
return getArray(at(Struct.Reserved), 24);
}
/**
* @param reserved
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
void setReserved(byte[] reserved) {
if (reserved == null)
reserved = new byte[24];
if (reserved.length != 24)
throw new IllegalArgumentException("Reserved must be 24 bytes long");
putArray(at(Struct.Reserved), reserved);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/InitializationException.java | package com.tigerbeetle;
public final class InitializationException extends RuntimeException {
private final int status;
public InitializationException(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
@Override
public String getMessage() {
return toString();
}
@Override
public String toString() {
if (status == InitializationStatus.Unexpected.value)
return "Unexpected internal error";
else if (status == InitializationStatus.OutOfMemory.value)
return "Internal client ran out of memory";
else if (status == InitializationStatus.AddressInvalid.value)
return "Replica addresses format is invalid";
else if (status == InitializationStatus.AddressLimitExceeded.value)
return "Replica addresses limit exceeded";
else if (status == InitializationStatus.SystemResources.value)
return "Internal client ran out of system resources";
else if (status == InitializationStatus.NetworkSubsystem.value)
return "Internal client had unexpected networking issues";
else
return "Error status " + status;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/QueryFilterBatch.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
import java.nio.ByteBuffer;
final class QueryFilterBatch extends Batch {
interface Struct {
int SIZE = 64;
int UserData128 = 0;
int UserData64 = 16;
int UserData32 = 24;
int Ledger = 28;
int Code = 32;
int Reserved = 34;
int TimestampMin = 40;
int TimestampMax = 48;
int Limit = 56;
int Flags = 60;
}
static final QueryFilterBatch EMPTY = new QueryFilterBatch(0);
/**
* Creates an empty batch with the desired maximum capacity.
* <p>
* Once created, an instance cannot be resized, however it may contain any number of elements
* between zero and its {@link #getCapacity capacity}.
*
* @param capacity the maximum capacity.
* @throws IllegalArgumentException if capacity is negative.
*/
public QueryFilterBatch(final int capacity) {
super(capacity, Struct.SIZE);
}
QueryFilterBatch(final ByteBuffer buffer) {
super(buffer, Struct.SIZE);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public byte[] getUserData128() {
return getUInt128(at(Struct.UserData128));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public long getUserData128(final UInt128 part) {
return getUInt128(at(Struct.UserData128), part);
}
/**
* @param userData128 an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code userData128} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setUserData128(final byte[] userData128) {
putUInt128(at(Struct.UserData128), userData128);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setUserData128(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.UserData128), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setUserData128(final long leastSignificant) {
putUInt128(at(Struct.UserData128), leastSignificant, 0);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public long getUserData64() {
final var value = getUInt64(at(Struct.UserData64));
return value;
}
/**
* @param userData64
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setUserData64(final long userData64) {
putUInt64(at(Struct.UserData64), userData64);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getUserData32() {
final var value = getUInt32(at(Struct.UserData32));
return value;
}
/**
* @param userData32
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setUserData32(final int userData32) {
putUInt32(at(Struct.UserData32), userData32);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getLedger() {
final var value = getUInt32(at(Struct.Ledger));
return value;
}
/**
* @param ledger
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setLedger(final int ledger) {
putUInt32(at(Struct.Ledger), ledger);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getCode() {
final var value = getUInt16(at(Struct.Code));
return value;
}
/**
* @param code
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setCode(final int code) {
putUInt16(at(Struct.Code), code);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
byte[] getReserved() {
return getArray(at(Struct.Reserved), 6);
}
/**
* @param reserved
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
void setReserved(byte[] reserved) {
if (reserved == null)
reserved = new byte[6];
if (reserved.length != 6)
throw new IllegalArgumentException("Reserved must be 6 bytes long");
putArray(at(Struct.Reserved), reserved);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public long getTimestampMin() {
final var value = getUInt64(at(Struct.TimestampMin));
return value;
}
/**
* @param timestampMin
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setTimestampMin(final long timestampMin) {
putUInt64(at(Struct.TimestampMin), timestampMin);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public long getTimestampMax() {
final var value = getUInt64(at(Struct.TimestampMax));
return value;
}
/**
* @param timestampMax
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setTimestampMax(final long timestampMax) {
putUInt64(at(Struct.TimestampMax), timestampMax);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getLimit() {
final var value = getUInt32(at(Struct.Limit));
return value;
}
/**
* @param limit
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setLimit(final int limit) {
putUInt32(at(Struct.Limit), limit);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public int getFlags() {
final var value = getUInt32(at(Struct.Flags));
return value;
}
/**
* @param flags
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setFlags(final int flags) {
putUInt32(at(Struct.Flags), flags);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/CreateAccountResult.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
public enum CreateAccountResult {
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#ok">ok</a>
*/
Ok((int) 0),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#linked_event_failed">linked_event_failed</a>
*/
LinkedEventFailed((int) 1),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#linked_event_chain_open">linked_event_chain_open</a>
*/
LinkedEventChainOpen((int) 2),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_expected">imported_event_expected</a>
*/
ImportedEventExpected((int) 22),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_not_expected">imported_event_not_expected</a>
*/
ImportedEventNotExpected((int) 23),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#timestamp_must_be_zero">timestamp_must_be_zero</a>
*/
TimestampMustBeZero((int) 3),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_timestamp_out_of_range">imported_event_timestamp_out_of_range</a>
*/
ImportedEventTimestampOutOfRange((int) 24),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_timestamp_must_not_advance">imported_event_timestamp_must_not_advance</a>
*/
ImportedEventTimestampMustNotAdvance((int) 25),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#reserved_field">reserved_field</a>
*/
ReservedField((int) 4),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#reserved_flag">reserved_flag</a>
*/
ReservedFlag((int) 5),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#id_must_not_be_zero">id_must_not_be_zero</a>
*/
IdMustNotBeZero((int) 6),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#id_must_not_be_int_max">id_must_not_be_int_max</a>
*/
IdMustNotBeIntMax((int) 7),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#flags_are_mutually_exclusive">flags_are_mutually_exclusive</a>
*/
FlagsAreMutuallyExclusive((int) 8),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#debits_pending_must_be_zero">debits_pending_must_be_zero</a>
*/
DebitsPendingMustBeZero((int) 9),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#debits_posted_must_be_zero">debits_posted_must_be_zero</a>
*/
DebitsPostedMustBeZero((int) 10),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#credits_pending_must_be_zero">credits_pending_must_be_zero</a>
*/
CreditsPendingMustBeZero((int) 11),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#credits_posted_must_be_zero">credits_posted_must_be_zero</a>
*/
CreditsPostedMustBeZero((int) 12),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#ledger_must_not_be_zero">ledger_must_not_be_zero</a>
*/
LedgerMustNotBeZero((int) 13),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#code_must_not_be_zero">code_must_not_be_zero</a>
*/
CodeMustNotBeZero((int) 14),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_flags">exists_with_different_flags</a>
*/
ExistsWithDifferentFlags((int) 15),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_user_data_128">exists_with_different_user_data_128</a>
*/
ExistsWithDifferentUserData128((int) 16),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_user_data_64">exists_with_different_user_data_64</a>
*/
ExistsWithDifferentUserData64((int) 17),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_user_data_32">exists_with_different_user_data_32</a>
*/
ExistsWithDifferentUserData32((int) 18),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_ledger">exists_with_different_ledger</a>
*/
ExistsWithDifferentLedger((int) 19),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#exists_with_different_code">exists_with_different_code</a>
*/
ExistsWithDifferentCode((int) 20),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#exists">exists</a>
*/
Exists((int) 21),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_accounts#imported_event_timestamp_must_not_regress">imported_event_timestamp_must_not_regress</a>
*/
ImportedEventTimestampMustNotRegress((int) 26);
public final int value;
static final CreateAccountResult[] enumByValue;
static {
final var values = values();
enumByValue = new CreateAccountResult[values.length];
for (final var item : values) {
enumByValue[item.value] = item;
}
}
CreateAccountResult(int value) {
this.value = value;
}
public static CreateAccountResult fromValue(int value) {
if (value < 0 || value >= enumByValue.length)
throw new IllegalArgumentException(
String.format("Invalid CreateAccountResult value=%d", value));
final var item = enumByValue[value];
AssertionError.assertTrue(item.value == value,
"Unexpected CreateAccountResult: found=%d expected=%d", item.value, value);
return item;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/CreateTransferResult.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
public enum CreateTransferResult {
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#ok">ok</a>
*/
Ok((int) 0),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#linked_event_failed">linked_event_failed</a>
*/
LinkedEventFailed((int) 1),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#linked_event_chain_open">linked_event_chain_open</a>
*/
LinkedEventChainOpen((int) 2),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#timestamp_must_be_zero">timestamp_must_be_zero</a>
*/
TimestampMustBeZero((int) 3),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#reserved_flag">reserved_flag</a>
*/
ReservedFlag((int) 4),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#id_must_not_be_zero">id_must_not_be_zero</a>
*/
IdMustNotBeZero((int) 5),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#id_must_not_be_int_max">id_must_not_be_int_max</a>
*/
IdMustNotBeIntMax((int) 6),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#flags_are_mutually_exclusive">flags_are_mutually_exclusive</a>
*/
FlagsAreMutuallyExclusive((int) 7),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#debit_account_id_must_not_be_zero">debit_account_id_must_not_be_zero</a>
*/
DebitAccountIdMustNotBeZero((int) 8),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#debit_account_id_must_not_be_int_max">debit_account_id_must_not_be_int_max</a>
*/
DebitAccountIdMustNotBeIntMax((int) 9),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#credit_account_id_must_not_be_zero">credit_account_id_must_not_be_zero</a>
*/
CreditAccountIdMustNotBeZero((int) 10),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#credit_account_id_must_not_be_int_max">credit_account_id_must_not_be_int_max</a>
*/
CreditAccountIdMustNotBeIntMax((int) 11),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#accounts_must_be_different">accounts_must_be_different</a>
*/
AccountsMustBeDifferent((int) 12),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_id_must_be_zero">pending_id_must_be_zero</a>
*/
PendingIdMustBeZero((int) 13),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_id_must_not_be_zero">pending_id_must_not_be_zero</a>
*/
PendingIdMustNotBeZero((int) 14),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_id_must_not_be_int_max">pending_id_must_not_be_int_max</a>
*/
PendingIdMustNotBeIntMax((int) 15),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_id_must_be_different">pending_id_must_be_different</a>
*/
PendingIdMustBeDifferent((int) 16),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#timeout_reserved_for_pending_transfer">timeout_reserved_for_pending_transfer</a>
*/
TimeoutReservedForPendingTransfer((int) 17),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#amount_must_not_be_zero">amount_must_not_be_zero</a>
*/
AmountMustNotBeZero((int) 18),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#ledger_must_not_be_zero">ledger_must_not_be_zero</a>
*/
LedgerMustNotBeZero((int) 19),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#code_must_not_be_zero">code_must_not_be_zero</a>
*/
CodeMustNotBeZero((int) 20),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#debit_account_not_found">debit_account_not_found</a>
*/
DebitAccountNotFound((int) 21),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#credit_account_not_found">credit_account_not_found</a>
*/
CreditAccountNotFound((int) 22),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#accounts_must_have_the_same_ledger">accounts_must_have_the_same_ledger</a>
*/
AccountsMustHaveTheSameLedger((int) 23),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#transfer_must_have_the_same_ledger_as_accounts">transfer_must_have_the_same_ledger_as_accounts</a>
*/
TransferMustHaveTheSameLedgerAsAccounts((int) 24),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_not_found">pending_transfer_not_found</a>
*/
PendingTransferNotFound((int) 25),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_not_pending">pending_transfer_not_pending</a>
*/
PendingTransferNotPending((int) 26),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_debit_account_id">pending_transfer_has_different_debit_account_id</a>
*/
PendingTransferHasDifferentDebitAccountId((int) 27),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_credit_account_id">pending_transfer_has_different_credit_account_id</a>
*/
PendingTransferHasDifferentCreditAccountId((int) 28),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_ledger">pending_transfer_has_different_ledger</a>
*/
PendingTransferHasDifferentLedger((int) 29),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_code">pending_transfer_has_different_code</a>
*/
PendingTransferHasDifferentCode((int) 30),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exceeds_pending_transfer_amount">exceeds_pending_transfer_amount</a>
*/
ExceedsPendingTransferAmount((int) 31),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_has_different_amount">pending_transfer_has_different_amount</a>
*/
PendingTransferHasDifferentAmount((int) 32),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_already_posted">pending_transfer_already_posted</a>
*/
PendingTransferAlreadyPosted((int) 33),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_already_voided">pending_transfer_already_voided</a>
*/
PendingTransferAlreadyVoided((int) 34),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#pending_transfer_expired">pending_transfer_expired</a>
*/
PendingTransferExpired((int) 35),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_flags">exists_with_different_flags</a>
*/
ExistsWithDifferentFlags((int) 36),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_debit_account_id">exists_with_different_debit_account_id</a>
*/
ExistsWithDifferentDebitAccountId((int) 37),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_credit_account_id">exists_with_different_credit_account_id</a>
*/
ExistsWithDifferentCreditAccountId((int) 38),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_amount">exists_with_different_amount</a>
*/
ExistsWithDifferentAmount((int) 39),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_pending_id">exists_with_different_pending_id</a>
*/
ExistsWithDifferentPendingId((int) 40),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_user_data_128">exists_with_different_user_data_128</a>
*/
ExistsWithDifferentUserData128((int) 41),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_user_data_64">exists_with_different_user_data_64</a>
*/
ExistsWithDifferentUserData64((int) 42),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_user_data_32">exists_with_different_user_data_32</a>
*/
ExistsWithDifferentUserData32((int) 43),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_timeout">exists_with_different_timeout</a>
*/
ExistsWithDifferentTimeout((int) 44),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists_with_different_code">exists_with_different_code</a>
*/
ExistsWithDifferentCode((int) 45),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exists">exists</a>
*/
Exists((int) 46),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_debits_pending">overflows_debits_pending</a>
*/
OverflowsDebitsPending((int) 47),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_credits_pending">overflows_credits_pending</a>
*/
OverflowsCreditsPending((int) 48),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_debits_posted">overflows_debits_posted</a>
*/
OverflowsDebitsPosted((int) 49),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_credits_posted">overflows_credits_posted</a>
*/
OverflowsCreditsPosted((int) 50),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_debits">overflows_debits</a>
*/
OverflowsDebits((int) 51),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_credits">overflows_credits</a>
*/
OverflowsCredits((int) 52),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#overflows_timeout">overflows_timeout</a>
*/
OverflowsTimeout((int) 53),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exceeds_credits">exceeds_credits</a>
*/
ExceedsCredits((int) 54),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#exceeds_debits">exceeds_debits</a>
*/
ExceedsDebits((int) 55),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_expected">imported_event_expected</a>
*/
ImportedEventExpected((int) 56),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_not_expected">imported_event_not_expected</a>
*/
ImportedEventNotExpected((int) 57),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_out_of_range">imported_event_timestamp_out_of_range</a>
*/
ImportedEventTimestampOutOfRange((int) 58),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_must_not_advance">imported_event_timestamp_must_not_advance</a>
*/
ImportedEventTimestampMustNotAdvance((int) 59),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_must_not_regress">imported_event_timestamp_must_not_regress</a>
*/
ImportedEventTimestampMustNotRegress((int) 60),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_must_postdate_debit_account">imported_event_timestamp_must_postdate_debit_account</a>
*/
ImportedEventTimestampMustPostdateDebitAccount((int) 61),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timestamp_must_postdate_credit_account">imported_event_timestamp_must_postdate_credit_account</a>
*/
ImportedEventTimestampMustPostdateCreditAccount((int) 62),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#imported_event_timeout_must_be_zero">imported_event_timeout_must_be_zero</a>
*/
ImportedEventTimeoutMustBeZero((int) 63),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#closing_transfer_must_be_pending">closing_transfer_must_be_pending</a>
*/
ClosingTransferMustBePending((int) 64),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#debit_account_already_closed">debit_account_already_closed</a>
*/
DebitAccountAlreadyClosed((int) 65),
/**
* @see <a href="https://docs.tigerbeetle.com/reference/requests/create_transfers#credit_account_already_closed">credit_account_already_closed</a>
*/
CreditAccountAlreadyClosed((int) 66);
public final int value;
static final CreateTransferResult[] enumByValue;
static {
final var values = values();
enumByValue = new CreateTransferResult[values.length];
for (final var item : values) {
enumByValue[item.value] = item;
}
}
CreateTransferResult(int value) {
this.value = value;
}
public static CreateTransferResult fromValue(int value) {
if (value < 0 || value >= enumByValue.length)
throw new IllegalArgumentException(
String.format("Invalid CreateTransferResult value=%d", value));
final var item = enumByValue[value];
AssertionError.assertTrue(item.value == value,
"Unexpected CreateTransferResult: found=%d expected=%d", item.value, value);
return item;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/package-info.java | /**
* TigerBeetle client for Java.
*
* @see <a href="https://docs.tigerbeetle.com">TigerBeetle Docs</a>
* @see <a href="https://github.com/tigerbeetle/tigerbeetle-java">Source code</a>
*/
package com.tigerbeetle;
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/NativeClient.java | package com.tigerbeetle;
import static com.tigerbeetle.AssertionError.assertTrue;
import java.lang.ref.Cleaner;
final class NativeClient implements AutoCloseable {
private final static Cleaner cleaner;
/*
* Holds the `handle` in an object instance detached from `NativeClient` to provide state for
* the cleaner to dispose native memory when the `Client` instance is GCed. Also implements
* `Runnable` to be usable as the cleaner action.
* https://docs.oracle.com/javase%2F9%2Fdocs%2Fapi%2F%2F/java/lang/ref/Cleaner.html
*
* Methods are synchronized to ensure tb_client functions aren't called on an invalid handle.
* Safe to synchronize on NativeHandle object as it's private to NativeClient and can't be
* arbitrarily/externally locked by the library user.
*/
private static final class NativeHandle implements Runnable {
private long handle;
public NativeHandle(long handle) {
assert handle != 0;
this.handle = handle;
}
public synchronized void submit(final Request<?> request) {
if (handle == 0) {
throw new IllegalStateException("Client is closed");
}
NativeClient.submit(handle, request);
}
public synchronized void close() {
if (handle == 0) {
return;
}
clientDeinit(handle);
handle = 0;
}
@Override
public void run() {
close();
}
}
static {
JNILoader.loadFromJar();
cleaner = Cleaner.create();
}
private final NativeHandle handle;
private final Cleaner.Cleanable cleanable;
public static NativeClient init(final byte[] clusterID, final String addresses) {
assertArgs(clusterID, addresses);
final long contextHandle = clientInit(clusterID, addresses);
return new NativeClient(contextHandle);
}
public static NativeClient initEcho(final byte[] clusterID, final String addresses) {
assertArgs(clusterID, addresses);
final long contextHandle = clientInitEcho(clusterID, addresses);
return new NativeClient(contextHandle);
}
private static void assertArgs(final byte[] clusterID, final String addresses) {
assertTrue(clusterID.length == 16, "ClusterID must be a UInt128");
assertTrue(addresses != null, "Replica addresses cannot be null");
}
private NativeClient(final long contextHandle) {
try {
this.handle = new NativeHandle(contextHandle);
this.cleanable = cleaner.register(this, handle);
} catch (Throwable forward) {
clientDeinit(contextHandle);
throw forward;
}
}
public void submit(final Request<?> request) {
this.handle.submit(request);
}
@Override
public void close() {
// When the user calls `close()` or the client is used in a `try-resource` block,
// we call `NativeHandle.close` to force it to run synchronously in the same thread.
// Otherwise, if the user never disposes the client and `close` is never called,
// the cleaner calls `NativeHandle.close` in another thread when the client is GCed.
this.handle.close();
// Unregistering the cleanable.
cleanable.clean();
}
private static native void submit(long contextHandle, Request<?> request);
private static native long clientInit(byte[] clusterID, String addresses);
private static native long clientInitEcho(byte[] clusterID, String addresses);
private static native void clientDeinit(long contextHandle);
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/TransferFlags.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
public interface TransferFlags {
int NONE = (int) 0;
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagslinked">linked</a>
*/
int LINKED = (int) (1 << 0);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagspending">pending</a>
*/
int PENDING = (int) (1 << 1);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagspost_pending_transfer">post_pending_transfer</a>
*/
int POST_PENDING_TRANSFER = (int) (1 << 2);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagsvoid_pending_transfer">void_pending_transfer</a>
*/
int VOID_PENDING_TRANSFER = (int) (1 << 3);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagsbalancing_debit">balancing_debit</a>
*/
int BALANCING_DEBIT = (int) (1 << 4);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagsbalancing_credit">balancing_credit</a>
*/
int BALANCING_CREDIT = (int) (1 << 5);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagsclosing_debit">closing_debit</a>
*/
int CLOSING_DEBIT = (int) (1 << 6);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagsclosing_credit">closing_credit</a>
*/
int CLOSING_CREDIT = (int) (1 << 7);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/transfer#flagsimported">imported</a>
*/
int IMPORTED = (int) (1 << 8);
static boolean hasLinked(final int flags) {
return (flags & LINKED) == LINKED;
}
static boolean hasPending(final int flags) {
return (flags & PENDING) == PENDING;
}
static boolean hasPostPendingTransfer(final int flags) {
return (flags & POST_PENDING_TRANSFER) == POST_PENDING_TRANSFER;
}
static boolean hasVoidPendingTransfer(final int flags) {
return (flags & VOID_PENDING_TRANSFER) == VOID_PENDING_TRANSFER;
}
static boolean hasBalancingDebit(final int flags) {
return (flags & BALANCING_DEBIT) == BALANCING_DEBIT;
}
static boolean hasBalancingCredit(final int flags) {
return (flags & BALANCING_CREDIT) == BALANCING_CREDIT;
}
static boolean hasClosingDebit(final int flags) {
return (flags & CLOSING_DEBIT) == CLOSING_DEBIT;
}
static boolean hasClosingCredit(final int flags) {
return (flags & CLOSING_CREDIT) == CLOSING_CREDIT;
}
static boolean hasImported(final int flags) {
return (flags & IMPORTED) == IMPORTED;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/InitializationStatus.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
public enum InitializationStatus {
Success((int) 0),
Unexpected((int) 1),
OutOfMemory((int) 2),
AddressInvalid((int) 3),
AddressLimitExceeded((int) 4),
SystemResources((int) 5),
NetworkSubsystem((int) 6);
public final int value;
static final InitializationStatus[] enumByValue;
static {
final var values = values();
enumByValue = new InitializationStatus[values.length];
for (final var item : values) {
enumByValue[item.value] = item;
}
}
InitializationStatus(int value) {
this.value = value;
}
public static InitializationStatus fromValue(int value) {
if (value < 0 || value >= enumByValue.length)
throw new IllegalArgumentException(
String.format("Invalid InitializationStatus value=%d", value));
final var item = enumByValue[value];
AssertionError.assertTrue(item.value == value,
"Unexpected InitializationStatus: found=%d expected=%d", item.value, value);
return item;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/AccountFilter.java | package com.tigerbeetle;
public final class AccountFilter {
// @formatter:off
/*
* Summary:
*
* Wraps the `AccountFilterBatch` auto-generated binding in a single-item batch.
* Since `getAccountTransfers()` expects only one item, we avoid exposing the `Batch` class externally.
*
* This is an ad-hoc feature meant to be replaced by a proper querying API shortly,
* therefore, it is not worth the effort to modify the binding generator to emit single-item batchs.
*
*/
// @formatter:on
AccountFilterBatch batch;
public AccountFilter() {
this.batch = new AccountFilterBatch(1);
this.batch.add();
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#account_id">account_id</a>
*/
public byte[] getAccountId() {
return batch.getAccountId();
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value is to be
* retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#account_id">account_id</a>
*/
public long getAccountId(final UInt128 part) {
return batch.getAccountId(part);
}
/**
* @param accountId an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code id} is not 16 bytes long.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#account_id">account_id</a>
*/
public void setAccountId(final byte[] accountId) {
batch.setAccountId(accountId);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#account_id">account_id</a>
*/
public void setAccountId(final long leastSignificant, final long mostSignificant) {
batch.setAccountId(leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#account_id">account_id</a>
*/
public void setAccountId(final long leastSignificant) {
batch.setAccountId(leastSignificant);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#timestamp_min">timestamp_min</a>
*/
public long getTimestampMin() {
return batch.getTimestampMin();
}
/**
* @param timestamp
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#timestamp_min">timestamp_min</a>
*/
public void setTimestampMin(final long timestamp) {
batch.setTimestampMin(timestamp);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#timestamp_max">timestamp_max</a>
*/
public long getTimestampMax() {
return batch.getTimestampMax();
}
/**
* @param timestamp
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#timestamp_max">timestamp_max</a>
*/
public void setTimestampMax(final long timestamp) {
batch.setTimestampMax(timestamp);
}
/**
* @see <a href= "https://docs.tigerbeetle.com/reference/account-filter#limit">limit</a>
*/
public int getLimit() {
return batch.getLimit();
}
/**
* @param limit
* @see <a href= "https://docs.tigerbeetle.com/reference/account-filter#limit">limit</a>
*/
public void setLimit(final int limit) {
batch.setLimit(limit);
}
/**
* @see <a href= "https://docs.tigerbeetle.com/reference/account-filter#flagsdebits">debits</a>
*/
public boolean getDebits() {
return getFlags(AccountFilterFlags.DEBITS);
}
/**
* @param value
* @see <a href= "https://docs.tigerbeetle.com/reference/account-filter#flagsdebits">debits</a>
*/
public void setDebits(boolean value) {
setFlags(AccountFilterFlags.DEBITS, value);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#flagscredits">credits</a>
*/
public boolean getCredits() {
return getFlags(AccountFilterFlags.CREDITS);
}
/**
* @param value
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#flagscredits">credits</a>
*/
public void setCredits(boolean value) {
setFlags(AccountFilterFlags.CREDITS, value);
}
/**
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#flagsreversed">reversed</a>
*/
public boolean getReversed() {
return getFlags(AccountFilterFlags.REVERSED);
}
/**
* @param value
* @see <a href=
* "https://docs.tigerbeetle.com/reference/account-filter#flagsreversed">reversed</a>
*/
public void setReversed(boolean value) {
setFlags(AccountFilterFlags.REVERSED, value);
}
boolean getFlags(final int flag) {
final var value = batch.getFlags();
return (value & flag) != 0;
}
void setFlags(final int flag, final boolean enabled) {
var value = batch.getFlags();
if (enabled)
value |= flag;
else
value &= ~flag;
batch.setFlags(value);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/Batch.java | package com.tigerbeetle;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Objects;
import static com.tigerbeetle.AssertionError.assertTrue;
/**
* A Batch is contiguous memory block representing a collection of elements of the same type with a
* cursor pointing to its current position.
* <p>
* Initially the cursor is positioned before the first element and must be positioned by calling
* {@link #next}, {@link #add}, or {@link #setPosition} prior to reading or writing an element.
*/
public abstract class Batch {
// @formatter:off
/*
* Overview
*
* Batch uses a ByteArray to hold direct memory that both the Java side and the JNI side can access.
*
* We expose the API using the concept of "Cursor" familiar to JDBC's ResultSet, where a single Batch
* instance points to multiple elements depending on the cursor position, eliminating individual instances
* for each element.
*
*/
// @formatter:off
private enum CursorStatus {
Begin,
Valid,
End;
public static final int INVALID_POSITION = -1;
}
final static ByteOrder BYTE_ORDER = ByteOrder.nativeOrder();
static {
// We require little-endian architectures everywhere for efficient network
// deserialization:
assertTrue(BYTE_ORDER == ByteOrder.LITTLE_ENDIAN, "Native byte order LITTLE ENDIAN expected");
}
private int position;
private CursorStatus cursorStatus;
private int length;
private final int capacity;
private final ByteBuffer buffer;
private final int ELEMENT_SIZE;
Batch(final int capacity, final int ELEMENT_SIZE) {
assertTrue(ELEMENT_SIZE > 0, "Element size cannot be zero or negative");
if (capacity < 0) throw new IllegalArgumentException("Buffer capacity cannot be negative");
this.ELEMENT_SIZE = ELEMENT_SIZE;
this.length = 0;
this.capacity = capacity;
this.position = CursorStatus.INVALID_POSITION;
this.cursorStatus = CursorStatus.Begin;
final var bufferCapacity = capacity * ELEMENT_SIZE;
this.buffer = ByteBuffer.allocateDirect(bufferCapacity).order(BYTE_ORDER);
}
Batch(final ByteBuffer buffer, final int ELEMENT_SIZE) {
assertTrue(ELEMENT_SIZE > 0, "Element size cannot be zero or negative");
Objects.requireNonNull(buffer, "Buffer cannot be null");
this.ELEMENT_SIZE = ELEMENT_SIZE;
final var bufferLen = buffer.capacity();
// Make sure the completion handler is giving us valid data
assertTrue(bufferLen % ELEMENT_SIZE == 0, "Invalid data received from completion handler: bufferLen=%d, elementSize=%d.",
bufferLen, ELEMENT_SIZE);
this.capacity = bufferLen / ELEMENT_SIZE;
this.length = capacity;
this.position = CursorStatus.INVALID_POSITION;
this.cursorStatus = CursorStatus.Begin;
this.buffer = buffer.order(BYTE_ORDER);
}
/**
* Tells whether or not this batch is read-only.
*
* @return true if this batch is read-only
*/
public final boolean isReadOnly() {
return buffer.isReadOnly();
}
/**
* Adds a new element at the end of this batch.
* <p>
* If successful, moves the current {@link #setPosition position} to the newly created
* element.
*
* @throws IllegalStateException if this batch is read-only.
* @throws IndexOutOfBoundsException if exceeds the batch's capacity.
*/
public final void add() {
if (isReadOnly())
throw new IllegalStateException("Cannot add an element in a read-only batch");
final var currentLen = this.length;
if (currentLen >= capacity)
throw new IndexOutOfBoundsException(String.format(
"Cannot add an element because the batch's capacity of %d was exceeded",
capacity));
this.length = currentLen + 1;
setPosition(currentLen);
}
/**
* Tries to move the current {@link #setPosition position} to the next element in this batch.
*
* @return true if moved or false if the end of the batch was reached.
*
* @throws IndexOutOfBoundsException if the batch is already at the end.
*/
public final boolean next() {
if (cursorStatus == CursorStatus.End)
throw new IndexOutOfBoundsException("This batch reached the end");
final var nextPosition = position + 1;
if (nextPosition >= this.length) {
position = CursorStatus.INVALID_POSITION;
cursorStatus = this.length > 0 ? CursorStatus.End : CursorStatus.Begin;
return false;
} else {
setPosition(nextPosition);
return true;
}
}
/**
* Tells if the current position points to an valid element.
*
* @return false if the cursor is positioned before the first element or at the end.
*/
public final boolean isValidPosition() {
return cursorStatus == CursorStatus.Valid;
}
/**
* Moves the cursor to the front of this Batch, before the first element.
* <p>
* This causes the batch to be iterable again by calling {@link #next()}.
*/
public final void beforeFirst() {
position = CursorStatus.INVALID_POSITION;
cursorStatus = CursorStatus.Begin;
}
/**
* Returns the current element's position.
*
* @return a zero-based index or {@code -1} if at the end of the batch.
*/
public final int getPosition() {
return this.position;
}
/**
* Moves to the element int the specified position.
*
* @param newPosition a zero-based index.
* @throws IndexOutOfBoundsException if {@code newPosition} is negative or greater than the
* batch's {@link #getLength length}.
*/
public final void setPosition(final int newPosition) {
if (newPosition < 0 || newPosition >= this.length)
throw new IndexOutOfBoundsException();
this.position = newPosition;
this.cursorStatus = CursorStatus.Valid;
}
/**
* Gets the number of elements in this batch
*/
public final int getLength() {
return length;
}
/**
* Gets the maximum number of elements this batch can contain.
*/
public final int getCapacity() {
return capacity;
}
final ByteBuffer getBuffer() {
return buffer.position(0);
}
final int getBufferLen() {
return this.length * ELEMENT_SIZE;
}
protected final int at(final int fieldOffSet) {
if (this.cursorStatus != CursorStatus.Valid)
throw new IllegalStateException();
final var elementPosition = this.position * ELEMENT_SIZE;
return elementPosition + fieldOffSet;
}
protected final byte[] getUInt128(final int index) {
byte[] bytes = new byte[16];
buffer.position(index).get(bytes);
return bytes;
}
protected final long getUInt128(final int index, final UInt128 part) {
if (part == UInt128.LeastSignificant) {
return buffer.getLong(index);
} else {
return buffer.getLong(index + Long.BYTES);
}
}
protected final void putUInt128(final int index, final byte[] value) {
if (value == null) {
// By default we assume null as zero
// The caller may throw a NullPointerException instead
putUInt128(index, 0L, 0L);
} else {
if (value.length != 16)
throw new IllegalArgumentException("UInt128 must be 16 bytes long");
buffer.position(index).put(value);
}
}
protected final void putUInt128(final int index, final long leastSignificant,
final long mostSignificant) {
buffer.putLong(index, leastSignificant);
buffer.putLong(index + Long.BYTES, mostSignificant);
}
protected final long getUInt64(final int index) {
return buffer.getLong(index);
}
protected final void putUInt64(final int index, final long value) {
buffer.putLong(index, value);
}
protected final int getUInt32(final int index) {
return buffer.getInt(index);
}
protected final void putUInt32(final int index, final int value) {
buffer.putInt(index, value);
}
protected final int getUInt16(final int index) {
return Short.toUnsignedInt(buffer.getShort(index));
}
protected final void putUInt16(final int index, final int value) {
if (value < 0 || value > Character.MAX_VALUE)
throw new IllegalArgumentException("Value must be a 16-bit unsigned integer");
buffer.putShort(index, (short) value);
}
protected final byte[] getArray(final int index, final int len) {
final byte[] array = new byte[len];
buffer.position(index);
buffer.get(array);
return array;
}
protected final void putArray(final int index, final byte[] array) {
Objects.requireNonNull(array, "Array cannot be null");
buffer.position(index);
buffer.put(array);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/IdBatch.java | package com.tigerbeetle;
import java.nio.ByteBuffer;
import java.util.Objects;
/**
* A {@link Batch batch} of 128-bit unsigned integers.
*/
public final class IdBatch extends Batch {
interface Struct {
int SIZE = 16;
}
static final IdBatch EMPTY = new IdBatch(0);
/**
* Constructs an empty batch of ids with the desired maximum capacity.
* <p>
* Once created, an instance cannot be resized, however it may contain any number of ids between
* zero and its {@link #getCapacity capacity}.
*
* @param capacity the maximum capacity.
*
* @throws IllegalArgumentException if capacity is negative.
*/
public IdBatch(final int capacity) {
super(capacity, Struct.SIZE);
}
IdBatch(final ByteBuffer buffer) {
super(buffer, Struct.SIZE);
}
/**
* Constructs a batch of ids copying the elements from an array.
*
* @param ids the array of ids.
*
* @throws NullPointerException if {@code ids} is null.
*/
public IdBatch(final byte[]... ids) {
super(ids.length, Struct.SIZE);
for (final var id : ids) {
add(id);
}
}
/**
* Adds a new id at the end of this batch.
* <p>
* If successful, moves the current {@link #setPosition position} to the newly created id.
*
* @param id an array of 16 bytes representing the 128-bit value.
*
* @throws IllegalStateException if this batch is read-only.
* @throws IndexOutOfBoundsException if exceeds the batch's capacity.
*/
public void add(final byte[] id) {
super.add();
setId(id);
}
/**
* Adds a new id at the end of this batch.
* <p>
* If successful, moves the current {@link #setPosition position} to the newly created id.
*
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
*
* @throws IllegalStateException if this batch is read-only.
* @throws IndexOutOfBoundsException if exceeds the batch's capacity.
*/
public void add(final long leastSignificant, final long mostSignificant) {
super.add();
setId(leastSignificant, mostSignificant);
}
/**
* Adds a new id at the end of this batch.
* <p>
* If successful, moves the current {@link #setPosition position} to the newly created id.
*
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
*
* @throws IllegalStateException if this batch is read-only.
* @throws IndexOutOfBoundsException if exceeds the batch's capacity.
*/
public void add(final long leastSignificant) {
super.add();
setId(leastSignificant, 0);
}
/**
* Gets the id.
*
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public byte[] getId() {
return getUInt128(at(0));
}
/**
* Gets the id.
*
* @param part a {@link UInt128} enum indicating which part of the 128-bit value is to be
* retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
*/
public long getId(final UInt128 part) {
return getUInt128(at(0), part);
}
/**
* Sets the id.
*
* @param id an array of 16 bytes representing the 128-bit value.
* @throws NullPointerException if {@code id} is null.
* @throws IllegalArgumentException if {@code id} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setId(final byte[] id) {
Objects.requireNonNull(id, "Id cannot be null");
putUInt128(at(0), id);
}
/**
* Sets the id.
*
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
*/
public void setId(final long leastSignificant, final long mostSignificant) {
putUInt128(at(0), leastSignificant, mostSignificant);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/AccountFlags.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
public interface AccountFlags {
int NONE = (int) 0;
/**
* @see <a href="https://docs.tigerbeetle.com/reference/account#flagslinked">linked</a>
*/
int LINKED = (int) (1 << 0);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/account#flagsdebits_must_not_exceed_credits">debits_must_not_exceed_credits</a>
*/
int DEBITS_MUST_NOT_EXCEED_CREDITS = (int) (1 << 1);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/account#flagscredits_must_not_exceed_debits">credits_must_not_exceed_debits</a>
*/
int CREDITS_MUST_NOT_EXCEED_DEBITS = (int) (1 << 2);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/account#flagshistory">history</a>
*/
int HISTORY = (int) (1 << 3);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/account#flagsimported">imported</a>
*/
int IMPORTED = (int) (1 << 4);
/**
* @see <a href="https://docs.tigerbeetle.com/reference/account#flagsclosed">closed</a>
*/
int CLOSED = (int) (1 << 5);
static boolean hasLinked(final int flags) {
return (flags & LINKED) == LINKED;
}
static boolean hasDebitsMustNotExceedCredits(final int flags) {
return (flags & DEBITS_MUST_NOT_EXCEED_CREDITS) == DEBITS_MUST_NOT_EXCEED_CREDITS;
}
static boolean hasCreditsMustNotExceedDebits(final int flags) {
return (flags & CREDITS_MUST_NOT_EXCEED_DEBITS) == CREDITS_MUST_NOT_EXCEED_DEBITS;
}
static boolean hasHistory(final int flags) {
return (flags & HISTORY) == HISTORY;
}
static boolean hasImported(final int flags) {
return (flags & IMPORTED) == IMPORTED;
}
static boolean hasClosed(final int flags) {
return (flags & CLOSED) == CLOSED;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/RequestException.java | package com.tigerbeetle;
/**
* RequestException is thrown when the internal invariants of the underlying native library are
* violated, which is expected to never happen. If tis exception is thrown, then either there is a
* programming error in the tigerbeetle-java library itself, or there is a version mismatch between
* the java code and the underlying native library.
*/
public final class RequestException extends RuntimeException {
private final byte status;
public RequestException(byte status) {
this.status = status;
}
public byte getStatus() {
return status;
}
@Override
public String getMessage() {
return toString();
}
@Override
public String toString() {
if (status == PacketStatus.TooMuchData.value)
return "Too much data provided on this batch.";
else if (status == PacketStatus.InvalidOperation.value)
return "Invalid operation.";
else if (status == PacketStatus.InvalidDataSize.value)
return "Invalid data size.";
else
return "Unknown error status " + status;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/AccountBalanceBatch.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
import java.nio.ByteBuffer;
import java.math.BigInteger;
public final class AccountBalanceBatch extends Batch {
interface Struct {
int SIZE = 128;
int DebitsPending = 0;
int DebitsPosted = 16;
int CreditsPending = 32;
int CreditsPosted = 48;
int Timestamp = 64;
int Reserved = 72;
}
static final AccountBalanceBatch EMPTY = new AccountBalanceBatch(0);
/**
* Creates an empty batch with the desired maximum capacity.
* <p>
* Once created, an instance cannot be resized, however it may contain any number of elements
* between zero and its {@link #getCapacity capacity}.
*
* @param capacity the maximum capacity.
* @throws IllegalArgumentException if capacity is negative.
*/
public AccountBalanceBatch(final int capacity) {
super(capacity, Struct.SIZE);
}
AccountBalanceBatch(final ByteBuffer buffer) {
super(buffer, Struct.SIZE);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_pending">debits_pending</a>
*/
public BigInteger getDebitsPending() {
final var index = at(Struct.DebitsPending);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_pending">debits_pending</a>
*/
public long getDebitsPending(final UInt128 part) {
return getUInt128(at(Struct.DebitsPending), part);
}
/**
* @param debitsPending a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_pending">debits_pending</a>
*/
void setDebitsPending(final BigInteger debitsPending) {
putUInt128(at(Struct.DebitsPending), UInt128.asBytes(debitsPending));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_pending">debits_pending</a>
*/
void setDebitsPending(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.DebitsPending), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_pending">debits_pending</a>
*/
void setDebitsPending(final long leastSignificant) {
putUInt128(at(Struct.DebitsPending), leastSignificant, 0);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_posted">debits_posted</a>
*/
public BigInteger getDebitsPosted() {
final var index = at(Struct.DebitsPosted);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_posted">debits_posted</a>
*/
public long getDebitsPosted(final UInt128 part) {
return getUInt128(at(Struct.DebitsPosted), part);
}
/**
* @param debitsPosted a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_posted">debits_posted</a>
*/
void setDebitsPosted(final BigInteger debitsPosted) {
putUInt128(at(Struct.DebitsPosted), UInt128.asBytes(debitsPosted));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_posted">debits_posted</a>
*/
void setDebitsPosted(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.DebitsPosted), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#debits_posted">debits_posted</a>
*/
void setDebitsPosted(final long leastSignificant) {
putUInt128(at(Struct.DebitsPosted), leastSignificant, 0);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_pending">credits_pending</a>
*/
public BigInteger getCreditsPending() {
final var index = at(Struct.CreditsPending);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_pending">credits_pending</a>
*/
public long getCreditsPending(final UInt128 part) {
return getUInt128(at(Struct.CreditsPending), part);
}
/**
* @param creditsPending a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_pending">credits_pending</a>
*/
void setCreditsPending(final BigInteger creditsPending) {
putUInt128(at(Struct.CreditsPending), UInt128.asBytes(creditsPending));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_pending">credits_pending</a>
*/
void setCreditsPending(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.CreditsPending), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_pending">credits_pending</a>
*/
void setCreditsPending(final long leastSignificant) {
putUInt128(at(Struct.CreditsPending), leastSignificant, 0);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_posted">credits_posted</a>
*/
public BigInteger getCreditsPosted() {
final var index = at(Struct.CreditsPosted);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_posted">credits_posted</a>
*/
public long getCreditsPosted(final UInt128 part) {
return getUInt128(at(Struct.CreditsPosted), part);
}
/**
* @param creditsPosted a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_posted">credits_posted</a>
*/
void setCreditsPosted(final BigInteger creditsPosted) {
putUInt128(at(Struct.CreditsPosted), UInt128.asBytes(creditsPosted));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_posted">credits_posted</a>
*/
void setCreditsPosted(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.CreditsPosted), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#credits_posted">credits_posted</a>
*/
void setCreditsPosted(final long leastSignificant) {
putUInt128(at(Struct.CreditsPosted), leastSignificant, 0);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#timestamp">timestamp</a>
*/
public long getTimestamp() {
final var value = getUInt64(at(Struct.Timestamp));
return value;
}
/**
* @param timestamp
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#timestamp">timestamp</a>
*/
void setTimestamp(final long timestamp) {
putUInt64(at(Struct.Timestamp), timestamp);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#reserved">reserved</a>
*/
byte[] getReserved() {
return getArray(at(Struct.Reserved), 56);
}
/**
* @param reserved
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account-balances#reserved">reserved</a>
*/
void setReserved(byte[] reserved) {
if (reserved == null)
reserved = new byte[56];
if (reserved.length != 56)
throw new IllegalArgumentException("Reserved must be 56 bytes long");
putArray(at(Struct.Reserved), reserved);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/Client.java | package com.tigerbeetle;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.concurrent.CompletableFuture;
public final class Client implements AutoCloseable {
private final byte[] clusterID;
private final NativeClient nativeClient;
/**
* Initializes an instance of TigerBeetle client. This class is thread-safe and for optimal
* performance, a single instance should be shared between multiple concurrent tasks.
* <p>
* Multiple clients can be instantiated in case of connecting to more than one TigerBeetle
* cluster.
*
* @param clusterID
* @param replicaAddresses
*
* @throws InitializationException if an error occurred initializing this client. See
* {@link InitializationStatus} for more details.
*
* @throws NullPointerException if {@code clusterID} is null.
* @throws IllegalArgumentException if {@code clusterID} is not a UInt128.
* @throws IllegalArgumentException if {@code replicaAddresses} is empty or presented in
* incorrect format.
* @throws NullPointerException if {@code replicaAddresses} is null or any element in the array
* is null.
*/
public Client(final byte[] clusterID, final String[] replicaAddresses) {
Objects.requireNonNull(clusterID, "ClusterID cannot be null");
if (clusterID.length != UInt128.SIZE)
throw new IllegalArgumentException("ClusterID must be 16 bytes long");
Objects.requireNonNull(replicaAddresses, "Replica addresses cannot be null");
if (replicaAddresses.length == 0)
throw new IllegalArgumentException("Empty replica addresses");
var joiner = new StringJoiner(",");
for (var address : replicaAddresses) {
Objects.requireNonNull(address, "Replica address cannot be null");
joiner.add(address);
}
this.clusterID = clusterID;
this.nativeClient = NativeClient.init(clusterID, joiner.toString());
}
/**
* Gets the cluster ID
*
* @return clusterID
*/
public byte[] getClusterID() {
return clusterID;
}
/**
* Submits a batch of new accounts to be created.
*
* @param batch a {@link com.tigerbeetle.AccountBatch batch} containing all accounts to be
* created.
* @return a read-only {@link com.tigerbeetle.CreateAccountResultBatch batch} describing the
* result.
* @throws RequestException refer to {@link PacketStatus} for more details.
* @throws IllegalArgumentException if {@code batch} is empty.
* @throws NullPointerException if {@code batch} is null.
* @throws IllegalStateException if this client is closed.
*/
public CreateAccountResultBatch createAccounts(final AccountBatch batch) {
final var request = BlockingRequest.createAccounts(this.nativeClient, batch);
request.beginRequest();
return request.waitForResult();
}
/**
* Submits a batch of new accounts to be created asynchronously.
*
* @see Client#createAccounts(AccountBatch)
* @param batch a {@link com.tigerbeetle.AccountBatch batch} containing all accounts to be
* created.
* @return a {@link java.util.concurrent.CompletableFuture} to be completed.
* @throws IllegalArgumentException if {@code batch} is empty.
* @throws NullPointerException if {@code batch} is null.
* @throws IllegalStateException if this client is closed.
*/
public CompletableFuture<CreateAccountResultBatch> createAccountsAsync(
final AccountBatch batch) {
final var request = AsyncRequest.createAccounts(this.nativeClient, batch);
request.beginRequest();
return request.getFuture();
}
/**
* Looks up a batch of accounts.
*
* @param batch an {@link com.tigerbeetle.IdBatch batch} containing all account ids.
* @return a read-only {@link com.tigerbeetle.AccountBatch batch} containing all accounts found.
* @throws RequestException refer to {@link PacketStatus} for more details.
* @throws IllegalArgumentException if {@code batch} is empty.
* @throws NullPointerException if {@code batch} is null.
* @throws IllegalStateException if this client is closed.
*/
public AccountBatch lookupAccounts(final IdBatch batch) {
final var request = BlockingRequest.lookupAccounts(this.nativeClient, batch);
request.beginRequest();
return request.waitForResult();
}
/**
* Looks up a batch of accounts asynchronously.
*
* @see Client#lookupAccounts
* @param batch a {@link com.tigerbeetle.IdBatch batch} containing all account ids.
* @return a {@link java.util.concurrent.CompletableFuture} to be completed.
* @throws IllegalArgumentException if {@code batch} is empty.
* @throws NullPointerException if {@code batch} is null.
* @throws IllegalStateException if this client is closed.
*/
public CompletableFuture<AccountBatch> lookupAccountsAsync(final IdBatch batch) {
final var request = AsyncRequest.lookupAccounts(this.nativeClient, batch);
request.beginRequest();
return request.getFuture();
}
/**
* Submits a batch of new transfers to be created.
*
* @param batch a {@link com.tigerbeetle.TransferBatch batch} containing all transfers to be
* created.
* @return a read-only {@link com.tigerbeetle.CreateTransferResultBatch batch} describing the
* result.
* @throws RequestException refer to {@link PacketStatus} for more details.
* @throws IllegalArgumentException if {@code batch} is empty.
* @throws NullPointerException if {@code batch} is null.
* @throws IllegalStateException if this client is closed.
*/
public CreateTransferResultBatch createTransfers(final TransferBatch batch) {
final var request = BlockingRequest.createTransfers(this.nativeClient, batch);
request.beginRequest();
return request.waitForResult();
}
/**
* Submits a batch of new transfers to be created asynchronously.
*
* @param batch a {@link com.tigerbeetle.TransferBatch batch} containing all transfers to be
* created.
* @return a {@link java.util.concurrent.CompletableFuture} to be completed.
* @throws IllegalArgumentException if {@code batch} is empty.
* @throws NullPointerException if {@code batch} is null.
* @throws IllegalStateException if this client is closed.
*/
public CompletableFuture<CreateTransferResultBatch> createTransfersAsync(
final TransferBatch batch) {
final var request = AsyncRequest.createTransfers(this.nativeClient, batch);
request.beginRequest();
return request.getFuture();
}
/**
* Looks up a batch of transfers.
*
* @param batch a {@link com.tigerbeetle.IdBatch batch} containing all transfer ids.
* @return a read-only {@link com.tigerbeetle.TransferBatch batch} containing all transfers
* found.
* @throws RequestException refer to {@link PacketStatus} for more details.
* @throws IllegalArgumentException if {@code batch} is empty.
* @throws NullPointerException if {@code batch} is null.
* @throws IllegalStateException if this client is closed.
*/
public TransferBatch lookupTransfers(final IdBatch batch) {
final var request = BlockingRequest.lookupTransfers(this.nativeClient, batch);
request.beginRequest();
return request.waitForResult();
}
/**
* Looks up a batch of transfers asynchronously.
*
* @see Client#lookupTransfers(IdBatch)
* @param batch a {@link com.tigerbeetle.IdBatch batch} containing all transfer ids.
* @return a {@link java.util.concurrent.CompletableFuture} to be completed.
* @throws IllegalArgumentException if {@code batch} is empty.
* @throws NullPointerException if {@code batch} is null.
* @throws IllegalStateException if this client is closed.
*/
public CompletableFuture<TransferBatch> lookupTransfersAsync(final IdBatch batch) {
final var request = AsyncRequest.lookupTransfers(this.nativeClient, batch);
request.beginRequest();
return request.getFuture();
}
/**
* Fetch transfers from a given account.
*
* @see Client#getAccountTransfers(AccountFilter)
* @param filter a {@link com.tigerbeetle.AccountFilter} containing all query parameters.
* @return a read-only {@link com.tigerbeetle.TransferBatch batch} containing all transfers that
* match the query parameters.
* @throws NullPointerException if {@code filter} is null.
* @throws IllegalStateException if this client is closed.
*/
public TransferBatch getAccountTransfers(final AccountFilter filter) {
final var request = BlockingRequest.getAccountTransfers(this.nativeClient, filter);
request.beginRequest();
return request.waitForResult();
}
/**
* Fetch transfers from a given account asynchronously.
*
* @see Client#getAccountTransfers(AccountFilter)
* @param filter a {@link com.tigerbeetle.AccountFilter} containing all query parameters.
* @return a {@link java.util.concurrent.CompletableFuture} to be completed.
* @throws NullPointerException if {@code filter} is null.
* @throws IllegalStateException if this client is closed.
*/
public CompletableFuture<TransferBatch> getAccountTransfersAsync(final AccountFilter filter) {
final var request = AsyncRequest.getAccountTransfers(this.nativeClient, filter);
request.beginRequest();
return request.getFuture();
}
/**
* Fetch the balance history from a given account.
*
* @see Client#getAccountBalances(AccountFilter)
* @param filter a {@link com.tigerbeetle.AccountFilter} containing all query parameters.
* @return a read-only {@link com.tigerbeetle.AccountBalanceBatch batch} containing all balances
* that match the query parameters.
* @throws NullPointerException if {@code filter} is null.
* @throws IllegalStateException if this client is closed.
*/
public AccountBalanceBatch getAccountBalances(final AccountFilter filter) {
final var request = BlockingRequest.getAccountBalances(this.nativeClient, filter);
request.beginRequest();
return request.waitForResult();
}
/**
* Fetch the balance history from a given account asynchronously.
*
* @see Client#getAccountBalances(AccountFilter)
* @param filter a {@link com.tigerbeetle.AccountFilter} containing all query parameters.
* @return a {@link java.util.concurrent.CompletableFuture} to be completed.
* @throws NullPointerException if {@code filter} is null.
* @throws IllegalStateException if this client is closed.
*/
public CompletableFuture<AccountBalanceBatch> getAccountBalancesAsync(
final AccountFilter filter) {
final var request = AsyncRequest.getAccountBalances(this.nativeClient, filter);
request.beginRequest();
return request.getFuture();
}
/**
* Query accounts.
*
* @param filter a {@link com.tigerbeetle.QueryFilter} containing all query parameters.
* @return a read-only {@link com.tigerbeetle.AccountBatch batch} containing all accounts that
* match the query parameters.
* @throws NullPointerException if {@code filter} is null.
* @throws IllegalStateException if this client is closed.
*/
public AccountBatch queryAccounts(final QueryFilter filter) {
final var request = BlockingRequest.queryAccounts(this.nativeClient, filter);
request.beginRequest();
return request.waitForResult();
}
/**
* Query accounts asynchronously.
*
* @see Client#queryAccounts(QueryFilter)
* @param filter a {@link com.tigerbeetle.QueryFilter} containing all query parameters.
* @return a {@link java.util.concurrent.CompletableFuture} to be completed.
* @throws NullPointerException if {@code filter} is null.
* @throws IllegalStateException if this client is closed.
*/
public CompletableFuture<AccountBatch> queryAccountsAsync(final QueryFilter filter) {
final var request = AsyncRequest.queryAccounts(this.nativeClient, filter);
request.beginRequest();
return request.getFuture();
}
/**
* Query transfers.
*
* @param filter a {@link com.tigerbeetle.QueryFilter} containing all query parameters.
* @return a read-only {@link com.tigerbeetle.TransferBatch batch} containing all transfers that
* match the query parameters.
* @throws NullPointerException if {@code filter} is null.
* @throws IllegalStateException if this client is closed.
*/
public TransferBatch queryTransfers(final QueryFilter filter) {
final var request = BlockingRequest.queryTransfers(this.nativeClient, filter);
request.beginRequest();
return request.waitForResult();
}
/**
* Query transfers asynchronously.
*
* @see Client#queryTransfers(QueryFilter)
* @param filter a {@link com.tigerbeetle.QueryFilter} containing all query parameters.
* @return a {@link java.util.concurrent.CompletableFuture} to be completed.
* @throws NullPointerException if {@code filter} is null.
* @throws IllegalStateException if this client is closed.
*/
public CompletableFuture<TransferBatch> queryTransfersAsync(final QueryFilter filter) {
final var request = AsyncRequest.queryTransfers(this.nativeClient, filter);
request.beginRequest();
return request.getFuture();
}
/**
* Closes the client, freeing all resources.
* <p>
* This method causes the current thread to wait for all ongoing requests to finish.
*
* @see java.lang.AutoCloseable#close()
*/
@Override
public void close() {
nativeClient.close();
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/UInt128.java | package com.tigerbeetle;
import java.security.SecureRandom;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Objects;
import java.util.UUID;
public enum UInt128 {
LeastSignificant,
MostSignificant;
public static final int SIZE = 16;
private static final BigInteger MOST_SIGNIFICANT_MASK = BigInteger.ONE.shiftLeft(64);
private static final BigInteger LEAST_SIGNIFICANT_MASK = BigInteger.valueOf(Long.MAX_VALUE);
/**
* Gets the partial 64-bit representation of a 128-bit unsigned integer.
*
* @param bytes an array of 16 bytes representing the 128-bit value.
* @param part a {@link UInt128} enum indicating which part of the 128-bit value is to be
* retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
*
* @throws NullPointerException if {@code bytes} is null.
* @throws IllegalArgumentException if {@code bytes} is not 16 bytes long.
*/
public static long asLong(final byte[] bytes, final UInt128 part) {
Objects.requireNonNull(bytes, "Bytes cannot be null");
if (bytes.length != UInt128.SIZE)
throw new IllegalArgumentException("Bytes must be 16 bytes long");
var buffer = ByteBuffer.wrap(bytes).order(Batch.BYTE_ORDER).position(0);
if (part == UInt128.MostSignificant)
buffer.position(Long.BYTES);
return buffer.getLong();
}
/**
* Gets an array of 16 bytes representing the 128-bit value.
*
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @return an array of 16 bytes representing the 128-bit value.
*/
public static byte[] asBytes(final long leastSignificant, final long mostSignificant) {
byte[] bytes = new byte[UInt128.SIZE];
if (leastSignificant != 0 || mostSignificant != 0) {
var buffer = ByteBuffer.wrap(bytes).order(Batch.BYTE_ORDER);
buffer.putLong(leastSignificant);
buffer.putLong(mostSignificant);
}
return bytes;
}
/**
* Gets an array of 16 bytes representing the 128-bit value.
*
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @return an array of 16 bytes representing the 128-bit value.
*/
public static byte[] asBytes(final long leastSignificant) {
return asBytes(leastSignificant, 0);
}
/**
* Gets an array of 16 bytes representing the UUID.
*
* @param uuid a {@link java.util.UUID}
* @return an array of 16 bytes representing the 128-bit value.
*
* @throws NullPointerException if {@code uuid} is null.
*/
public static byte[] asBytes(final UUID uuid) {
Objects.requireNonNull(uuid, "Uuid cannot be null");
return asBytes(uuid.getLeastSignificantBits(), uuid.getMostSignificantBits());
}
/**
* Gets a {@link java.util.UUID} representing a 128-bit value.
*
* @param bytes an array of 16 bytes representing the 128-bit value.
* @return a {@link java.util.UUID}.
*
* @throws NullPointerException if {@code bytes} is null.
* @throws IllegalArgumentException if {@code bytes} is not 16 bytes long.
*/
public static UUID asUUID(final byte[] bytes) {
final long leastSignificant = asLong(bytes, UInt128.LeastSignificant);
final long mostSignificant = asLong(bytes, UInt128.MostSignificant);
return new UUID(mostSignificant, leastSignificant);
}
/**
* Gets a {@link java.math.BigInteger} representing a 128-bit unsigned integer.
*
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @return a {@link java.math.BigInteger}.
*/
public static BigInteger asBigInteger(final long leastSignificant, final long mostSignificant) {
if (leastSignificant == 0 && mostSignificant == 0) {
return BigInteger.ZERO;
}
var bigintMsb = BigInteger.valueOf(mostSignificant);
var bigintLsb = BigInteger.valueOf(leastSignificant);
if (bigintMsb.signum() < 0) {
bigintMsb = bigintMsb.add(MOST_SIGNIFICANT_MASK);
}
if (bigintLsb.signum() < 0) {
bigintLsb = bigintLsb.add(MOST_SIGNIFICANT_MASK);
}
return bigintLsb.add(bigintMsb.multiply(MOST_SIGNIFICANT_MASK));
}
/**
* Gets a {@link java.math.BigInteger} representing a 128-bit unsigned integer.
*
* @param bytes an array of 16 bytes representing the 128-bit value.
* @return a {@code java.math.BigInteger}.
*
* @throws NullPointerException if {@code bytes} is null.
* @throws IllegalArgumentException if {@code bytes} is not 16 bytes long.
*/
public static BigInteger asBigInteger(final byte[] bytes) {
Objects.requireNonNull(bytes, "Bytes cannot be null");
if (bytes.length != UInt128.SIZE)
throw new IllegalArgumentException("Bytes must be 16 bytes long");
final var buffer = ByteBuffer.wrap(bytes).order(Batch.BYTE_ORDER).position(0);
return asBigInteger(buffer.getLong(), buffer.getLong());
}
/**
* Gets an array of 16 bytes representing the 128-bit unsigned integer.
*
* @param value a {@link java.math.BigDecimal}
* @return an array of 16 bytes representing the 128-bit value.
*
* @throws NullPointerException if {@code value} is null.
*/
public static byte[] asBytes(final BigInteger value) {
Objects.requireNonNull(value, "Value cannot be null");
if (BigInteger.ZERO.equals(value))
return new byte[SIZE];
final var parts = value.divideAndRemainder(MOST_SIGNIFICANT_MASK);
var bigintMsb = parts[0];
var bigintLsb = parts[1];
if (LEAST_SIGNIFICANT_MASK.compareTo(bigintMsb) < 0) {
bigintMsb = bigintMsb.subtract(MOST_SIGNIFICANT_MASK);
}
if (LEAST_SIGNIFICANT_MASK.compareTo(bigintLsb) < 0) {
bigintLsb = bigintLsb.subtract(MOST_SIGNIFICANT_MASK);
}
return asBytes(bigintLsb.longValueExact(), bigintMsb.longValueExact());
}
private static long idLastTimestamp = 0L;
private static final byte[] idLastRandom = new byte[10];
private static final SecureRandom idSecureRandom = new SecureRandom();
/**
* Generates a Universally Unique Binary Sortable Identifier as 16 bytes of a 128-bit value.
*
* The ID() function is thread-safe, the bytes returned are stored in little endian, and the
* unsigned 128-bit value increases monotonically. The algorithm is based on
* <a href="https://github.com/ulid/spec">ULID</a> but is adjusted for u128-LE interpretation.
*
* @throws ArithmeticException if the random monotonic bits in the same millisecond overflows.
* @return An array of 16 bytes representing an unsigned 128-bit value in little endian.
*/
public static byte[] id() {
long randomLo;
short randomHi;
long timestamp = System.currentTimeMillis();
// Only modify the static variables in the synchronized block.
synchronized (idSecureRandom) {
// Ensure timestamp is monotonic. If it advances forward, also generate a new random.
if (timestamp <= idLastTimestamp) {
timestamp = idLastTimestamp;
} else {
idLastTimestamp = timestamp;
idSecureRandom.nextBytes(idLastRandom);
}
var random = ByteBuffer.wrap(idLastRandom).order(ByteOrder.nativeOrder());
randomLo = random.getLong();
randomHi = random.getShort();
// Increment the u80 stored in idLastRandom using a u64 increment then u16 increment.
// Throws an exception if the entire u80 represented with both overflows.
// In Java, all arithmetic wraps around on overflow by default so check for zero.
randomLo += 1;
if (randomLo == 0) {
randomHi += 1;
if (randomHi == 0) {
throw new ArithmeticException("Random bits overflow on monotonic increment");
}
}
// Write back the incremented random.
random.flip();
random.putLong(randomLo);
random.putShort(randomHi);
}
var buffer = ByteBuffer.allocate(UInt128.SIZE).order(Batch.BYTE_ORDER);
buffer.putLong(randomLo);
buffer.putShort(randomHi);
buffer.putShort((short) timestamp); // timestamp lo
buffer.putInt((int) (timestamp >> 16)); // timestamp hi
return buffer.array();
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/AssertionError.java | package com.tigerbeetle;
public final class AssertionError extends java.lang.AssertionError {
AssertionError(String format, Object... args) {
super(String.format(format, args));
}
AssertionError(Throwable cause, String format, Object... args) {
super(String.format(format, args), cause);
}
public static void assertTrue(boolean condition, String format, Object... args) {
if (!condition)
throw new AssertionError(format, args);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/BlockingRequest.java | package com.tigerbeetle;
import static com.tigerbeetle.AssertionError.assertTrue;
final class BlockingRequest<TResponse extends Batch> extends Request<TResponse> {
// @formatter:off
/*
* Overview:
*
* Implements a Request that blocks the caller thread until signaled as completed by the TB's callback.
* See AsyncRequest.java for the async implementation.
*
* We could have used the same AsyncRequest implementation by just waiting the CompletableFuture<T>.
*
* CompletableFuture<T> implements a sophisticated lock using CAS + waiter stack:
* https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/concurrent/CompletableFuture.java#l114
*
* This BlockingRequest<T> implements a much simpler general-purpose "synchronized" block that relies on the
* standard Monitor.wait().
*
* This approach is particularly good here for 3 reasons:
*
* 1. We are always dealing with just one waiter thread, no need for a waiter stack.
* 2. It is expected for a request to be at least 2 io-ticks long, making sense to suspend the waiter thread immediately.
* 3. To avoid putting more pressure on the GC with additional object allocations required by the CompletableFuture
*
*/
// @formatter:on
private TResponse result;
private Throwable exception;
BlockingRequest(final NativeClient nativeClient, final Operations operation,
final Batch batch) {
super(nativeClient, operation, batch);
result = null;
exception = null;
}
public static BlockingRequest<CreateAccountResultBatch> createAccounts(
final NativeClient nativeClient, final AccountBatch batch) {
return new BlockingRequest<CreateAccountResultBatch>(nativeClient,
Request.Operations.CREATE_ACCOUNTS, batch);
}
public static BlockingRequest<AccountBatch> lookupAccounts(final NativeClient nativeClient,
final IdBatch batch) {
return new BlockingRequest<AccountBatch>(nativeClient, Request.Operations.LOOKUP_ACCOUNTS,
batch);
}
public static BlockingRequest<CreateTransferResultBatch> createTransfers(
final NativeClient nativeClient, final TransferBatch batch) {
return new BlockingRequest<CreateTransferResultBatch>(nativeClient,
Request.Operations.CREATE_TRANSFERS, batch);
}
public static BlockingRequest<TransferBatch> lookupTransfers(final NativeClient nativeClient,
final IdBatch batch) {
return new BlockingRequest<TransferBatch>(nativeClient, Request.Operations.LOOKUP_TRANSFERS,
batch);
}
public static BlockingRequest<TransferBatch> getAccountTransfers(
final NativeClient nativeClient, final AccountFilter filter) {
return new BlockingRequest<TransferBatch>(nativeClient,
Request.Operations.GET_ACCOUNT_TRANSFERS, filter.batch);
}
public static BlockingRequest<AccountBalanceBatch> getAccountBalances(
final NativeClient nativeClient, final AccountFilter filter) {
return new BlockingRequest<AccountBalanceBatch>(nativeClient,
Request.Operations.GET_ACCOUNT_BALANCES, filter.batch);
}
public static BlockingRequest<AccountBatch> queryAccounts(final NativeClient nativeClient,
final QueryFilter filter) {
return new BlockingRequest<AccountBatch>(nativeClient, Request.Operations.QUERY_ACCOUNTS,
filter.batch);
}
public static BlockingRequest<TransferBatch> queryTransfers(final NativeClient nativeClient,
final QueryFilter filter) {
return new BlockingRequest<TransferBatch>(nativeClient, Request.Operations.QUERY_TRANSFERS,
filter.batch);
}
public static BlockingRequest<AccountBatch> echo(final NativeClient nativeClient,
final AccountBatch batch) {
return new BlockingRequest<AccountBatch>(nativeClient, Request.Operations.ECHO_ACCOUNTS,
batch);
}
public static BlockingRequest<TransferBatch> echo(final NativeClient nativeClient,
final TransferBatch batch) {
return new BlockingRequest<TransferBatch>(nativeClient, Request.Operations.ECHO_TRANSFERS,
batch);
}
public boolean isDone() {
return result != null || exception != null;
}
public TResponse waitForResult() {
waitForCompletionUninterruptibly();
return getResult();
}
@Override
protected void setResult(final TResponse result) {
synchronized (this) {
if (isDone()) {
this.result = null;
this.exception = new AssertionError(this.exception,
"This request has already been completed");
} else {
this.result = result;
this.exception = null;
}
notify();
}
}
@Override
protected void setException(final Throwable exception) {
synchronized (this) {
this.result = null;
this.exception = exception;
notify();
}
}
private void waitForCompletionUninterruptibly() {
try {
if (!isDone()) {
synchronized (this) {
while (!isDone()) {
wait();
}
}
}
} catch (InterruptedException interruptedException) {
// Since we don't support canceling an ongoing request
// this exception should never exposed by the API to be handled by the user
throw new AssertionError(interruptedException,
"Unexpected thread interruption on waitForCompletion.");
}
}
TResponse getResult() {
assertTrue(result != null || exception != null, "Unexpected request result: result=null");
// Handling checked and unchecked exceptions accordingly
if (exception != null) {
if (exception instanceof RequestException)
throw (RequestException) exception;
if (exception instanceof RuntimeException)
throw (RuntimeException) exception;
if (exception instanceof Error)
throw (Error) exception;
throw new AssertionError(exception, "Unexpected exception");
} else {
return this.result;
}
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/JNILoader.java | package com.tigerbeetle;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
final class JNILoader {
enum OS {
windows,
linux,
macos;
public static OS getOS() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.startsWith("win")) {
return OS.windows;
} else if (osName.startsWith("mac") || osName.startsWith("darwin")) {
return OS.macos;
} else if (osName.startsWith("linux")) {
return OS.linux;
} else {
throw new AssertionError(String.format("Unsupported OS %s", osName));
}
}
}
enum Arch {
x86_64,
aarch64;
public static Arch getArch() {
String osArch = System.getProperty("os.arch").toLowerCase();
if (osArch.startsWith("x86_64") || osArch.startsWith("amd64")
|| osArch.startsWith("x64")) {
return Arch.x86_64;
} else if (osArch.startsWith("aarch64")) {
return Arch.aarch64;
} else {
throw new AssertionError(String.format("Unsupported OS arch %s", osArch));
}
}
}
enum Abi {
none,
gnu,
musl;
public static Abi getAbi(OS os) {
if (os != OS.linux)
return Abi.none;
/**
* We need to detect during runtime which libc the JVM uses to load the correct JNI lib.
*
* Rationale: The /proc/self/map_files/ subdirectory contains entries corresponding to
* memory-mapped files loaded by the JVM.
* https://man7.org/linux/man-pages/man5/proc.5.html: We detect a musl-based distro by
* checking if any library contains the name "musl".
*
* Prior art: https://github.com/xerial/sqlite-jdbc/issues/623
*/
final var mapFiles = Paths.get("/proc/self/map_files");
try (var stream = Files.newDirectoryStream(mapFiles)) {
for (final Path path : stream) {
try {
final var libName = path.toRealPath().toString().toLowerCase();
if (libName.contains("musl")) {
return Abi.musl;
}
} catch (IOException exception) {
continue;
}
}
} catch (IOException exception) {
}
return Abi.gnu;
}
}
private JNILoader() {}
public static final String libName = "tb_jniclient";
public static void loadFromJar() {
Arch arch = Arch.getArch();
OS os = OS.getOS();
Abi abi = Abi.getAbi(os);
final String jniResourcesPath = getResourcesPath(arch, os, abi);
final String fileName = Paths.get(jniResourcesPath).getFileName().toString();
File temp;
try (InputStream stream = JNILoader.class.getResourceAsStream(jniResourcesPath)) {
if (stream == null) {
// It's not expected when running from the jar package.
// If not found, we fallback to the standard JVM path and let the
// UnsatisfiedLinkError alert if it couldn't be found there.
System.loadLibrary(libName);
return;
}
temp = Files.createTempFile(fileName, "").toFile();
Files.copy(stream, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioException) {
throw new AssertionError(ioException,
"TigerBeetle jni %s could not be extracted from jar.", fileName);
}
System.load(temp.getAbsolutePath());
temp.deleteOnExit();
}
static String getResourcesPath(Arch arch, OS os, Abi abi) {
final String jniResources = String.format("/lib/%s-%s", arch, os);
switch (os) {
case linux:
return String.format("%s-%s/lib%s.so", jniResources, abi, libName);
case macos:
return String.format("%s/lib%s.dylib", jniResources, libName);
case windows:
if (arch == Arch.x86_64)
return String.format("%s/%s.dll", jniResources, libName);
break;
}
throw new AssertionError("Unsupported OS-arch %s-%s", os, arch);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/AccountBatch.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
import java.nio.ByteBuffer;
import java.math.BigInteger;
public final class AccountBatch extends Batch {
interface Struct {
int SIZE = 128;
int Id = 0;
int DebitsPending = 16;
int DebitsPosted = 32;
int CreditsPending = 48;
int CreditsPosted = 64;
int UserData128 = 80;
int UserData64 = 96;
int UserData32 = 104;
int Reserved = 108;
int Ledger = 112;
int Code = 116;
int Flags = 118;
int Timestamp = 120;
}
static final AccountBatch EMPTY = new AccountBatch(0);
/**
* Creates an empty batch with the desired maximum capacity.
* <p>
* Once created, an instance cannot be resized, however it may contain any number of elements
* between zero and its {@link #getCapacity capacity}.
*
* @param capacity the maximum capacity.
* @throws IllegalArgumentException if capacity is negative.
*/
public AccountBatch(final int capacity) {
super(capacity, Struct.SIZE);
}
AccountBatch(final ByteBuffer buffer) {
super(buffer, Struct.SIZE);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#id">id</a>
*/
public byte[] getId() {
return getUInt128(at(Struct.Id));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#id">id</a>
*/
public long getId(final UInt128 part) {
return getUInt128(at(Struct.Id), part);
}
/**
* @param id an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code id} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#id">id</a>
*/
public void setId(final byte[] id) {
putUInt128(at(Struct.Id), id);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#id">id</a>
*/
public void setId(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.Id), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#id">id</a>
*/
public void setId(final long leastSignificant) {
putUInt128(at(Struct.Id), leastSignificant, 0);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_pending">debits_pending</a>
*/
public BigInteger getDebitsPending() {
final var index = at(Struct.DebitsPending);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_pending">debits_pending</a>
*/
public long getDebitsPending(final UInt128 part) {
return getUInt128(at(Struct.DebitsPending), part);
}
/**
* @param debitsPending a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_pending">debits_pending</a>
*/
void setDebitsPending(final BigInteger debitsPending) {
putUInt128(at(Struct.DebitsPending), UInt128.asBytes(debitsPending));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_pending">debits_pending</a>
*/
void setDebitsPending(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.DebitsPending), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_pending">debits_pending</a>
*/
void setDebitsPending(final long leastSignificant) {
putUInt128(at(Struct.DebitsPending), leastSignificant, 0);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_posted">debits_posted</a>
*/
public BigInteger getDebitsPosted() {
final var index = at(Struct.DebitsPosted);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_posted">debits_posted</a>
*/
public long getDebitsPosted(final UInt128 part) {
return getUInt128(at(Struct.DebitsPosted), part);
}
/**
* @param debitsPosted a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_posted">debits_posted</a>
*/
void setDebitsPosted(final BigInteger debitsPosted) {
putUInt128(at(Struct.DebitsPosted), UInt128.asBytes(debitsPosted));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_posted">debits_posted</a>
*/
void setDebitsPosted(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.DebitsPosted), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#debits_posted">debits_posted</a>
*/
void setDebitsPosted(final long leastSignificant) {
putUInt128(at(Struct.DebitsPosted), leastSignificant, 0);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_pending">credits_pending</a>
*/
public BigInteger getCreditsPending() {
final var index = at(Struct.CreditsPending);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_pending">credits_pending</a>
*/
public long getCreditsPending(final UInt128 part) {
return getUInt128(at(Struct.CreditsPending), part);
}
/**
* @param creditsPending a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_pending">credits_pending</a>
*/
void setCreditsPending(final BigInteger creditsPending) {
putUInt128(at(Struct.CreditsPending), UInt128.asBytes(creditsPending));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_pending">credits_pending</a>
*/
void setCreditsPending(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.CreditsPending), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_pending">credits_pending</a>
*/
void setCreditsPending(final long leastSignificant) {
putUInt128(at(Struct.CreditsPending), leastSignificant, 0);
}
/**
* @return a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_posted">credits_posted</a>
*/
public BigInteger getCreditsPosted() {
final var index = at(Struct.CreditsPosted);
return UInt128.asBigInteger(
getUInt128(index, UInt128.LeastSignificant),
getUInt128(index, UInt128.MostSignificant));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_posted">credits_posted</a>
*/
public long getCreditsPosted(final UInt128 part) {
return getUInt128(at(Struct.CreditsPosted), part);
}
/**
* @param creditsPosted a {@link java.math.BigInteger} representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_posted">credits_posted</a>
*/
void setCreditsPosted(final BigInteger creditsPosted) {
putUInt128(at(Struct.CreditsPosted), UInt128.asBytes(creditsPosted));
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_posted">credits_posted</a>
*/
void setCreditsPosted(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.CreditsPosted), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#credits_posted">credits_posted</a>
*/
void setCreditsPosted(final long leastSignificant) {
putUInt128(at(Struct.CreditsPosted), leastSignificant, 0);
}
/**
* @return an array of 16 bytes representing the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_128">user_data_128</a>
*/
public byte[] getUserData128() {
return getUInt128(at(Struct.UserData128));
}
/**
* @param part a {@link UInt128} enum indicating which part of the 128-bit value
is to be retrieved.
* @return a {@code long} representing the first 8 bytes of the 128-bit value if
* {@link UInt128#LeastSignificant} is informed, or the last 8 bytes if
* {@link UInt128#MostSignificant}.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_128">user_data_128</a>
*/
public long getUserData128(final UInt128 part) {
return getUInt128(at(Struct.UserData128), part);
}
/**
* @param userData128 an array of 16 bytes representing the 128-bit value.
* @throws IllegalArgumentException if {@code userData128} is not 16 bytes long.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_128">user_data_128</a>
*/
public void setUserData128(final byte[] userData128) {
putUInt128(at(Struct.UserData128), userData128);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @param mostSignificant a {@code long} representing the last 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_128">user_data_128</a>
*/
public void setUserData128(final long leastSignificant, final long mostSignificant) {
putUInt128(at(Struct.UserData128), leastSignificant, mostSignificant);
}
/**
* @param leastSignificant a {@code long} representing the first 8 bytes of the 128-bit value.
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_128">user_data_128</a>
*/
public void setUserData128(final long leastSignificant) {
putUInt128(at(Struct.UserData128), leastSignificant, 0);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_64">user_data_64</a>
*/
public long getUserData64() {
final var value = getUInt64(at(Struct.UserData64));
return value;
}
/**
* @param userData64
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_64">user_data_64</a>
*/
public void setUserData64(final long userData64) {
putUInt64(at(Struct.UserData64), userData64);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_32">user_data_32</a>
*/
public int getUserData32() {
final var value = getUInt32(at(Struct.UserData32));
return value;
}
/**
* @param userData32
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#user_data_32">user_data_32</a>
*/
public void setUserData32(final int userData32) {
putUInt32(at(Struct.UserData32), userData32);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#reserved">reserved</a>
*/
int getReserved() {
final var value = getUInt32(at(Struct.Reserved));
return value;
}
/**
* @param reserved
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#reserved">reserved</a>
*/
void setReserved(final int reserved) {
putUInt32(at(Struct.Reserved), reserved);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#ledger">ledger</a>
*/
public int getLedger() {
final var value = getUInt32(at(Struct.Ledger));
return value;
}
/**
* @param ledger
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#ledger">ledger</a>
*/
public void setLedger(final int ledger) {
putUInt32(at(Struct.Ledger), ledger);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#code">code</a>
*/
public int getCode() {
final var value = getUInt16(at(Struct.Code));
return value;
}
/**
* @param code
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#code">code</a>
*/
public void setCode(final int code) {
putUInt16(at(Struct.Code), code);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#flags">flags</a>
*/
public int getFlags() {
final var value = getUInt16(at(Struct.Flags));
return value;
}
/**
* @param flags
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#flags">flags</a>
*/
public void setFlags(final int flags) {
putUInt16(at(Struct.Flags), flags);
}
/**
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @see <a href="https://docs.tigerbeetle.com/reference/account#timestamp">timestamp</a>
*/
public long getTimestamp() {
final var value = getUInt64(at(Struct.Timestamp));
return value;
}
/**
* @param timestamp
* @throws IllegalStateException if not at a {@link #isValidPosition valid position}.
* @throws IllegalStateException if a {@link #isReadOnly() read-only} batch.
* @see <a href="https://docs.tigerbeetle.com/reference/account#timestamp">timestamp</a>
*/
public void setTimestamp(final long timestamp) {
putUInt64(at(Struct.Timestamp), timestamp);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/main/java/com | repos/tigerbeetle/src/clients/java/src/main/java/com/tigerbeetle/PacketAcquireStatus.java | //////////////////////////////////////////////////////////
// This file was auto-generated by java_bindings.zig
// Do not manually modify.
//////////////////////////////////////////////////////////
package com.tigerbeetle;
enum PacketAcquireStatus {
Ok((int) 0),
ConcurrencyMaxExceeded((int) 1),
Shutdown((int) 2);
public final int value;
PacketAcquireStatus(int value) {
this.value = value;
}
public static PacketAcquireStatus fromValue(int value) {
var values = PacketAcquireStatus.values();
if (value < 0 || value >= values.length)
throw new IllegalArgumentException(
String.format("Invalid PacketAcquireStatus value=%d", value));
return values[value];
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test | repos/tigerbeetle/src/clients/java/src/test/java/module-info.test | open module com.tigerbeetle {
requires junit;
} |
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/TransferTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import org.junit.Test;
public class TransferTest {
@Test
public void testDefaultValues() {
var transfers = new TransferBatch(1);
transfers.add();
assertEquals(0L, transfers.getId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getId(UInt128.MostSignificant));
assertEquals(0L, transfers.getDebitAccountId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getDebitAccountId(UInt128.MostSignificant));
assertEquals(0L, transfers.getCreditAccountId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getCreditAccountId(UInt128.MostSignificant));
assertEquals(BigInteger.ZERO, transfers.getAmount());
assertEquals(0L, transfers.getPendingId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getPendingId(UInt128.MostSignificant));
assertEquals(0L, transfers.getUserData128(UInt128.LeastSignificant));
assertEquals(0L, transfers.getUserData128(UInt128.MostSignificant));
assertEquals(0L, transfers.getUserData64());
assertEquals(0, transfers.getUserData32());
assertEquals(0, transfers.getTimeout());
assertEquals(0, transfers.getLedger());
assertEquals(0, transfers.getCode());
assertEquals(TransferFlags.NONE, transfers.getFlags());
assertEquals(0L, transfers.getTimestamp());
}
@Test
public void testId() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(100, 200);
assertEquals(100L, transfers.getId(UInt128.LeastSignificant));
assertEquals(200L, transfers.getId(UInt128.MostSignificant));
}
@Test
public void testIdLong() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(100);
assertEquals(100L, transfers.getId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getId(UInt128.MostSignificant));
}
@Test
public void testIdAsBytes() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
transfers.setId(id);
assertArrayEquals(id, transfers.getId());
}
@Test
public void testIdNull() {
var transfers = new TransferBatch(1);
transfers.add();
byte[] id = null;
transfers.setId(id);
assertArrayEquals(new byte[16], transfers.getId());
}
@Test(expected = IllegalArgumentException.class)
public void testIdInvalid() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
transfers.setId(id);
assert false;
}
@Test
public void testDebitAccountId() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setDebitAccountId(100, 200);
assertEquals(100L, transfers.getDebitAccountId(UInt128.LeastSignificant));
assertEquals(200L, transfers.getDebitAccountId(UInt128.MostSignificant));
}
@Test
public void testDebitAccountIdLong() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setDebitAccountId(100);
assertEquals(100L, transfers.getDebitAccountId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getDebitAccountId(UInt128.MostSignificant));
}
@Test
public void testDebitAccountIdAsBytes() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
transfers.setDebitAccountId(id);
assertArrayEquals(id, transfers.getDebitAccountId());
}
@Test
public void testDebitAccountIdNull() {
var transfers = new TransferBatch(1);
transfers.add();
byte[] debitAccountId = null;
transfers.setDebitAccountId(debitAccountId);
assertArrayEquals(new byte[16], transfers.getDebitAccountId());
}
@Test(expected = IllegalArgumentException.class)
public void testDebitAccountIdInvalid() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
transfers.setDebitAccountId(id);
assert false;
}
@Test
public void testCreditAccountId() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setCreditAccountId(100, 200);
assertEquals(100L, transfers.getCreditAccountId(UInt128.LeastSignificant));
assertEquals(200L, transfers.getCreditAccountId(UInt128.MostSignificant));
}
@Test
public void testCreditAccountIdLong() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setCreditAccountId(100);
assertEquals(100L, transfers.getCreditAccountId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getCreditAccountId(UInt128.MostSignificant));
}
@Test
public void testCreditAccountIdAsBytes() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
transfers.setCreditAccountId(id);
assertArrayEquals(id, transfers.getCreditAccountId());
}
@Test
public void testCreditAccountIdNull() {
var transfers = new TransferBatch(1);
transfers.add();
byte[] creditAccountId = null;
transfers.setCreditAccountId(creditAccountId);
assertArrayEquals(new byte[16], transfers.getCreditAccountId());
}
@Test(expected = IllegalArgumentException.class)
public void testCreditAccountIdInvalid() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
transfers.setCreditAccountId(id);
assert false;
}
@Test
public void testAmount() {
var transfers = new TransferBatch(1);
transfers.add();
final var value = new BigInteger("123456789012345678901234567890");
transfers.setAmount(value);
assertEquals(value, transfers.getAmount());
}
@Test
public void testAmountLong() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setAmount(999);
assertEquals(BigInteger.valueOf(999), transfers.getAmount());
transfers.setAmount(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), transfers.getAmount());
assertEquals(999L, transfers.getAmount(UInt128.LeastSignificant));
assertEquals(1L, transfers.getAmount(UInt128.MostSignificant));
}
@Test
public void testPendingId() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setPendingId(100, 200);
assertEquals(100L, transfers.getPendingId(UInt128.LeastSignificant));
assertEquals(200L, transfers.getPendingId(UInt128.MostSignificant));
}
@Test
public void testPendingIdLong() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setPendingId(100);
assertEquals(100L, transfers.getPendingId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getPendingId(UInt128.MostSignificant));
}
@Test
public void testPendingIdAsBytes() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
transfers.setPendingId(id);
assertArrayEquals(id, transfers.getPendingId());
}
@Test
public void testPendingIdNull() {
var transfers = new TransferBatch(1);
transfers.add();
byte[] pendingId = null;
transfers.setPendingId(pendingId);
assertEquals(0L, transfers.getPendingId(UInt128.LeastSignificant));
assertEquals(0L, transfers.getPendingId(UInt128.MostSignificant));
}
@Test(expected = IllegalArgumentException.class)
public void testPendingIdInvalid() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
transfers.setPendingId(id);
assert false;
}
@Test
public void testUserData128Long() {
var transfers = new TransferBatch(2);
transfers.add();
transfers.setUserData128(100);
assertEquals(100L, transfers.getUserData128(UInt128.LeastSignificant));
assertEquals(0L, transfers.getUserData128(UInt128.MostSignificant));
}
@Test
public void testUserData128() {
var transfers = new TransferBatch(2);
transfers.add();
transfers.setUserData128(100, 200);
assertEquals(100L, transfers.getUserData128(UInt128.LeastSignificant));
assertEquals(200L, transfers.getUserData128(UInt128.MostSignificant));
}
@Test
public void testUserData128AsBytes() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
transfers.setUserData128(id);
assertArrayEquals(id, transfers.getUserData128());
}
@Test
public void testUserData128Null() {
var transfers = new TransferBatch(1);
transfers.add();
byte[] userData = null;
transfers.setUserData128(userData);
assertEquals(0L, transfers.getUserData128(UInt128.LeastSignificant));
assertEquals(0L, transfers.getUserData128(UInt128.MostSignificant));
}
@Test(expected = IllegalArgumentException.class)
public void testUserData128Invalid() {
var transfers = new TransferBatch(1);
transfers.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
transfers.setUserData128(id);
assert false;
}
@Test
public void testUserData64() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setUserData64(1000L);
assertEquals(1000L, transfers.getUserData64());
}
@Test
public void testUserData32() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setUserData32(100);
assertEquals(100, transfers.getUserData32());
}
@Test
public void testTimeout() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setTimeout(9999);
assertEquals(9999, transfers.getTimeout());
}
@Test
public void testLedger() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setLedger(200);
assertEquals(200, transfers.getLedger());
}
@Test
public void testCode() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setCode(30);
assertEquals(30, transfers.getCode());
}
@Test(expected = IllegalArgumentException.class)
public void testCodeNegative() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setCode(-1);
}
@Test(expected = IllegalArgumentException.class)
public void testCodeOverflow() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setCode(Integer.MAX_VALUE);
}
@Test
public void testCodeUnsigned() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setCode(53000);
assertEquals(53000, transfers.getCode());
}
@Test
public void testFlags() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setFlags(TransferFlags.POST_PENDING_TRANSFER | TransferFlags.LINKED);
assertEquals((int) (TransferFlags.POST_PENDING_TRANSFER | TransferFlags.LINKED),
transfers.getFlags());
}
@Test(expected = IllegalArgumentException.class)
public void testFlagsNegative() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setFlags(-1);
}
@Test(expected = IllegalArgumentException.class)
public void testFlagsOverflow() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setFlags(Integer.MAX_VALUE);
}
@Test
public void testFlagsUnsigned() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setFlags(60000);
assertEquals(60000, transfers.getFlags());
}
@Test
public void testTimestamp() {
var transfers = new TransferBatch(1);
transfers.add();
transfers.setTimestamp(1234567890);
assertEquals((long) 1234567890, transfers.getTimestamp());
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/AccountFilterTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class AccountFilterTest {
@Test
public void testDefaultValues() {
final var accountFilter = new AccountFilter();
assertEquals(0L, accountFilter.getAccountId(UInt128.LeastSignificant));
assertEquals(0L, accountFilter.getAccountId(UInt128.MostSignificant));
assertEquals(0L, accountFilter.getTimestampMin());
assertEquals(0L, accountFilter.getTimestampMax());
assertEquals(0, accountFilter.getLimit());
assertEquals(false, accountFilter.getDebits());
assertEquals(false, accountFilter.getCredits());
assertEquals(false, accountFilter.getReversed());
}
@Test
public void testAccountId() {
final var accountFilter = new AccountFilter();
accountFilter.setAccountId(100, 200);
assertEquals(100L, accountFilter.getAccountId(UInt128.LeastSignificant));
assertEquals(200L, accountFilter.getAccountId(UInt128.MostSignificant));
}
@Test
public void testAccountIdLong() {
final var accountFilter = new AccountFilter();
accountFilter.setAccountId(100);
assertEquals(100L, accountFilter.getAccountId(UInt128.LeastSignificant));
assertEquals(0L, accountFilter.getAccountId(UInt128.MostSignificant));
}
@Test
public void testAccountIdIdAsBytes() {
final var accountFilter = new AccountFilter();
final var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
accountFilter.setAccountId(id);
assertArrayEquals(id, accountFilter.getAccountId());
}
@Test
public void testAccountIdNull() {
final var accountFilter = new AccountFilter();
final byte[] id = null;
accountFilter.setAccountId(id);
assertArrayEquals(new byte[16], accountFilter.getAccountId());
}
@Test(expected = IllegalArgumentException.class)
public void testAccountIdInvalid() {
final var accountFilter = new AccountFilter();
final var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
accountFilter.setAccountId(id);
assert false;
}
@Test
public void testTimestampMin() {
final var accountFilter = new AccountFilter();
accountFilter.setTimestampMin(100L);
assertEquals(100, accountFilter.getTimestampMin());
}
@Test
public void testTimestampMax() {
final var accountFilter = new AccountFilter();
accountFilter.setTimestampMax(100L);
assertEquals(100, accountFilter.getTimestampMax());
}
@Test
public void testLimit() {
final var accountFilter = new AccountFilter();
accountFilter.setLimit(30);
assertEquals(30, accountFilter.getLimit());
}
@Test
public void testFlags() {
// Debits
{
final var accountFilter = new AccountFilter();
accountFilter.setDebits(true);
assertEquals(true, accountFilter.getDebits());
assertEquals(false, accountFilter.getCredits());
assertEquals(false, accountFilter.getReversed());
}
// Credits
{
final var accountFilter = new AccountFilter();
accountFilter.setCredits(true);
assertEquals(false, accountFilter.getDebits());
assertEquals(true, accountFilter.getCredits());
assertEquals(false, accountFilter.getReversed());
}
// Direction
{
final var accountFilter = new AccountFilter();
accountFilter.setReversed(true);
assertEquals(false, accountFilter.getDebits());
assertEquals(false, accountFilter.getCredits());
assertEquals(true, accountFilter.getReversed());
}
}
@Test
public void testReserved() {
final var accountFilter = new AccountFilterBatch(1);
accountFilter.add();
// Empty array:
final var bytes = new byte[24];
assertArrayEquals(new byte[24], accountFilter.getReserved());
// Null == empty array:
assertArrayEquals(new byte[24], accountFilter.getReserved());
accountFilter.setReserved(null);
for (byte i = 0; i < 24; i++) {
bytes[i] = i;
}
accountFilter.setReserved(bytes);
assertArrayEquals(bytes, accountFilter.getReserved());
}
@Test(expected = IllegalArgumentException.class)
public void testReservedInvalid() {
final var accountFilter = new AccountFilterBatch(1);
accountFilter.add();
accountFilter.setReserved(new byte[25]);
assert false;
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/JNILoaderTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class JNILoaderTest {
@Test
public void testResourcePath() {
assertEquals("/lib/x86_64-linux-gnu/libtb_jniclient.so", JNILoader
.getResourcesPath(JNILoader.Arch.x86_64, JNILoader.OS.linux, JNILoader.Abi.gnu));
assertEquals("/lib/aarch64-linux-gnu/libtb_jniclient.so", JNILoader
.getResourcesPath(JNILoader.Arch.aarch64, JNILoader.OS.linux, JNILoader.Abi.gnu));
assertEquals("/lib/x86_64-linux-musl/libtb_jniclient.so", JNILoader
.getResourcesPath(JNILoader.Arch.x86_64, JNILoader.OS.linux, JNILoader.Abi.musl));
assertEquals("/lib/aarch64-linux-musl/libtb_jniclient.so", JNILoader
.getResourcesPath(JNILoader.Arch.aarch64, JNILoader.OS.linux, JNILoader.Abi.musl));
assertEquals("/lib/x86_64-macos/libtb_jniclient.dylib", JNILoader
.getResourcesPath(JNILoader.Arch.x86_64, JNILoader.OS.macos, JNILoader.Abi.none));
assertEquals("/lib/aarch64-macos/libtb_jniclient.dylib", JNILoader
.getResourcesPath(JNILoader.Arch.aarch64, JNILoader.OS.macos, JNILoader.Abi.none));
assertEquals("/lib/x86_64-windows/tb_jniclient.dll", JNILoader
.getResourcesPath(JNILoader.Arch.x86_64, JNILoader.OS.windows, JNILoader.Abi.none));
}
@Test(expected = AssertionError.class)
public void testUnsupportedPlatform() {
JNILoader.getResourcesPath(JNILoader.Arch.aarch64, JNILoader.OS.windows,
JNILoader.Abi.none);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/EchoTest.java | package com.tigerbeetle;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class EchoTest {
static final int HEADER_SIZE = 256; // @sizeOf(vsr.Header)
static final int TRANSFER_SIZE = 128; // @sizeOf(Transfer)
static final int MESSAGE_SIZE_MAX = 1024 * 1024; // config.message_size_max
static final int ITEMS_PER_BATCH = (MESSAGE_SIZE_MAX - HEADER_SIZE) / TRANSFER_SIZE;
// The number of times the same test is repeated, to stress the
// cycle of packet exhaustion followed by completions.
static final int repetitionsMax = 16;
// The number of concurrency requests on each cycle.
static final int concurrencyMax = 64;
@Test(expected = AssertionError.class)
public void testConstructorNullReplicaAddresses() throws Throwable {
try (var client = new EchoClient(UInt128.asBytes(0), null)) {
} catch (Throwable any) {
throw any;
}
}
@Test(expected = AssertionError.class)
public void testConstructorInvalidCluster() throws Throwable {
var clusterInvalid = new byte[] {1, 2, 3};
try (var client = new EchoClient(clusterInvalid, "3000")) {
} catch (Throwable any) {
throw any;
}
}
@Test
public void testEchoAccounts() throws Throwable {
final Random rnd = new Random(1);
try (var client = new EchoClient(UInt128.asBytes(0), "3000")) {
final var batch = new AccountBatch(getRandomData(rnd, AccountBatch.Struct.SIZE));
final var reply = client.echo(batch);
assertBatchesEqual(batch, reply);
}
}
@Test
public void testEchoTransfers() throws Throwable {
final Random rnd = new Random(2);
try (var client = new EchoClient(UInt128.asBytes(0), "3000")) {
final var batch = new TransferBatch(getRandomData(rnd, TransferBatch.Struct.SIZE));
final var future = client.echoAsync(batch);
final var reply = future.join();
assertBatchesEqual(batch, reply);
}
}
@Test
public void testEchoAccountsAsync() throws Throwable {
final class AsyncContext {
public AccountBatch batch;
public CompletableFuture<AccountBatch> future;
};
final Random rnd = new Random(3);
try (var client = new EchoClient(UInt128.asBytes(0), "3000")) {
for (int repetition = 0; repetition < repetitionsMax; repetition++) {
final var list = new ArrayList<AsyncContext>();
for (int i = 0; i < concurrencyMax; i++) {
// Submitting some random data to be echoed back:
final var batch =
new AccountBatch(getRandomData(rnd, AccountBatch.Struct.SIZE));
var context = new AsyncContext();
context.batch = batch;
context.future = client.echoAsync(batch);
list.add(context);
}
for (var context : list) {
final var batch = context.batch;
final var reply = context.future.get();
assertBatchesEqual(batch, reply);
}
}
}
}
@Test
public void testEchoTransfersConcurrent() throws Throwable {
final class ThreadContext extends Thread {
public final TransferBatch batch;
private final EchoClient client;
private TransferBatch reply;
private Throwable exception;
public ThreadContext(EchoClient client, TransferBatch batch) {
this.client = client;
this.batch = batch;
this.reply = null;
this.exception = null;
}
public TransferBatch getReply() {
if (exception != null)
throw new RuntimeException(exception);
return reply;
}
@Override
public synchronized void run() {
try {
reply = client.echo(batch);
} catch (Throwable e) {
exception = e;
}
}
}
final Random rnd = new Random(4);
try (var client = new EchoClient(UInt128.asBytes(0), "3000")) {
for (int repetition = 0; repetition < repetitionsMax; repetition++) {
final var list = new ArrayList<ThreadContext>();
for (int i = 0; i < concurrencyMax; i++) {
// Submitting some random data to be echoed back:
final var batch =
new TransferBatch(getRandomData(rnd, TransferBatch.Struct.SIZE));
var context = new ThreadContext(client, batch);
context.start();
list.add(context);
}
for (var context : list) {
context.join();
final var batch = context.batch;
final var reply = context.getReply();
assertBatchesEqual(batch, reply);
}
}
}
}
private ByteBuffer getRandomData(final Random rnd, final int SIZE) {
final var length = rnd.nextInt(ITEMS_PER_BATCH - 1) + 1;
var buffer = ByteBuffer.allocateDirect(length * SIZE);
for (int i = 0; i < length; i++) {
var item = new byte[SIZE];
rnd.nextBytes(item);
buffer.put(item);
}
return buffer.position(0);
}
private void assertBatchesEqual(Batch batch, Batch reply) {
final var capacity = batch.getCapacity();
assertEquals(capacity, reply.getCapacity());
final var length = batch.getLength();
assertEquals(length, reply.getLength());
var buffer = batch.getBuffer();
var replyBuffer = reply.getBuffer();
assertEquals(buffer, replyBuffer);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/BlockingRequestTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.junit.Test;
import com.tigerbeetle.Request.Operations;
public class BlockingRequestTest {
@Test
public void testCreateAccountsRequestConstructor() {
var client = getDummyClient();
var batch = new AccountBatch(1);
batch.add();
var request = BlockingRequest.createAccounts(client, batch);
assert request != null;
}
@Test
public void testCreateTransfersRequestConstructor() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var request = BlockingRequest.createTransfers(client, batch);
assert request != null;
}
@Test
public void testLookupAccountsRequestConstructor() {
var client = getDummyClient();
var batch = new IdBatch(1);
batch.add();
var request = BlockingRequest.lookupAccounts(client, batch);
assert request != null;
}
@Test
public void testLookupTransfersRequestConstructor() {
var client = getDummyClient();
var batch = new IdBatch(1);
batch.add();
var request = BlockingRequest.lookupTransfers(client, batch);
assert request != null;
}
@Test(expected = NullPointerException.class)
public void testConstructorWithClientNull() {
var batch = new AccountBatch(1);
batch.add();
BlockingRequest.createAccounts(null, batch);
assert false;
}
@Test(expected = NullPointerException.class)
public void testConstructorWithBatchNull() {
var client = getDummyClient();
BlockingRequest.createAccounts(client, null);
assert false;
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorWithZeroCapacityBatch() {
var client = getDummyClient();
var batch = new AccountBatch(0);
BlockingRequest.createAccounts(client, batch);
assert false;
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorWithZeroItemsBatch() {
var client = getDummyClient();
var batch = new AccountBatch(1);
BlockingRequest.createAccounts(client, batch);
assert false;
}
@Test(expected = AssertionError.class)
public void testEndRequestWithInvalidOperation() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var request = BlockingRequest.createTransfers(client, batch);
assertFalse(request.isDone());
// Invalid operation, should be CREATE_TRANSFERS
request.endRequest(Request.Operations.LOOKUP_ACCOUNTS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
request.waitForResult();
assert false;
}
@Test(expected = AssertionError.class)
public void testEndRequestWithUnknownOperation() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
final byte UNKNOWN = 99;
var request = new BlockingRequest<CreateTransferResultBatch>(client,
Operations.CREATE_TRANSFERS, batch);
assertFalse(request.isDone());
// Unknown operation
request.endRequest(UNKNOWN, PacketStatus.Ok.value);
assertTrue(request.isDone());
request.waitForResult();
assert false;
}
@Test
public void testEndRequestWithNullBuffer() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var request = BlockingRequest.createTransfers(client, batch);
assertFalse(request.isDone());
request.endRequest(Request.Operations.CREATE_TRANSFERS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
var result = request.waitForResult();
assertEquals(0, result.getLength());
}
@Test(expected = AssertionError.class)
public void testEndRequestWithInvalidBufferSize() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var request = BlockingRequest.createTransfers(client, batch);
var invalidBuffer = ByteBuffer.allocate((CreateTransferResultBatch.Struct.SIZE * 2) - 1);
assertFalse(request.isDone());
request.setReplyBuffer(invalidBuffer.array());
request.endRequest(Request.Operations.CREATE_TRANSFERS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
request.waitForResult();
assert false;
}
@Test(expected = AssertionError.class)
public void testGetResultBeforeEndRequest() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var request = BlockingRequest.createTransfers(client, batch);
assertFalse(request.isDone());
request.getResult();
assert false;
}
@Test
public void testEndRequestWithRequestException() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var request = BlockingRequest.createTransfers(client, batch);
assertFalse(request.isDone());
var dummyBuffer = ByteBuffer.allocate(CreateTransferResultBatch.Struct.SIZE);
request.setReplyBuffer(dummyBuffer.array());
request.endRequest(Request.Operations.CREATE_TRANSFERS.value,
PacketStatus.TooMuchData.value);
assertTrue(request.isDone());
try {
request.waitForResult();
assert false;
} catch (RequestException e) {
assertEquals(PacketStatus.TooMuchData.value, e.getStatus());
}
}
@Test(expected = AssertionError.class)
public void testEndRequestWithAmountOfResultsGreaterThanAmountOfRequests() {
var client = getDummyClient();
// A batch with only 1 item
var batch = new AccountBatch(1);
batch.add();
// A reply with 2 items, while the batch had only 1 item
var dummyReplyBuffer = ByteBuffer.allocate(CreateAccountResultBatch.Struct.SIZE * 2)
.order(ByteOrder.LITTLE_ENDIAN);
var request = BlockingRequest.createAccounts(client, batch);
request.setReplyBuffer(dummyReplyBuffer.position(0).array());
request.endRequest(Request.Operations.CREATE_ACCOUNTS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
request.waitForResult();
}
@Test(expected = AssertionError.class)
public void testEndRequestTwice() {
var client = getDummyClient();
// A batch with only 1 item
var batch = new AccountBatch(1);
batch.add();
// A reply with 2 items, while the batch had only 1 item
var dummyReplyBuffer = ByteBuffer.allocate(CreateAccountResultBatch.Struct.SIZE)
.order(ByteOrder.LITTLE_ENDIAN);
var request = BlockingRequest.createAccounts(client, batch);
assertFalse(request.isDone());
request.setReplyBuffer(dummyReplyBuffer.position(0).array());
request.endRequest(Request.Operations.CREATE_ACCOUNTS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
var result = request.waitForResult();
assertEquals(1, result.getLength());
request.setReplyBuffer(dummyReplyBuffer.position(0).array());
request.endRequest(Request.Operations.CREATE_ACCOUNTS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
request.waitForResult();
assert false;
}
@Test
public void testCreateAccountEndRequest() {
var client = getDummyClient();
var batch = new AccountBatch(2);
batch.add();
batch.add();
var request = BlockingRequest.createAccounts(client, batch);
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer = ByteBuffer.allocate(CreateAccountResultBatch.Struct.SIZE * 2)
.order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putInt(0);
dummyReplyBuffer.putInt(CreateAccountResult.IdMustNotBeZero.value);
dummyReplyBuffer.putInt(1);
dummyReplyBuffer.putInt(CreateAccountResult.Exists.value);
request.setReplyBuffer(dummyReplyBuffer.position(0).array());
request.endRequest(Request.Operations.CREATE_ACCOUNTS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
var result = request.waitForResult();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(0, result.getIndex());
assertEquals(CreateAccountResult.IdMustNotBeZero, result.getResult());
assertTrue(result.next());
assertEquals(1, result.getIndex());
assertEquals(CreateAccountResult.Exists, result.getResult());
}
@Test
public void testCreateTransferEndRequest() {
var client = getDummyClient();
var batch = new TransferBatch(2);
batch.add();
batch.add();
var request = BlockingRequest.createTransfers(client, batch);
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer = ByteBuffer.allocate(CreateTransferResultBatch.Struct.SIZE * 2)
.order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putInt(0);
dummyReplyBuffer.putInt(CreateTransferResult.IdMustNotBeZero.value);
dummyReplyBuffer.putInt(1);
dummyReplyBuffer.putInt(CreateTransferResult.Exists.value);
request.setReplyBuffer(dummyReplyBuffer.position(0).array());
request.endRequest(Request.Operations.CREATE_TRANSFERS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
var result = request.waitForResult();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(0, result.getIndex());
assertEquals(CreateTransferResult.IdMustNotBeZero, result.getResult());
assertTrue(result.next());
assertEquals(1, result.getIndex());
assertEquals(CreateTransferResult.Exists, result.getResult());
}
@Test
public void testLookupAccountEndRequest() {
var client = getDummyClient();
var batch = new IdBatch(2);
batch.add();
batch.add();
var request = BlockingRequest.lookupAccounts(client, batch);
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer =
ByteBuffer.allocate(AccountBatch.Struct.SIZE * 2).order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putLong(100).putLong(1000);
dummyReplyBuffer.position(AccountBatch.Struct.SIZE).putLong(200).putLong(2000);
request.setReplyBuffer(dummyReplyBuffer.position(0).array());
request.endRequest(Request.Operations.LOOKUP_ACCOUNTS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
var result = request.waitForResult();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(100L, result.getId(UInt128.LeastSignificant));
assertEquals(1000L, result.getId(UInt128.MostSignificant));
assertTrue(result.next());
assertEquals(200L, result.getId(UInt128.LeastSignificant));
assertEquals(2000L, result.getId(UInt128.MostSignificant));
}
@Test
public void testLookupTransferEndRequest() {
var client = getDummyClient();
var batch = new IdBatch(2);
batch.add();
batch.add();
var request = BlockingRequest.lookupTransfers(client, batch);
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer =
ByteBuffer.allocate(TransferBatch.Struct.SIZE * 2).order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putLong(100).putLong(1000);
dummyReplyBuffer.position(TransferBatch.Struct.SIZE).putLong(200).putLong(2000);
request.setReplyBuffer(dummyReplyBuffer.position(0).array());
request.endRequest(Request.Operations.LOOKUP_TRANSFERS.value, PacketStatus.Ok.value);
assertTrue(request.isDone());
var result = request.waitForResult();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(100L, result.getId(UInt128.LeastSignificant));
assertEquals(1000L, result.getId(UInt128.MostSignificant));
assertTrue(result.next());
assertEquals(200L, result.getId(UInt128.LeastSignificant));
assertEquals(2000L, result.getId(UInt128.MostSignificant));
}
@Test
public void testSuccessCompletion() {
var client = getDummyClient();
var batch = new IdBatch(2);
batch.add();
batch.add();
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer =
ByteBuffer.allocate(TransferBatch.Struct.SIZE * 2).order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putLong(100).putLong(1000);
dummyReplyBuffer.position(TransferBatch.Struct.SIZE).putLong(200).putLong(2000);
var callback =
new CallbackSimulator<TransferBatch>(BlockingRequest.lookupTransfers(client, batch),
Request.Operations.LOOKUP_TRANSFERS.value, dummyReplyBuffer,
PacketStatus.Ok.value, 500);
callback.start();
// Wait for completion
var result = callback.request.waitForResult();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(100L, result.getId(UInt128.LeastSignificant));
assertEquals(1000L, result.getId(UInt128.MostSignificant));
assertTrue(result.next());
assertEquals(200L, result.getId(UInt128.LeastSignificant));
assertEquals(2000L, result.getId(UInt128.MostSignificant));
}
@Test
public void testFailedCompletion() throws InterruptedException {
var client = getDummyClient();
var batch = new IdBatch(1);
batch.add();
var callback =
new CallbackSimulator<TransferBatch>(BlockingRequest.lookupTransfers(client, batch),
Request.Operations.LOOKUP_TRANSFERS.value, null,
PacketStatus.TooMuchData.value, 250);
callback.start();
try {
callback.request.waitForResult();
assert false;
} catch (RequestException requestException) {
assertEquals(PacketStatus.TooMuchData.value, requestException.getStatus());
}
}
private static NativeClient getDummyClient() {
return NativeClient.initEcho(UInt128.asBytes(0), "3000");
}
private class CallbackSimulator<T extends Batch> extends Thread {
public final BlockingRequest<T> request;
private final byte receivedOperation;
private final ByteBuffer buffer;
private final byte status;
private final int delay;
private CallbackSimulator(BlockingRequest<T> request, byte receivedOperation,
ByteBuffer buffer, byte status, int delay) {
this.request = request;
this.receivedOperation = receivedOperation;
this.buffer = buffer;
this.status = status;
this.delay = delay;
}
@Override
public synchronized void run() {
try {
Thread.sleep(delay);
if (buffer != null) {
request.setReplyBuffer(buffer.array());
}
request.endRequest(receivedOperation, status);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/AccountFlagsTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AccountFlagsTest {
@Test
public void testFlags() {
assertTrue(AccountFlags.hasLinked(AccountFlags.LINKED));
assertTrue(AccountFlags
.hasLinked(AccountFlags.LINKED | AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS));
assertTrue(AccountFlags
.hasLinked(AccountFlags.LINKED | AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS));
assertTrue(AccountFlags
.hasDebitsMustNotExceedCredits(AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS));
assertTrue(AccountFlags.hasDebitsMustNotExceedCredits(
AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS | AccountFlags.LINKED));
assertTrue(AccountFlags
.hasDebitsMustNotExceedCredits(AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS
| AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS));
assertTrue(AccountFlags
.hasCreditsMustNotExceedDebits(AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS));
assertTrue(AccountFlags.hasCreditsMustNotExceedDebits(
AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS | AccountFlags.LINKED));
assertTrue(AccountFlags
.hasCreditsMustNotExceedDebits(AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS
| AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS));
assertFalse(AccountFlags.hasLinked(AccountFlags.NONE));
assertFalse(AccountFlags.hasLinked(AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS));
assertFalse(AccountFlags.hasLinked(AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS
| AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS));
assertFalse(AccountFlags.hasDebitsMustNotExceedCredits(AccountFlags.NONE));
assertFalse(AccountFlags.hasDebitsMustNotExceedCredits(AccountFlags.LINKED));
assertFalse(AccountFlags.hasDebitsMustNotExceedCredits(
AccountFlags.LINKED | AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS));
assertFalse(AccountFlags.hasCreditsMustNotExceedDebits(AccountFlags.NONE));
assertFalse(AccountFlags.hasCreditsMustNotExceedDebits(AccountFlags.LINKED));
assertFalse(AccountFlags.hasCreditsMustNotExceedDebits(
AccountFlags.LINKED | AccountFlags.DEBITS_MUST_NOT_EXCEED_CREDITS));
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/BatchTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.math.BigInteger;
import org.junit.Test;
/**
* Asserts the memory interpretation from/to a binary stream.
*/
public class BatchTest {
private static final DummyAccountDto account1;
private static final DummyAccountDto account2;
private static final ByteBuffer dummyAccountsStream;
private static final DummyTransferDto transfer1;
private static final DummyTransferDto transfer2;
private static final ByteBuffer dummyTransfersStream;
private static final CreateAccountResult createAccountResult1;
private static final CreateAccountResult createAccountResult2;
private static final ByteBuffer dummyCreateAccountResultsStream;
private static final CreateTransferResult createTransferResult1;
private static final CreateTransferResult createTransferResult2;
private static final ByteBuffer dummyCreateTransfersResultsStream;
private static final byte[] id1;
private static final long id1LeastSignificant;
private static final long id1MostSignificant;
private static final byte[] id2;
private static final long id2LeastSignificant;
private static final long id2MostSignificant;
private static final ByteBuffer dummyIdsStream;
@Test(expected = IllegalArgumentException.class)
public void testConstructorWithNegativeCapacity() {
new AccountBatch(-1);
}
@Test(expected = NullPointerException.class)
public void testConstructorWithNullBuffer() {
ByteBuffer buffer = null;
new TransferBatch(buffer);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testPositionIndexOutOfBounds() {
var batch = new AccountBatch(1);
batch.setPosition(1);
assert false; // Should be unreachable
}
@Test(expected = IndexOutOfBoundsException.class)
public void testPositionIndexNegative() {
var batch = new CreateTransferResultBatch(1);
batch.setPosition(-1);
assert false; // Should be unreachable
}
@Test
public void testNextFromCapacity() {
var batch = new AccountBatch(2);
// Creating from capacity
// Expected position = -1 and length = 0
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
assertEquals(0 * AccountBatch.Struct.SIZE, batch.getBufferLen());
assertFalse(batch.isValidPosition());
// Zero elements, next must return false
assertFalse(batch.next());
assertFalse(batch.isValidPosition());
// Calling next multiple times on an EMPTY batch is allowed since the cursor does not move.
// This allows reusing a single instance of an empty batch,
// avoiding allocations for the common case (empty batch == success).
batch.next();
batch.next();
assertFalse(batch.isValidPosition());
// Adding 2 elements
batch.add();
assertTrue(batch.isValidPosition());
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
assertEquals(1 * AccountBatch.Struct.SIZE, batch.getBufferLen());
batch.add();
assertTrue(batch.isValidPosition());
assertEquals(1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2 * AccountBatch.Struct.SIZE, batch.getBufferLen());
// reset to the beginning,
// Expected position -1
batch.beforeFirst();
assertFalse(batch.isValidPosition());
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
// Moving
assertTrue(batch.next());
assertTrue(batch.isValidPosition());
assertEquals(0, batch.getPosition());
assertTrue(batch.next());
assertEquals(1, batch.getPosition());
// End of the batch
assertFalse(batch.next());
assertFalse(batch.isValidPosition());
// Calling next multiple times must throw an exception, preventing the user to assume that
// an iterated batch is an empty one.
try {
batch.next();
assert false;
} catch (IndexOutOfBoundsException exception) {
assert true;
}
assertFalse(batch.isValidPosition());
}
@Test
public void testNextFromBuffer() {
var batch = new AccountBatch(dummyAccountsStream.position(0));
// Creating from a existing buffer
// Expected position = -1 and length = 2
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertEquals(dummyAccountsStream.capacity(), batch.getBufferLen());
assertFalse(batch.isValidPosition());
// Moving
assertTrue(batch.next());
assertTrue(batch.isValidPosition());
assertEquals(0, batch.getPosition());
assertTrue(batch.next());
assertTrue(batch.isValidPosition());
assertEquals(1, batch.getPosition());
// End of the batch
assertFalse(batch.next());
assertFalse(batch.isValidPosition());
// Calling next multiple times must throw an exception, preventing the user to assume that
// an iterated batch is an empty one.
try {
batch.next();
assert false;
} catch (IndexOutOfBoundsException exception) {
assert true;
}
assertFalse(batch.isValidPosition());
}
@Test
public void testNextEmptyBatch() {
var batch = TransferBatch.EMPTY;
// Empty batch
// Expected position = -1 and length = 0
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(0, batch.getCapacity());
assertEquals(0, batch.getBufferLen());
assertFalse(batch.isValidPosition());
// Before the first element
assertFalse(batch.next());
assertFalse(batch.isValidPosition());
// Resting an empty batch
batch.beforeFirst();
// Still, before the first element
assertFalse(batch.next());
assertFalse(batch.isValidPosition());
// Calling next multiple times on an EMPTY batch is allowed since the cursor does not move.
// This allows reusing a single instance of an empty batch,
// avoiding allocations for the common case (empty batch == success).
batch.next();
batch.next();
assertFalse(batch.isValidPosition());
}
@Test
public void testAdd() {
var batch = new AccountBatch(2);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
assertEquals(0 * AccountBatch.Struct.SIZE, batch.getBufferLen());
batch.add();
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
assertEquals(2, batch.getCapacity());
assertEquals(1 * AccountBatch.Struct.SIZE, batch.getBufferLen());
batch.add();
assertEquals(1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertEquals(2 * AccountBatch.Struct.SIZE, batch.getBufferLen());
}
@Test(expected = IllegalStateException.class)
public void testAddReadOnly() {
var batch = new AccountBatch(dummyAccountsStream.asReadOnlyBuffer().position(0));
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertEquals(2 * AccountBatch.Struct.SIZE, batch.getBufferLen());
batch.add();
}
@Test(expected = IllegalStateException.class)
public void testReadInvalidPosition() {
AccountBatch batch = new AccountBatch(dummyAccountsStream.position(0));
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertFalse(batch.isValidPosition());
batch.getLedger();
}
@Test(expected = IllegalStateException.class)
public void testWriteInvalidPosition() {
AccountBatch batch = new AccountBatch(2);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
assertFalse(batch.isValidPosition());
batch.setCode(100);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testAddExceedCapacity() {
var batch = new AccountBatch(1);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(1, batch.getCapacity());
assertEquals(0 * AccountBatch.Struct.SIZE, batch.getBufferLen());
batch.add();
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
assertEquals(1 * AccountBatch.Struct.SIZE, batch.getBufferLen());
batch.add();
}
@Test
public void testReadAccounts() {
AccountBatch batch = new AccountBatch(dummyAccountsStream.position(0));
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertTrue(batch.next());
assertAccounts(account1, batch);
assertTrue(batch.next());
assertAccounts(account2, batch);
assertFalse(batch.next());
}
@Test
public void testWriteAccounts() {
AccountBatch batch = new AccountBatch(2);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
batch.add();
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
setAccount(batch, account1);
batch.add();
assertEquals(1, batch.getPosition());
assertEquals(2, batch.getLength());
setAccount(batch, account2);
batch.beforeFirst();
assertTrue(batch.next());
assertAccounts(account1, batch);
assertTrue(batch.next());
assertAccounts(account2, batch);
assertFalse(batch.next());
assertBuffer(dummyAccountsStream, batch.getBuffer());
}
@Test
public void testMoveAndSetAccounts() {
AccountBatch batch = new AccountBatch(2);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
// Set index 0
batch.add();
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
assertEquals(2, batch.getCapacity());
setAccount(batch, account1);
assertAccounts(account1, batch);
// Set index 1 with account1 again
batch.add();
assertEquals(1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
setAccount(batch, account1);
assertAccounts(account1, batch);
// Replace index 0 with account 2
batch.setPosition(0);
assertEquals(0, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
setAccount(batch, account2);
batch.beforeFirst();
assertTrue(batch.next());
assertAccounts(account2, batch);
assertTrue(batch.next());
assertAccounts(account1, batch);
assertFalse(batch.next());
}
@Test(expected = AssertionError.class)
public void testInvalidAccountBuffer() {
// Invalid size
var invalidBuffer = ByteBuffer.allocate((AccountBatch.Struct.SIZE * 2) - 1)
.order(ByteOrder.LITTLE_ENDIAN);
@SuppressWarnings("unused")
var batch = new AccountBatch(invalidBuffer);
assert false;
}
@Test
public void testReadTransfers() {
var batch = new TransferBatch(dummyTransfersStream.position(0));
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertTrue(batch.next());
assertTransfers(transfer1, batch);
assertTrue(batch.next());
assertTransfers(transfer2, batch);
assertFalse(batch.next());
}
@Test
public void testWriteTransfers() {
var batch = new TransferBatch(2);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
batch.add();
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
setTransfer(batch, transfer1);
batch.add();
assertEquals(1, batch.getPosition());
assertEquals(2, batch.getLength());
setTransfer(batch, transfer2);
batch.beforeFirst();
assertTrue(batch.next());
assertTransfers(transfer1, batch);
assertTrue(batch.next());
assertTransfers(transfer2, batch);
assertFalse(batch.next());
assertBuffer(dummyTransfersStream, batch.getBuffer());
}
@Test
public void testMoveAndSetTransfers() {
var batch = new TransferBatch(2);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
// Set index 0
batch.add();
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
assertEquals(2, batch.getCapacity());
setTransfer(batch, transfer1);
assertTransfers(transfer1, batch);
// Set index 1 with transfer1 again
batch.add();
assertEquals(1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
setTransfer(batch, transfer1);
assertTransfers(transfer1, batch);
// Replace index 0 with account 2
batch.setPosition(0);
assertEquals(0, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
setTransfer(batch, transfer2);
batch.beforeFirst();
assertTrue(batch.next());
assertTransfers(transfer2, batch);
assertTrue(batch.next());
assertTransfers(transfer1, batch);
assertFalse(batch.next());
}
@Test(expected = AssertionError.class)
public void testInvalidTransfersBuffer() {
// Invalid size
var invalidBuffer = ByteBuffer.allocate((TransferBatch.Struct.SIZE * 2) - 1)
.order(ByteOrder.LITTLE_ENDIAN);
@SuppressWarnings("unused")
var batch = new TransferBatch(invalidBuffer);
assert false;
}
@Test
public void testReadCreateAccountResults() {
var batch = new CreateAccountResultBatch(dummyCreateAccountResultsStream.position(0));
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertTrue(batch.next());
assertEquals(0, batch.getIndex());
assertEquals(createAccountResult1, batch.getResult());
assertTrue(batch.next());
assertEquals(1, batch.getIndex());
assertEquals(createAccountResult2, batch.getResult());
assertFalse(batch.next());
}
@Test
public void testWriteCreateAccountResults() {
var batch = new CreateAccountResultBatch(1);
batch.add();
batch.setIndex(1);
assertEquals(1, batch.getIndex());
batch.setResult(createAccountResult1);
assertEquals(createAccountResult1, batch.getResult());
}
@Test(expected = AssertionError.class)
public void testInvalidCreateAccountResultsBuffer() {
// Invalid size
var invalidBuffer = ByteBuffer.allocate((CreateAccountResultBatch.Struct.SIZE * 2) - 1)
.order(ByteOrder.LITTLE_ENDIAN);
@SuppressWarnings("unused")
var batch = new CreateAccountResultBatch(invalidBuffer);
assert false;
}
@Test
public void testReadCreateTransferResults() {
var batch = new CreateTransferResultBatch(dummyCreateTransfersResultsStream.position(0));
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertTrue(batch.next());
assertEquals(0, batch.getIndex());
assertEquals(createTransferResult1, batch.getResult());
assertTrue(batch.next());
assertEquals(1, batch.getIndex());
assertEquals(createTransferResult2, batch.getResult());
assertFalse(batch.next());
}
@Test
public void testWriteCreateTransferResults() {
var batch = new CreateTransferResultBatch(1);
batch.add();
batch.setIndex(1);
assertEquals(1, batch.getIndex());
batch.setResult(createTransferResult1);
assertEquals(createTransferResult1, batch.getResult());
}
@Test(expected = AssertionError.class)
public void testInvalidTransferAccountResultsBuffer() {
// Invalid size
var invalidBuffer = ByteBuffer.allocate((CreateTransferResultBatch.Struct.SIZE * 2) - 1)
.order(ByteOrder.LITTLE_ENDIAN);
@SuppressWarnings("unused")
var batch = new CreateTransferResultBatch(invalidBuffer);
assert false;
}
@Test
public void testReadIds() {
var batch = new IdBatch(dummyIdsStream.position(0));
assertEquals(-1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertTrue(batch.next());
assertEquals(id1LeastSignificant, batch.getId(UInt128.LeastSignificant));
assertEquals(id1MostSignificant, batch.getId(UInt128.MostSignificant));
assertArrayEquals(id1, batch.getId());
assertTrue(batch.next());
assertEquals(id2LeastSignificant, batch.getId(UInt128.LeastSignificant));
assertEquals(id2MostSignificant, batch.getId(UInt128.MostSignificant));
assertArrayEquals(id2, batch.getId());
assertFalse(batch.next());
}
@Test
public void testWriteIds() {
var batch = new IdBatch(2);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
batch.add(id1LeastSignificant, id1MostSignificant);
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
batch.add(id2LeastSignificant, id2MostSignificant);
assertEquals(1, batch.getPosition());
assertEquals(2, batch.getLength());
batch.beforeFirst();
assertTrue(batch.next());
assertEquals(id1LeastSignificant, batch.getId(UInt128.LeastSignificant));
assertEquals(id1MostSignificant, batch.getId(UInt128.MostSignificant));
assertArrayEquals(id1, batch.getId());
assertTrue(batch.next());
assertEquals(id2LeastSignificant, batch.getId(UInt128.LeastSignificant));
assertEquals(id2MostSignificant, batch.getId(UInt128.MostSignificant));
assertArrayEquals(id2, batch.getId());
assertFalse(batch.next());
assertBuffer(dummyIdsStream, batch.getBuffer());
}
@Test
public void testMoveAndSetIds() {
var batch = new IdBatch(2);
assertEquals(-1, batch.getPosition());
assertEquals(0, batch.getLength());
assertEquals(2, batch.getCapacity());
// Set index 0
batch.add(id1);
assertEquals(0, batch.getPosition());
assertEquals(1, batch.getLength());
assertEquals(2, batch.getCapacity());
assertEquals(id1LeastSignificant, batch.getId(UInt128.LeastSignificant));
assertEquals(id1MostSignificant, batch.getId(UInt128.MostSignificant));
assertArrayEquals(id1, batch.getId());
// Set index 1 with id1 again
batch.add(id1);
assertEquals(1, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
assertEquals(id1LeastSignificant, batch.getId(UInt128.LeastSignificant));
assertEquals(id1MostSignificant, batch.getId(UInt128.MostSignificant));
assertArrayEquals(id1, batch.getId());
// Replace index 0 with id2
batch.setPosition(0);
assertEquals(0, batch.getPosition());
assertEquals(2, batch.getLength());
assertEquals(2, batch.getCapacity());
batch.setId(id2);
batch.beforeFirst();
assertTrue(batch.next());
assertArrayEquals(id2, batch.getId());
assertTrue(batch.next());
assertArrayEquals(id1, batch.getId());
assertFalse(batch.next());
}
@Test(expected = AssertionError.class)
public void testInvalidIdsBuffer() {
// Invalid size
var invalidBuffer =
ByteBuffer.allocate((UInt128.SIZE * 2) - 1).order(ByteOrder.LITTLE_ENDIAN);
@SuppressWarnings("unused")
var batch = new IdBatch(invalidBuffer);
assert false;
}
@Test(expected = NullPointerException.class)
public void testNullIds() {
var batch = new IdBatch(1);
batch.add();
batch.setId(null);
assert false;
}
@Test
public void testLongIds() {
var batch = new IdBatch(1);
batch.add(100L);
assertEquals(100L, batch.getId(UInt128.LeastSignificant));
assertEquals(0L, batch.getId(UInt128.MostSignificant));
}
private static void setAccount(AccountBatch batch, DummyAccountDto account) {
batch.setId(account.idLeastSignificant, account.idMostSignificant);
batch.setDebitsPending(account.debitsPending);
batch.setDebitsPosted(account.debitsPosted);
batch.setCreditsPending(account.creditsPending);
batch.setCreditsPosted(account.creditsPosted);
batch.setUserData128(account.userData128LeastSignificant,
account.userData128MostSignificant);
batch.setUserData64(account.userData64);
batch.setUserData32(account.userData32);
batch.setLedger(account.ledger);
batch.setCode(account.code);
batch.setFlags(account.flags);
batch.setTimestamp(account.timestamp);
}
private static void assertAccounts(DummyAccountDto account, AccountBatch batch) {
assertEquals(account.idLeastSignificant, batch.getId(UInt128.LeastSignificant));
assertEquals(account.idMostSignificant, batch.getId(UInt128.MostSignificant));
assertEquals(account.debitsPending, batch.getDebitsPending());
assertEquals(account.debitsPosted, batch.getDebitsPosted());
assertEquals(account.creditsPending, batch.getCreditsPending());
assertEquals(account.creditsPosted, batch.getCreditsPosted());
assertEquals(account.userData128LeastSignificant,
batch.getUserData128(UInt128.LeastSignificant));
assertEquals(account.userData128MostSignificant,
batch.getUserData128(UInt128.MostSignificant));
assertEquals(account.userData64, batch.getUserData64());
assertEquals(account.userData32, batch.getUserData32());
assertEquals(account.ledger, batch.getLedger());
assertEquals(account.code, (short) batch.getCode());
assertEquals(account.flags, (short) batch.getFlags());
assertEquals(account.timestamp, batch.getTimestamp());
}
private static void assertTransfers(DummyTransferDto transfer, TransferBatch batch) {
assertEquals(transfer.idLeastSignificant, batch.getId(UInt128.LeastSignificant));
assertEquals(transfer.idMostSignificant, batch.getId(UInt128.MostSignificant));
assertEquals(transfer.creditAccountIdLeastSignificant,
batch.getCreditAccountId(UInt128.LeastSignificant));
assertEquals(transfer.creditAccountIdMostSignificant,
batch.getCreditAccountId(UInt128.MostSignificant));
assertEquals(transfer.debitAccountIdLeastSignificant,
batch.getDebitAccountId(UInt128.LeastSignificant));
assertEquals(transfer.debitAccountIdMostSignificant,
batch.getDebitAccountId(UInt128.MostSignificant));
assertEquals(transfer.amount, batch.getAmount());
assertEquals(transfer.pendingIdLeastSignificant,
batch.getPendingId(UInt128.LeastSignificant));
assertEquals(transfer.pendingIdMostSignificant,
batch.getPendingId(UInt128.MostSignificant));
assertEquals(transfer.userData128LeastSignificant,
batch.getUserData128(UInt128.LeastSignificant));
assertEquals(transfer.userData128MostSignificant,
batch.getUserData128(UInt128.MostSignificant));
assertEquals(transfer.userData64, batch.getUserData64());
assertEquals(transfer.userData32, batch.getUserData32());
assertEquals(transfer.ledger, batch.getLedger());
assertEquals(transfer.code, (short) batch.getCode());
assertEquals(transfer.flags, (short) batch.getFlags());
assertEquals(transfer.timeout, batch.getTimeout());
assertEquals(transfer.timestamp, batch.getTimestamp());
}
private static void setTransfer(TransferBatch batch, DummyTransferDto transfer) {
batch.setId(transfer.idLeastSignificant, transfer.idMostSignificant);
batch.setDebitAccountId(transfer.debitAccountIdLeastSignificant,
transfer.debitAccountIdMostSignificant);
batch.setCreditAccountId(transfer.creditAccountIdLeastSignificant,
transfer.creditAccountIdMostSignificant);
batch.setAmount(transfer.amount);
batch.setPendingId(transfer.pendingIdLeastSignificant, transfer.pendingIdMostSignificant);
batch.setUserData128(transfer.userData128LeastSignificant,
transfer.userData128MostSignificant);
batch.setUserData64(transfer.userData64);
batch.setUserData32(transfer.userData32);
batch.setLedger(transfer.ledger);
batch.setCode(transfer.code);
batch.setFlags(transfer.flags);
batch.setTimeout(transfer.timeout);
batch.setTimestamp(transfer.timestamp);
}
private void assertBuffer(ByteBuffer expected, ByteBuffer actual) {
assertEquals(expected.capacity(), actual.capacity());
for (int i = 0; i < expected.capacity(); i++) {
assertEquals(expected.get(i), actual.get(i));
}
}
private static final class DummyAccountDto {
public long idLeastSignificant;
public long idMostSignificant;
public BigInteger creditsPosted;
public BigInteger creditsPending;
public BigInteger debitsPosted;
public BigInteger debitsPending;
public long userData128LeastSignificant;
public long userData128MostSignificant;
public long userData64;
public int userData32;
public int ledger;
public short code;
public short flags;
public long timestamp;
}
private static final class DummyTransferDto {
private long idLeastSignificant;
private long idMostSignificant;
private long debitAccountIdLeastSignificant;
private long debitAccountIdMostSignificant;
private long creditAccountIdLeastSignificant;
private long creditAccountIdMostSignificant;
private BigInteger amount;
private long pendingIdLeastSignificant;
private long pendingIdMostSignificant;
private long userData128LeastSignificant;
private long userData128MostSignificant;
private long userData64;
private int userData32;
private int timeout;
private int ledger;
private short code;
private short flags;
private long timestamp;
}
static {
account1 = new DummyAccountDto();
account1.idLeastSignificant = 10;
account1.idMostSignificant = 100;
account1.debitsPending = BigInteger.valueOf(100);
account1.debitsPosted = BigInteger.valueOf(200);
account1.creditsPending = BigInteger.valueOf(300);
account1.creditsPosted = BigInteger.valueOf(400);
account1.userData128LeastSignificant = 1000;
account1.userData128MostSignificant = 1100;
account1.userData64 = 2000;
account1.userData32 = 3000;
account1.ledger = 720;
account1.code = 1;
account1.flags = AccountFlags.LINKED;
account1.timestamp = 999;
account2 = new DummyAccountDto();
account2.idLeastSignificant = 20;
account2.idMostSignificant = 200;
account2.debitsPending = BigInteger.valueOf(10);
account2.debitsPosted = BigInteger.valueOf(20);
account2.creditsPending = BigInteger.valueOf(30);
account2.creditsPosted = BigInteger.valueOf(40);
account2.userData128LeastSignificant = 2000;
account2.userData128MostSignificant = 2200;
account2.userData64 = 4000;
account2.userData32 = 5000;
account2.ledger = 730;
account2.code = 2;
account2.flags = AccountFlags.LINKED | AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS;
account2.timestamp = 99;
// Mimic the binary response
dummyAccountsStream = ByteBuffer.allocate(256).order(ByteOrder.LITTLE_ENDIAN);
// Item 1
dummyAccountsStream.putLong(10).putLong(100); // Id
dummyAccountsStream.putLong(100).putLong(0); // DebitsPending
dummyAccountsStream.putLong(200).putLong(0); // DebitsPosted
dummyAccountsStream.putLong(300).putLong(0); // CreditPending
dummyAccountsStream.putLong(400).putLong(0); // CreditsPosted
dummyAccountsStream.putLong(1000).putLong(1100); // UserData128
dummyAccountsStream.putLong(2000); // UserData64
dummyAccountsStream.putInt(3000); // UserData32
dummyAccountsStream.putInt(0); // Reserved
dummyAccountsStream.putInt(720); // Ledger
dummyAccountsStream.putShort((short) 1); // Code
dummyAccountsStream.putShort((short) 1); // Flags
dummyAccountsStream.putLong(999); // Timestamp
// Item 2
dummyAccountsStream.putLong(20).putLong(200); // Id
dummyAccountsStream.putLong(10).putLong(0); // DebitsPending
dummyAccountsStream.putLong(20).putLong(0);; // DebitsPosted
dummyAccountsStream.putLong(30).putLong(0);; // CreditPending
dummyAccountsStream.putLong(40).putLong(0);; // CreditsPosted
dummyAccountsStream.putLong(2000).putLong(2200); // UserData128
dummyAccountsStream.putLong(4000); // UserData64
dummyAccountsStream.putInt(5000); // UserData32
dummyAccountsStream.putInt(0); // Reserved
dummyAccountsStream.putInt(730); // Ledger
dummyAccountsStream.putShort((short) 2); // Code
dummyAccountsStream.putShort((short) 5); // Flags
dummyAccountsStream.putLong(99); // Timestamp
transfer1 = new DummyTransferDto();
transfer1.idLeastSignificant = 5000;
transfer1.idMostSignificant = 500;
transfer1.debitAccountIdLeastSignificant = 1000;
transfer1.debitAccountIdMostSignificant = 100;
transfer1.creditAccountIdLeastSignificant = 2000;
transfer1.creditAccountIdMostSignificant = 200;
transfer1.amount = BigInteger.valueOf(1000);
transfer1.userData128LeastSignificant = 3000;
transfer1.userData128MostSignificant = 300;
transfer1.userData64 = 6000;
transfer1.userData32 = 7000;
transfer1.code = 10;
transfer1.ledger = 720;
transfer2 = new DummyTransferDto();
transfer2.idLeastSignificant = 5001;
transfer2.idMostSignificant = 501;
transfer2.debitAccountIdLeastSignificant = 1001;
transfer2.debitAccountIdMostSignificant = 101;
transfer2.creditAccountIdLeastSignificant = 2001;
transfer2.creditAccountIdMostSignificant = 201;
transfer2.amount = BigInteger.valueOf(200);
transfer2.pendingIdLeastSignificant = transfer1.idLeastSignificant;
transfer2.pendingIdMostSignificant = transfer1.idMostSignificant;
transfer2.userData128LeastSignificant = 3001;
transfer2.userData128MostSignificant = 301;
transfer2.userData64 = 8000;
transfer2.userData32 = 9000;
transfer2.timeout = 2500;
transfer2.code = 20;
transfer2.ledger = 100;
transfer2.flags = TransferFlags.PENDING | TransferFlags.LINKED;
transfer2.timestamp = 900;
// Mimic the binary response
dummyTransfersStream = ByteBuffer.allocate(256).order(ByteOrder.LITTLE_ENDIAN);
// Item 1
dummyTransfersStream.putLong(5000).putLong(500); // Id
dummyTransfersStream.putLong(1000).putLong(100); // CreditAccountId
dummyTransfersStream.putLong(2000).putLong(200); // DebitAccountId
dummyTransfersStream.putLong(1000).putLong(0); // Amount
dummyTransfersStream.putLong(0).putLong(0); // PendingId
dummyTransfersStream.putLong(3000).putLong(300); // UserData128
dummyTransfersStream.putLong(6000); // UserData64
dummyTransfersStream.putInt(7000); // UserData32
dummyTransfersStream.putInt(0); // Timeout
dummyTransfersStream.putInt(720); // Ledger
dummyTransfersStream.putShort((short) 10); // Code
dummyTransfersStream.putShort((short) 0); // Flags
dummyTransfersStream.putLong(0); // Timestamp
// Item 2
dummyTransfersStream.putLong(5001).putLong(501); // Id
dummyTransfersStream.putLong(1001).putLong(101); // CreditAccountId
dummyTransfersStream.putLong(2001).putLong(201); // DebitAccountId
dummyTransfersStream.putLong(200).putLong(0); // Amount
dummyTransfersStream.putLong(5000).putLong(500); // PendingId
dummyTransfersStream.putLong(3001).putLong(301); // UserData128
dummyTransfersStream.putLong(8000); // UserData64
dummyTransfersStream.putInt(9000); // UserData32
dummyTransfersStream.putInt(2500); // Timeout
dummyTransfersStream.putInt(100); // Ledger
dummyTransfersStream.putShort((short) 20); // Code
dummyTransfersStream.putShort((short) 3); // Flags
dummyTransfersStream.putLong(900); // Timestamp
createAccountResult1 = CreateAccountResult.Ok;
createAccountResult2 = CreateAccountResult.Exists;
// Mimic the binary response
dummyCreateAccountResultsStream = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN);
dummyCreateAccountResultsStream.putInt(0).putInt(0); // Item 0 - OK
dummyCreateAccountResultsStream.putInt(1).putInt(CreateAccountResult.Exists.value); // Item
// 1 -
// Exists
createTransferResult1 = CreateTransferResult.Ok;
createTransferResult2 = CreateTransferResult.ExceedsDebits;
// Mimic the binary response
dummyCreateTransfersResultsStream = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN);
dummyCreateTransfersResultsStream.putInt(0).putInt(0); // Item 0 - OK
dummyCreateTransfersResultsStream.putInt(1)
.putInt(CreateTransferResult.ExceedsDebits.value); // Item 1 - ExceedsDebits
id1 = new byte[] {10, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0};
id1LeastSignificant = 10;
id1MostSignificant = 100;
id2 = new byte[] {2, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0};
id2LeastSignificant = 2;
id2MostSignificant = 20;
// Mimic the binary response
dummyIdsStream = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN);
dummyIdsStream.putLong(10).putLong(100); // Item (10,100)
dummyIdsStream.putLong(2).putLong(20); // Item (2,20)
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/AsyncRequestTest.java |
package com.tigerbeetle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import com.tigerbeetle.Request.Operations;
public class AsyncRequestTest {
@Test
public void testCreateAccountsRequestConstructor() {
var client = getDummyClient();
var batch = new AccountBatch(1);
batch.add();
var request = AsyncRequest.createAccounts(client, batch);
assert request != null;
}
@Test
public void testCreateTransfersRequestConstructor() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var request = AsyncRequest.createTransfers(client, batch);
assert request != null;
}
@Test
public void testLookupAccountsRequestConstructor() {
var client = getDummyClient();
var batch = new IdBatch(1);
batch.add();
var request = AsyncRequest.lookupAccounts(client, batch);
assert request != null;
}
@Test
public void testLookupTransfersRequestConstructor() {
var client = getDummyClient();
var batch = new IdBatch(1);
batch.add();
var request = AsyncRequest.lookupTransfers(client, batch);
assert request != null;
}
@Test(expected = NullPointerException.class)
public void testConstructorWithClientNull() {
var batch = new AccountBatch(1);
batch.add();
AsyncRequest.createAccounts(null, batch);
assert false;
}
@Test(expected = NullPointerException.class)
public void testConstructorWithBatchNull() {
var client = getDummyClient();
AsyncRequest.createAccounts(client, null);
assert false;
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorWithZeroCapacityBatch() {
var client = getDummyClient();
var batch = new AccountBatch(0);
AsyncRequest.createAccounts(client, batch);
assert false;
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorWithZeroItemsBatch() {
var client = getDummyClient();
var batch = new AccountBatch(1);
AsyncRequest.createAccounts(client, batch);
assert false;
}
@Test(expected = AssertionError.class)
public void testEndRequestWithInvalidOperation() throws Throwable {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var dummyBuffer = ByteBuffer.allocate(CreateTransferResultBatch.Struct.SIZE);
var callback = new CallbackSimulator<CreateTransferResultBatch>(
AsyncRequest.createTransfers(client, batch),
Request.Operations.LOOKUP_ACCOUNTS.value, dummyBuffer, PacketStatus.Ok.value, 250);
CompletableFuture<CreateTransferResultBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
try {
future.get();
assert false;
} catch (ExecutionException e) {
assertNotNull(e.getCause());
throw e.getCause();
}
}
@Test(expected = AssertionError.class)
public void testEndRequestWithUnknownOperation() throws Throwable {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
final byte UNKNOWN = 99;
var dummyBuffer = ByteBuffer.allocate(CreateTransferResultBatch.Struct.SIZE);
var callback =
new CallbackSimulator<CreateTransferResultBatch>(
new AsyncRequest<CreateTransferResultBatch>(client,
Operations.CREATE_TRANSFERS, batch),
UNKNOWN, dummyBuffer, PacketStatus.Ok.value, 250);
CompletableFuture<CreateTransferResultBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
try {
future.get();
assert false;
} catch (ExecutionException e) {
assertNotNull(e.getCause());
throw e.getCause();
}
}
@Test
public void testEndRequestWithNullBuffer() throws Throwable {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var callback = new CallbackSimulator<CreateTransferResultBatch>(
AsyncRequest.createTransfers(client, batch),
Request.Operations.CREATE_TRANSFERS.value, null, PacketStatus.Ok.value, 250);
CompletableFuture<CreateTransferResultBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
var result = future.get();
assertEquals(0, result.getLength());
}
@Test(expected = AssertionError.class)
public void testEndRequestWithInvalidBufferSize() throws Throwable {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var invalidBuffer = ByteBuffer.allocate((CreateTransferResultBatch.Struct.SIZE * 2) - 1);
var callback = new CallbackSimulator<CreateTransferResultBatch>(
AsyncRequest.createTransfers(client, batch),
Request.Operations.CREATE_TRANSFERS.value, invalidBuffer, PacketStatus.Ok.value,
250);
CompletableFuture<CreateTransferResultBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
try {
future.get();
assert false;
} catch (ExecutionException e) {
assertNotNull(e.getCause());
throw e.getCause();
}
}
@Test
public void testEndRequestWithRequestException() {
var client = getDummyClient();
var batch = new TransferBatch(1);
batch.add();
var dummyBuffer = ByteBuffer.allocate(CreateTransferResultBatch.Struct.SIZE);
var callback = new CallbackSimulator<CreateTransferResultBatch>(
AsyncRequest.createTransfers(client, batch),
Request.Operations.CREATE_TRANSFERS.value, dummyBuffer,
PacketStatus.TooMuchData.value, 250);
CompletableFuture<CreateTransferResultBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
try {
future.join();
assert false;
} catch (CompletionException e) {
assertTrue(e.getCause() instanceof RequestException);
var requestException = (RequestException) e.getCause();
assertEquals(PacketStatus.TooMuchData.value, requestException.getStatus());
}
}
@Test(expected = AssertionError.class)
public void testEndRequestWithAmountOfResultsGreaterThanAmountOfRequests() throws Throwable {
var client = getDummyClient();
// A batch with only 1 item
var batch = new AccountBatch(1);
batch.add();
// A reply with 2 items, while the batch had only 1 item
var incorrectReply = ByteBuffer.allocate(CreateAccountResultBatch.Struct.SIZE * 2)
.order(ByteOrder.LITTLE_ENDIAN);
var callback = new CallbackSimulator<CreateAccountResultBatch>(
AsyncRequest.createAccounts(client, batch),
Request.Operations.CREATE_ACCOUNTS.value, incorrectReply, PacketStatus.Ok.value,
250);
CompletableFuture<CreateAccountResultBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
try {
future.get();
assert false;
} catch (ExecutionException e) {
assertNotNull(e.getCause());
throw e.getCause();
}
}
@Test
public void testCreateAccountEndRequest() throws ExecutionException, InterruptedException {
var client = getDummyClient();
var batch = new AccountBatch(2);
batch.add();
batch.add();
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer = ByteBuffer.allocate(CreateAccountResultBatch.Struct.SIZE * 2)
.order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putInt(0);
dummyReplyBuffer.putInt(CreateAccountResult.IdMustNotBeZero.value);
dummyReplyBuffer.putInt(1);
dummyReplyBuffer.putInt(CreateAccountResult.Exists.value);
var callback = new CallbackSimulator<CreateAccountResultBatch>(
AsyncRequest.createAccounts(client, batch),
Request.Operations.CREATE_ACCOUNTS.value, dummyReplyBuffer, PacketStatus.Ok.value,
250);
CompletableFuture<CreateAccountResultBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
var result = future.get();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(0, result.getIndex());
assertEquals(CreateAccountResult.IdMustNotBeZero, result.getResult());
assertTrue(result.next());
assertEquals(1, result.getIndex());
assertEquals(CreateAccountResult.Exists, result.getResult());
}
@Test
public void testCreateTransferEndRequest() throws InterruptedException, ExecutionException {
var client = getDummyClient();
var batch = new TransferBatch(2);
batch.add();
batch.add();
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer = ByteBuffer.allocate(CreateTransferResultBatch.Struct.SIZE * 2)
.order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putInt(0);
dummyReplyBuffer.putInt(CreateTransferResult.IdMustNotBeZero.value);
dummyReplyBuffer.putInt(1);
dummyReplyBuffer.putInt(CreateTransferResult.Exists.value);
var callback = new CallbackSimulator<CreateTransferResultBatch>(
AsyncRequest.createTransfers(client, batch),
Request.Operations.CREATE_TRANSFERS.value, dummyReplyBuffer, PacketStatus.Ok.value,
250);
CompletableFuture<CreateTransferResultBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
var result = future.get();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(0, result.getIndex());
assertEquals(CreateTransferResult.IdMustNotBeZero, result.getResult());
assertTrue(result.next());
assertEquals(1, result.getIndex());
assertEquals(CreateTransferResult.Exists, result.getResult());
}
@Test
public void testLookupAccountEndRequest() throws InterruptedException, ExecutionException {
var client = getDummyClient();
var batch = new IdBatch(2);
batch.add();
batch.add();
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer =
ByteBuffer.allocate(AccountBatch.Struct.SIZE * 2).order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putLong(100).putLong(1000);
dummyReplyBuffer.position(AccountBatch.Struct.SIZE).putLong(200).putLong(2000);
var callback =
new CallbackSimulator<AccountBatch>(AsyncRequest.lookupAccounts(client, batch),
Request.Operations.LOOKUP_ACCOUNTS.value, dummyReplyBuffer,
PacketStatus.Ok.value, 250);
CompletableFuture<AccountBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
var result = future.get();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(100L, result.getId(UInt128.LeastSignificant));
assertEquals(1000L, result.getId(UInt128.MostSignificant));
assertTrue(result.next());
assertEquals(200L, result.getId(UInt128.LeastSignificant));
assertEquals(2000L, result.getId(UInt128.MostSignificant));
}
@Test
public void testLookupTransferEndRequest() throws InterruptedException, ExecutionException {
var client = getDummyClient();
var batch = new IdBatch(2);
batch.add();
batch.add();
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer =
ByteBuffer.allocate(TransferBatch.Struct.SIZE * 2).order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putLong(100).putLong(1000);
dummyReplyBuffer.position(TransferBatch.Struct.SIZE).putLong(200).putLong(2000);
var callback =
new CallbackSimulator<TransferBatch>(AsyncRequest.lookupTransfers(client, batch),
Request.Operations.LOOKUP_TRANSFERS.value, dummyReplyBuffer,
PacketStatus.Ok.value, 250);
CompletableFuture<TransferBatch> future = callback.request.getFuture();
callback.start();
assertFalse(future.isDone());
var result = future.get();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(100L, result.getId(UInt128.LeastSignificant));
assertEquals(1000L, result.getId(UInt128.MostSignificant));
assertTrue(result.next());
assertEquals(200L, result.getId(UInt128.LeastSignificant));
assertEquals(2000L, result.getId(UInt128.MostSignificant));
}
@Test
public void testSuccessFuture() throws InterruptedException, ExecutionException {
var client = getDummyClient();
var batch = new IdBatch(2);
batch.add();
batch.add();
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer =
ByteBuffer.allocate(TransferBatch.Struct.SIZE * 2).order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putLong(100).putLong(1000);
dummyReplyBuffer.position(TransferBatch.Struct.SIZE).putLong(200).putLong(2000);
var callback =
new CallbackSimulator<TransferBatch>(AsyncRequest.lookupTransfers(client, batch),
Request.Operations.LOOKUP_TRANSFERS.value, dummyReplyBuffer,
PacketStatus.Ok.value, 5000);
Future<TransferBatch> future = callback.request.getFuture();
callback.start();
try {
// Our goal is just to test the future timeout.
// The timeout is much smaller than the delay,
// to avoid flaky results due to thread scheduling.
future.get(5, TimeUnit.MILLISECONDS);
assert false;
} catch (TimeoutException timeout) {
assert true;
}
// Wait for completion
var result = future.get();
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(100L, result.getId(UInt128.LeastSignificant));
assertEquals(1000L, result.getId(UInt128.MostSignificant));
assertTrue(result.next());
assertEquals(200L, result.getId(UInt128.LeastSignificant));
assertEquals(2000L, result.getId(UInt128.MostSignificant));
}
@Test
public void testSuccessFutureWithTimeout() throws InterruptedException, ExecutionException {
var client = getDummyClient();
var batch = new IdBatch(2);
batch.add();
batch.add();
// A dummy ByteBuffer simulating some simple reply
var dummyReplyBuffer =
ByteBuffer.allocate(TransferBatch.Struct.SIZE * 2).order(ByteOrder.LITTLE_ENDIAN);
dummyReplyBuffer.putLong(100).putLong(1000);
dummyReplyBuffer.position(TransferBatch.Struct.SIZE).putLong(200).putLong(2000);
var callback =
new CallbackSimulator<TransferBatch>(AsyncRequest.lookupTransfers(client, batch),
Request.Operations.LOOKUP_TRANSFERS.value, dummyReplyBuffer,
PacketStatus.Ok.value, 5);
Future<TransferBatch> future = callback.request.getFuture();
callback.start();
try {
// Our goal is just to test the future completion.
// The timeout is much bigger than the delay,
// to avoid flaky results due to thread scheduling.
var result = future.get(5000, TimeUnit.MILLISECONDS);
assertEquals(2, result.getLength());
assertTrue(result.next());
assertEquals(100L, result.getId(UInt128.LeastSignificant));
assertEquals(1000L, result.getId(UInt128.MostSignificant));
assertTrue(result.next());
assertEquals(200L, result.getId(UInt128.LeastSignificant));
assertEquals(2000L, result.getId(UInt128.MostSignificant));
} catch (TimeoutException timeout) {
assert false;
}
}
@Test
public void testFailedFuture() throws InterruptedException {
var client = getDummyClient();
var batch = new IdBatch(1);
batch.add();
var callback =
new CallbackSimulator<TransferBatch>(AsyncRequest.lookupTransfers(client, batch),
Request.Operations.LOOKUP_TRANSFERS.value, null,
PacketStatus.TooMuchData.value, 250);
Future<TransferBatch> future = callback.request.getFuture();
callback.start();
try {
future.get();
assert false;
} catch (ExecutionException exception) {
assertTrue(exception.getCause() instanceof RequestException);
var requestException = (RequestException) exception.getCause();
assertEquals(PacketStatus.TooMuchData.value, requestException.getStatus());
}
}
@Test
public void testFailedFutureWithTimeout() throws InterruptedException, TimeoutException {
var client = getDummyClient();
var batch = new IdBatch(1);
batch.add();
var callback =
new CallbackSimulator<AccountBatch>(AsyncRequest.lookupAccounts(client, batch),
Request.Operations.LOOKUP_ACCOUNTS.value, null,
PacketStatus.InvalidDataSize.value, 100);
Future<AccountBatch> future = callback.request.getFuture();
callback.start();
try {
future.get(1000, TimeUnit.MILLISECONDS);
assert false;
} catch (ExecutionException exception) {
assertTrue(exception.getCause() instanceof RequestException);
var requestException = (RequestException) exception.getCause();
assertEquals(PacketStatus.InvalidDataSize.value, requestException.getStatus());
}
}
private static NativeClient getDummyClient() {
return NativeClient.initEcho(UInt128.asBytes(0), "3000");
}
private class CallbackSimulator<T extends Batch> extends Thread {
public final AsyncRequest<T> request;
private final byte receivedOperation;
private final ByteBuffer buffer;
private final byte status;
private final int delay;
private CallbackSimulator(AsyncRequest<T> request, byte receivedOperation,
ByteBuffer buffer, byte status, int delay) {
this.request = request;
this.receivedOperation = receivedOperation;
this.buffer = buffer;
this.status = status;
this.delay = delay;
}
@Override
public synchronized void run() {
try {
Thread.sleep(delay);
if (buffer != null) {
request.setReplyBuffer(buffer.array());
}
request.endRequest(receivedOperation, status);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/IntegrationTest.java | package com.tigerbeetle;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
import java.math.BigInteger;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
/**
* Integration tests using a TigerBeetle instance.
*/
public class IntegrationTest {
private static final byte[] clusterId = new byte[16];
private static Server server;
private static Client client;
private static AccountBatch generateAccounts(final byte[]... ids) {
final var accounts = new AccountBatch(ids.length);
for (var id : ids) {
accounts.add();
accounts.setId(id);
accounts.setUserData128(100, 0);
accounts.setUserData64(101);
accounts.setUserData32(102);
accounts.setLedger(720);
accounts.setCode(1);
accounts.setFlags(AccountFlags.NONE);
}
accounts.beforeFirst();
return accounts;
}
@BeforeClass
public static void initialize() throws Exception {
server = new Server();
client = new Client(clusterId, new String[] {server.address});
}
@AfterClass
public static void cleanup() throws Exception {
client.close();
server.close();
}
@Test(expected = NullPointerException.class)
public void testConstructorNullReplicaAddresses() throws Throwable {
try (final var client = new Client(clusterId, null)) {
assert false;
}
}
@Test(expected = NullPointerException.class)
public void testConstructorNullElementReplicaAddresses() throws Throwable {
final var replicaAddresses = new String[] {"3001", null};
try (final var client = new Client(clusterId, replicaAddresses)) {
assert false;
}
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorEmptyReplicaAddresses() throws Throwable {
final var replicaAddresses = new String[0];
try (final var client = new Client(clusterId, replicaAddresses)) {
assert false;
}
}
@Test
public void testConstructorReplicaAddressesLimitExceeded() throws Throwable {
final var replicaAddresses = new String[100];
for (int i = 0; i < replicaAddresses.length; i++) {
replicaAddresses[i] = "3000";
}
try (final var client = new Client(clusterId, replicaAddresses)) {
assert false;
} catch (InitializationException initializationException) {
assertEquals(InitializationStatus.AddressLimitExceeded.value,
initializationException.getStatus());
}
}
@Test
public void testConstructorEmptyStringReplicaAddresses() throws Throwable {
final var replicaAddresses = new String[] {"", "", ""};
try (final var client = new Client(clusterId, replicaAddresses)) {
assert false;
} catch (InitializationException initializationException) {
assertEquals(InitializationStatus.AddressInvalid.value,
initializationException.getStatus());
}
}
@Test
public void testConstructorInvalidReplicaAddresses() throws Throwable {
final var replicaAddresses = new String[] {"127.0.0.1:99999"};
try (final var client = new Client(clusterId, replicaAddresses)) {
assert false;
} catch (InitializationException initializationException) {
assertEquals(InitializationStatus.AddressInvalid.value,
initializationException.getStatus());
}
}
public void testConstructorCluster() throws Throwable {
final var clusterId = UInt128.id();
final var replicaAddresses = new String[] {"3001"};
try (final var client = new Client(clusterId, replicaAddresses)) {
assertArrayEquals(clusterId, client.getClusterID());
}
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorInvalidCluster() throws Throwable {
final var clusterIdInvalid = new byte[] {0, 0, 0};
final var replicaAddresses = new String[] {"3001"};
try (final var client = new Client(clusterIdInvalid, replicaAddresses)) {
assert false;
}
}
@Test
public void testCreateAccounts() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
final var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertEquals(2, lookupAccounts.getLength());
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
}
@Test
public void testCreateInvalidAccount() throws Throwable {
final var zeroedAccounts = new AccountBatch(1);
zeroedAccounts.add();
final var createAccountErrors = client.createAccounts(zeroedAccounts);
assertTrue(createAccountErrors.getLength() == 1);
assertTrue(createAccountErrors.next());
assertEquals(CreateAccountResult.IdMustNotBeZero, createAccountErrors.getResult());
}
@Test
public void testCreateAccountsAsync() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
CompletableFuture<CreateAccountResultBatch> accountsFuture =
client.createAccountsAsync(accounts);
final var createAccountErrors = accountsFuture.get();
assertTrue(createAccountErrors.getLength() == 0);
CompletableFuture<AccountBatch> lookupFuture =
client.lookupAccountsAsync(new IdBatch(account1Id, account2Id));
final var lookupAccounts = lookupFuture.get();
assertEquals(2, lookupAccounts.getLength());
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
}
@Test
public void testCreateTransfers() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var transfer1Id = UInt128.id();
final var transfer2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
// Creating the accounts.
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
// Creating a transfer.
final var transfers = new TransferBatch(2);
transfers.add();
transfers.setId(transfer1Id);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setFlags(TransferFlags.NONE);
transfers.setAmount(100);
final var createTransferErrors = client.createTransfers(transfers);
assertTrue(createTransferErrors.getLength() == 0);
// Looking up the accounts.
final var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertTrue(lookupAccounts.getLength() == 2);
accounts.beforeFirst();
// Asserting the first account for the credit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.valueOf(100), lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Asserting the second account for the debit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.valueOf(100), lookupAccounts.getDebitsPosted());
// Looking up and asserting the transfer.
final var lookupTransfers = client.lookupTransfers(new IdBatch(transfer1Id, transfer2Id));
assertEquals(1, lookupTransfers.getLength());
transfers.beforeFirst();
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertNotEquals(0L, lookupTransfers.getTimestamp());
}
@Test
public void testCreateTransfersAsync() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var transfer1Id = UInt128.id();
final var transfer2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
// Creating the accounts.
CompletableFuture<CreateAccountResultBatch> future = client.createAccountsAsync(accounts);
final var createAccountErrors = future.get();
assertTrue(createAccountErrors.getLength() == 0);
// Creating a transfer.
final var transfers = new TransferBatch(2);
transfers.add();
transfers.setId(transfer1Id);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(100);
CompletableFuture<CreateTransferResultBatch> transfersFuture =
client.createTransfersAsync(transfers);
final var createTransferErrors = transfersFuture.get();
assertTrue(createTransferErrors.getLength() == 0);
// Looking up the accounts.
CompletableFuture<AccountBatch> lookupAccountsFuture =
client.lookupAccountsAsync(new IdBatch(account1Id, account2Id));
final var lookupAccounts = lookupAccountsFuture.get();
assertTrue(lookupAccounts.getLength() == 2);
accounts.beforeFirst();
// Asserting the first account for the credit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.valueOf(100), lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Asserting the second account for the debit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.valueOf(100), lookupAccounts.getDebitsPosted());
// Looking up and asserting the transfer.
CompletableFuture<TransferBatch> lookupTransfersFuture =
client.lookupTransfersAsync(new IdBatch(transfer1Id, transfer2Id));
final var lookupTransfers = lookupTransfersFuture.get();
assertEquals(1, lookupTransfers.getLength());
transfers.beforeFirst();
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertNotEquals(BigInteger.ZERO, lookupTransfers.getTimestamp());
}
@Test
public void testCreateInvalidTransfer() throws Throwable {
final var zeroedTransfers = new TransferBatch(1);
zeroedTransfers.add();
final var createTransfersErrors = client.createTransfers(zeroedTransfers);
assertTrue(createTransfersErrors.getLength() == 1);
assertTrue(createTransfersErrors.next());
assertEquals(CreateTransferResult.IdMustNotBeZero, createTransfersErrors.getResult());
}
@Test
public void testCreatePendingTransfers() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var transfer1Id = UInt128.id();
final var transfer2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
// Creating the accounts.
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
// Creating a pending transfer.
final var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(transfer1Id);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(100);
transfers.setFlags(TransferFlags.PENDING);
transfers.setTimeout(Integer.MAX_VALUE);
final var createTransfersErrors = client.createTransfers(transfers);
assertTrue(createTransfersErrors.getLength() == 0);
// Looking up the accounts.
var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertTrue(lookupAccounts.getLength() == 2);
accounts.beforeFirst();
// Asserting the first account for the pending credit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100), lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Asserting the second account for the pending debit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100), lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
// Looking up and asserting the pending transfer.
var lookupTransfers = client.lookupTransfers(new IdBatch(transfer1Id));
assertEquals(1, lookupTransfers.getLength());
transfers.beforeFirst();
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertNotEquals(0L, lookupTransfers.getTimestamp());
// Creating a post_pending transfer.
final var confirmTransfers = new TransferBatch(1);
confirmTransfers.add();
confirmTransfers.setId(transfer2Id);
confirmTransfers.setCreditAccountId(account1Id);
confirmTransfers.setDebitAccountId(account2Id);
confirmTransfers.setLedger(720);
confirmTransfers.setCode(1);
confirmTransfers.setAmount(100);
confirmTransfers.setFlags(TransferFlags.POST_PENDING_TRANSFER);
confirmTransfers.setPendingId(transfer1Id);
final var createPostTransfersErrors = client.createTransfers(confirmTransfers);
assertEquals(0, createPostTransfersErrors.getLength());
// Looking up the accounts again for the updated balance.
lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertTrue(lookupAccounts.getLength() == 2);
accounts.beforeFirst();
// Asserting the pending credit was posted for the first account.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.valueOf(100), lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Asserting the pending debit was posted for the second account.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.valueOf(100), lookupAccounts.getDebitsPosted());
// Looking up and asserting the post_pending transfer.
final var lookupVoidTransfers = client.lookupTransfers(new IdBatch(transfer2Id));
assertEquals(1, lookupVoidTransfers.getLength());
confirmTransfers.beforeFirst();
assertTrue(confirmTransfers.next());
assertTrue(lookupVoidTransfers.next());
assertTransfers(confirmTransfers, lookupVoidTransfers);
assertNotEquals(0L, lookupVoidTransfers.getTimestamp());
}
@Test
public void testCreatePendingTransfersAndVoid() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var transfer1Id = UInt128.id();
final var transfer2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
// Creating the accounts.
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
// Creating a pending transfer.
final var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(transfer1Id);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(100);
transfers.setFlags(TransferFlags.PENDING);
transfers.setTimeout(Integer.MAX_VALUE);
final var createTransfersErrors = client.createTransfers(transfers);
assertTrue(createTransfersErrors.getLength() == 0);
// Looking up the accounts.
var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertTrue(lookupAccounts.getLength() == 2);
accounts.beforeFirst();
// Asserting the first account for the pending credit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100), lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Asserting the second account for the pending credit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100), lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
// Looking up and asserting the pending transfer.
var lookupTransfers = client.lookupTransfers(new IdBatch(transfer1Id));
assertEquals(1, lookupTransfers.getLength());
transfers.beforeFirst();
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertNotEquals(0L, lookupTransfers.getTimestamp());
// Creating a void_pending transfer.
final var voidTransfers = new TransferBatch(2);
voidTransfers.add();
voidTransfers.setId(transfer2Id);
voidTransfers.setCreditAccountId(account1Id);
voidTransfers.setDebitAccountId(account2Id);
voidTransfers.setLedger(720);
voidTransfers.setCode(1);
voidTransfers.setAmount(100);
voidTransfers.setFlags(TransferFlags.VOID_PENDING_TRANSFER);
voidTransfers.setPendingId(transfer1Id);
final var createVoidTransfersErrors = client.createTransfers(voidTransfers);
assertEquals(0, createVoidTransfersErrors.getLength());
// Looking up the accounts again for the updated balance.
lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertTrue(lookupAccounts.getLength() == 2);
accounts.beforeFirst();
// Asserting the pending credit was voided for the first account.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Asserting the pending debit was voided for the second account.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Looking up and asserting the void_pending transfer.
final var lookupVoidTransfers = client.lookupTransfers(new IdBatch(transfer2Id));
assertEquals(1, lookupVoidTransfers.getLength());
voidTransfers.beforeFirst();
assertTrue(voidTransfers.next());
assertTrue(lookupVoidTransfers.next());
assertTransfers(voidTransfers, lookupVoidTransfers);
assertNotEquals(0L, lookupVoidTransfers.getTimestamp());
}
@Test
public void testCreatePendingTransfersAndVoidExpired() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var transfer1Id = UInt128.id();
final var transfer2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
// Creating the accounts.
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
// Creating a pending transfer.
final var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(transfer1Id);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(100);
transfers.setFlags(TransferFlags.PENDING);
transfers.setTimeout(1);
final var createTransfersErrors = client.createTransfers(transfers);
assertTrue(createTransfersErrors.getLength() == 0);
// Looking up the accounts.
var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertTrue(lookupAccounts.getLength() == 2);
accounts.beforeFirst();
// Asserting the first account for the pending credit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100), lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Asserting the second account for the pending credit.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100), lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
// Looking up and asserting the pending transfer.
final var lookupTransfers = client.lookupTransfers(new IdBatch(transfer1Id));
assertEquals(1, lookupTransfers.getLength());
transfers.beforeFirst();
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertNotEquals(0L, lookupTransfers.getTimestamp());
// We need to wait 1s for the server to expire the transfer, however the
// server can pulse the expiry operation anytime after the timeout,
// so adding an extra delay to avoid flaky tests.
final var timeout_ms = TimeUnit.SECONDS.toMillis(lookupTransfers.getTimeout());
final var currentMilis = System.currentTimeMillis();
final var extra_wait_time = 250L;
Thread.sleep(timeout_ms + extra_wait_time);
assertTrue(System.currentTimeMillis() - currentMilis > timeout_ms);
// Looking up the accounts again for the updated balance.
lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertTrue(lookupAccounts.getLength() == 2);
accounts.beforeFirst();
// Asserting the pending credit was voided.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Asserting the pending debit was voided.
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
// Creating a void_pending transfer.
final var voidTransfers = new TransferBatch(1);
voidTransfers.add();
voidTransfers.setId(transfer2Id);
voidTransfers.setCreditAccountId(account1Id);
voidTransfers.setDebitAccountId(account2Id);
voidTransfers.setLedger(720);
voidTransfers.setCode(1);
voidTransfers.setAmount(100);
voidTransfers.setFlags(TransferFlags.VOID_PENDING_TRANSFER);
voidTransfers.setPendingId(transfer1Id);
final var createVoidTransfersErrors = client.createTransfers(voidTransfers);
assertEquals(1, createVoidTransfersErrors.getLength());
assertTrue(createVoidTransfersErrors.next());
assertEquals(CreateTransferResult.PendingTransferExpired,
createVoidTransfersErrors.getResult());
}
@Test
public void testCreateLinkedTransfers() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var transfer1Id = UInt128.id();
final var transfer2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
final var transfers = new TransferBatch(2);
transfers.add();
transfers.setId(transfer1Id);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(100);
transfers.setFlags(TransferFlags.LINKED);
transfers.add();
transfers.setId(transfer2Id);
transfers.setCreditAccountId(account2Id);
transfers.setDebitAccountId(account1Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(49);
transfers.setFlags(TransferFlags.NONE);
final var createTransfersErrors = client.createTransfers(transfers);
assertTrue(createTransfersErrors.getLength() == 0);
final var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertEquals(2, lookupAccounts.getLength());
accounts.beforeFirst();
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100), lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.valueOf(49), lookupAccounts.getDebitsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(49), lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.valueOf(100), lookupAccounts.getDebitsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPending());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPending());
final var lookupTransfers = client.lookupTransfers(new IdBatch(transfer1Id, transfer2Id));
assertEquals(2, lookupTransfers.getLength());
transfers.beforeFirst();
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertNotEquals(0L, lookupTransfers.getTimestamp());
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertNotEquals(0L, lookupTransfers.getTimestamp());
}
@Test
public void testCreateClosingTransfers() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var closingTransferId = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(closingTransferId);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(0);
transfers.setFlags(
TransferFlags.CLOSING_CREDIT | TransferFlags.CLOSING_DEBIT | TransferFlags.PENDING);
var createTransfersErrors = client.createTransfers(transfers);
assertTrue(createTransfersErrors.getLength() == 0);
var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertEquals(2, lookupAccounts.getLength());
accounts.beforeFirst();
while (lookupAccounts.next()) {
assertTrue(accounts.next());
assertFalse(accounts.getFlags() == lookupAccounts.getFlags());
assertTrue(AccountFlags.hasClosed(lookupAccounts.getFlags()));
}
transfers = new TransferBatch(1);
transfers.add();
transfers.setId(UInt128.id());
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(0);
transfers.setPendingId(closingTransferId);
transfers.setFlags(TransferFlags.VOID_PENDING_TRANSFER);
createTransfersErrors = client.createTransfers(transfers);
assertTrue(createTransfersErrors.getLength() == 0);
lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertEquals(2, lookupAccounts.getLength());
accounts.beforeFirst();
while (lookupAccounts.next()) {
assertTrue(accounts.next());
assertAccounts(accounts, lookupAccounts);
assertFalse(AccountFlags.hasClosed(lookupAccounts.getFlags()));
}
}
@Test
public void testCreateAccountTooMuchData() throws Throwable {
final int TOO_MUCH_DATA = 10_000;
final var accounts = new AccountBatch(TOO_MUCH_DATA);
for (int i = 0; i < TOO_MUCH_DATA; i++) {
accounts.add();
accounts.setId(UInt128.id());
accounts.setCode(1);
accounts.setLedger(1);
}
try {
client.createAccounts(accounts);
assert false;
} catch (RequestException requestException) {
assertEquals(PacketStatus.TooMuchData.value, requestException.getStatus());
}
}
@Test
public void testCreateAccountTooMuchDataAsync() throws Throwable {
final int TOO_MUCH_DATA = 10_000;
final var accounts = new AccountBatch(TOO_MUCH_DATA);
for (int i = 0; i < TOO_MUCH_DATA; i++) {
accounts.add();
accounts.setId(UInt128.id());
accounts.setCode(1);
accounts.setLedger(1);
}
try {
CompletableFuture<CreateAccountResultBatch> future =
client.createAccountsAsync(accounts);
assert future != null;
future.get();
assert false;
} catch (ExecutionException executionException) {
assertTrue(executionException.getCause() instanceof RequestException);
final var requestException = (RequestException) executionException.getCause();
assertEquals(PacketStatus.TooMuchData.value, requestException.getStatus());
}
}
@Test
public void testCreateTransferTooMuchData() throws Throwable {
final int TOO_MUCH_DATA = 10_000;
final var transfers = new TransferBatch(TOO_MUCH_DATA);
for (int i = 0; i < TOO_MUCH_DATA; i++) {
transfers.add();
transfers.setId(UInt128.id());
transfers.setDebitAccountId(UInt128.id());
transfers.setDebitAccountId(UInt128.id());
transfers.setCode(1);
transfers.setLedger(1);
}
try {
client.createTransfers(transfers);
assert false;
} catch (RequestException requestException) {
assertEquals(PacketStatus.TooMuchData.value, requestException.getStatus());
}
}
@Test
public void testCreateTransferTooMuchDataAsync() throws Throwable {
final int TOO_MUCH_DATA = 10_000;
final var transfers = new TransferBatch(TOO_MUCH_DATA);
for (int i = 0; i < TOO_MUCH_DATA; i++) {
transfers.add();
transfers.setId(UInt128.id());
transfers.setDebitAccountId(UInt128.id());
transfers.setDebitAccountId(UInt128.id());
transfers.setCode(1);
transfers.setLedger(1);
}
try {
CompletableFuture<CreateTransferResultBatch> future =
client.createTransfersAsync(transfers);
assert future != null;
future.get();
assert false;
} catch (ExecutionException executionException) {
assertTrue(executionException.getCause() instanceof RequestException);
final var requestException = (RequestException) executionException.getCause();
assertEquals(PacketStatus.TooMuchData.value, requestException.getStatus());
}
}
/**
* This test asserts that the client can handle parallel threads up to concurrencyMax.
*/
@Test
public void testConcurrentTasks() throws Throwable {
final int TASKS_COUNT = 100;
final var barrier = new CountDownLatch(TASKS_COUNT);
try (final var client = new Client(clusterId, new String[] {server.getAddress()})) {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
final var tasks = new TransferTask[TASKS_COUNT];
for (int i = 0; i < TASKS_COUNT; i++) {
// Starting multiple threads submitting transfers.
tasks[i] = new TransferTask(client, account1Id, account2Id, barrier,
new CountDownLatch(0));
tasks[i].start();
}
// Wait for all threads:
for (int i = 0; i < TASKS_COUNT; i++) {
tasks[i].join();
assertTrue(tasks[i].result.getLength() == 0);
}
// Asserting if all transfers were submitted correctly.
final var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertEquals(2, lookupAccounts.getLength());
accounts.beforeFirst();
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100 * TASKS_COUNT), lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100 * TASKS_COUNT), lookupAccounts.getDebitsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
}
}
/**
* This test asserts that client.close() will wait for all ongoing request to complete And new
* threads trying to submit a request after the client was closed will fail with
* IllegalStateException.
*/
@Test
public void testCloseWithConcurrentTasks() throws Throwable {
// The goal here is to queue many concurrent requests,
// so we have a good chance of testing "client.close()" not only before/after
// calling "submit()", but also during the native call.
//
// Unfortunately this is a hacky test, but a reasonable one:
// Since our JNI module does not expose the acquire_packet function,
// we cannot insert a lock/wait in between "acquire_packet" and "submit"
// in order to cause and assert each variant.
final int TASKS_COUNT = 256;
final var enterBarrier = new CountDownLatch(TASKS_COUNT);
final var exitBarrier = new CountDownLatch(1);
try (final var client = new Client(clusterId, new String[] {server.getAddress()})) {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
final var tasks = new TransferTask[TASKS_COUNT];
for (int i = 0; i < TASKS_COUNT; i++) {
// Starting multiple threads submitting transfers.
tasks[i] =
new TransferTask(client, account1Id, account2Id, enterBarrier, exitBarrier);
tasks[i].start();
}
// Waits until one thread finish.
exitBarrier.await();
// And then close the client while threads are still working
// Some of them have already submitted the request, while others will fail
// due to "shutdown".
client.close();
int failedCount = 0;
int succeededCount = 0;
for (int i = 0; i < TASKS_COUNT; i++) {
// The client.close must wait until all submitted requests have completed
// Asserting that either the task succeeded or failed while waiting.
tasks[i].join();
final var succeeded = tasks[i].result != null && tasks[i].result.getLength() == 0;
// Can fail due to client closed.
final var failed = tasks[i].exception != null
&& tasks[i].exception instanceof IllegalStateException;
assertTrue(failed || succeeded);
if (failed) {
failedCount += 1;
} else if (succeeded) {
succeededCount += 1;
}
}
assertTrue(succeededCount + failedCount == TASKS_COUNT);
}
}
/**
* This test asserts that submit a request after the client was closed will fail with
* IllegalStateException.
*/
@Test
public void testClose() throws Throwable {
try {
// As we call client.close() explicitly,
// we don't need to use a try-with-resources block here.
final var client = new Client(clusterId, new String[] {server.getAddress()});
// Creating accounts.
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
// Closing the client.
client.close();
// Creating a transfer with a closed client.
final var transfers = new TransferBatch(2);
transfers.add();
transfers.setId(UInt128.id());
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setFlags(TransferFlags.NONE);
transfers.setAmount(100);
client.createTransfers(transfers);
assert false;
} catch (Throwable any) {
assertEquals(IllegalStateException.class, any.getClass());
}
}
/**
* This test asserts that async tasks will respect client's concurrencyMax.
*/
@Test
public void testAsyncTasks() throws Throwable {
final int TASKS_COUNT = 1_000_000;
final int CONCURRENCY_MAX = 8192;
final var semaphore = new Semaphore(CONCURRENCY_MAX);
final var executor = Executors.newFixedThreadPool(4);
try (final var client = new Client(clusterId, new String[] {server.getAddress()})) {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
final var tasks = new CompletableFuture[TASKS_COUNT];
for (int i = 0; i < TASKS_COUNT; i++) {
final var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(UInt128.id());
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(100);
// Starting async batch.
semaphore.acquire();
tasks[i] = client.createTransfersAsync(transfers).thenApplyAsync((result) -> {
semaphore.release();
return result;
}, executor);
}
// Wait for all tasks.
CompletableFuture.allOf(tasks).join();
for (int i = 0; i < TASKS_COUNT; i++) {
@SuppressWarnings("unchecked")
final var future = (CompletableFuture<CreateTransferResultBatch>) tasks[i];
final var result = future.get();
assertEquals(0, result.getLength());
}
// Asserting if all transfers were submitted correctly.
final var lookupAccounts = client.lookupAccounts(new IdBatch(account1Id, account2Id));
assertEquals(2, lookupAccounts.getLength());
accounts.beforeFirst();
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100 * TASKS_COUNT), lookupAccounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getDebitsPosted());
assertTrue(accounts.next());
assertTrue(lookupAccounts.next());
assertAccounts(accounts, lookupAccounts);
assertEquals(BigInteger.valueOf(100 * TASKS_COUNT), lookupAccounts.getDebitsPosted());
assertEquals(BigInteger.ZERO, lookupAccounts.getCreditsPosted());
}
}
@Test
public void testAccountTransfers() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
{
final var accounts = generateAccounts(account1Id, account2Id);
// Enabling AccountFlags.HISTORY:
while (accounts.next()) {
accounts.setFlags(accounts.getFlags() | AccountFlags.HISTORY);
}
accounts.beforeFirst();
// Creating the accounts.
final var createAccountsErrors = client.createAccounts(accounts);
assertTrue(createAccountsErrors.getLength() == 0);
}
{
// Creating a transfer.
final var transfers = new TransferBatch(10);
for (int i = 0; i < 10; i++) {
transfers.add();
transfers.setId(UInt128.id());
// Swap the debit and credit accounts:
if (i % 2 == 0) {
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
} else {
transfers.setCreditAccountId(account2Id);
transfers.setDebitAccountId(account1Id);
}
transfers.setLedger(720);
transfers.setCode(1);
transfers.setFlags(TransferFlags.NONE);
transfers.setAmount(100);
}
final var createTransfersErrors = client.createTransfers(transfers);
assertTrue(createTransfersErrors.getLength() == 0);
}
{
// Querying transfers where:
// `debit_account_id=$account1Id OR credit_account_id=$account1Id
// ORDER BY timestamp ASC`.
final var filter = new AccountFilter();
filter.setAccountId(account1Id);
filter.setTimestampMin(0);
filter.setTimestampMax(0);
filter.setLimit(254);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(false);
final var accountTransfers = client.getAccountTransfers(filter);
final var accountBalances = client.getAccountBalances(filter);
assertTrue(accountTransfers.getLength() == 10);
assertTrue(accountBalances.getLength() == 10);
long timestamp = 0;
while (accountTransfers.next()) {
assertTrue(Long.compareUnsigned(accountTransfers.getTimestamp(), timestamp) > 0);
timestamp = accountTransfers.getTimestamp();
assertTrue(accountBalances.next());
assertEquals(accountTransfers.getTimestamp(), accountBalances.getTimestamp());
}
}
{
// Querying transfers where:
// `debit_account_id=$account2Id OR credit_account_id=$account2Id
// ORDER BY timestamp DESC`.
final var filter = new AccountFilter();
filter.setAccountId(account2Id);
filter.setTimestampMin(0);
filter.setTimestampMax(0);
filter.setLimit(254);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(true);
final var accountTransfers = client.getAccountTransfers(filter);
final var accountBalances = client.getAccountBalances(filter);
assertTrue(accountTransfers.getLength() == 10);
assertTrue(accountBalances.getLength() == 10);
long timestamp = Long.MIN_VALUE; // MIN_VALUE is the unsigned MAX_VALUE.
while (accountTransfers.next()) {
assertTrue(Long.compareUnsigned(accountTransfers.getTimestamp(), timestamp) < 0);
timestamp = accountTransfers.getTimestamp();
assertTrue(accountBalances.next());
assertEquals(accountTransfers.getTimestamp(), accountBalances.getTimestamp());
}
}
{
// Querying transfers where:
// `debit_account_id=$account1Id
// ORDER BY timestamp ASC`.
final var filter = new AccountFilter();
filter.setAccountId(account1Id);
filter.setTimestampMin(0);
filter.setTimestampMax(0);
filter.setLimit(254);
filter.setDebits(true);
filter.setCredits(false);
filter.setReversed(false);
final var accountTransfers = client.getAccountTransfers(filter);
final var accountBalances = client.getAccountBalances(filter);
assertTrue(accountTransfers.getLength() == 5);
assertTrue(accountBalances.getLength() == 5);
long timestamp = 0;
while (accountTransfers.next()) {
assertTrue(Long.compareUnsigned(accountTransfers.getTimestamp(), timestamp) > 0);
timestamp = accountTransfers.getTimestamp();
assertTrue(accountBalances.next());
assertEquals(accountTransfers.getTimestamp(), accountBalances.getTimestamp());
}
}
{
// Querying transfers where:
// `credit_account_id=$account2Id
// ORDER BY timestamp DESC`.
final var filter = new AccountFilter();
filter.setAccountId(account2Id);
filter.setTimestampMin(1);
filter.setTimestampMax(-2L); // -2L == ulong max - 1
filter.setLimit(254);
filter.setDebits(false);
filter.setCredits(true);
filter.setReversed(true);
final var accountTransfers = client.getAccountTransfers(filter);
final var accountBalances = client.getAccountBalances(filter);
assertTrue(accountTransfers.getLength() == 5);
assertTrue(accountBalances.getLength() == 5);
long timestamp = Long.MIN_VALUE; // MIN_VALUE is the unsigned MAX_VALUE.
while (accountTransfers.next()) {
assertTrue(Long.compareUnsigned(accountTransfers.getTimestamp(), timestamp) < 0);
timestamp = accountTransfers.getTimestamp();
assertTrue(accountBalances.next());
assertEquals(accountTransfers.getTimestamp(), accountBalances.getTimestamp());
}
}
{
// Querying transfers where:
// `debit_account_id=$account1Id OR credit_account_id=$account1Id
// ORDER BY timestamp ASC LIMIT 5`.
final var filter = new AccountFilter();
filter.setAccountId(account1Id);
filter.setTimestampMin(0);
filter.setTimestampMax(0);
filter.setLimit(5);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(false);
// First 5 items:
final var accountTransfers1 = client.getAccountTransfers(filter);
final var accountBalances1 = client.getAccountBalances(filter);
assertTrue(accountTransfers1.getLength() == 5);
assertTrue(accountBalances1.getLength() == 5);
long timestamp = 0;
while (accountTransfers1.next()) {
assertTrue(Long.compareUnsigned(accountTransfers1.getTimestamp(), timestamp) > 0);
timestamp = accountTransfers1.getTimestamp();
assertTrue(accountBalances1.next());
assertEquals(accountTransfers1.getTimestamp(), accountBalances1.getTimestamp());
}
// Next 5 items from this timestamp:
filter.setTimestampMin(timestamp + 1);
final var accountTransfers2 = client.getAccountTransfers(filter);
final var accountBalances2 = client.getAccountBalances(filter);
assertTrue(accountTransfers2.getLength() == 5);
assertTrue(accountBalances2.getLength() == 5);
while (accountTransfers2.next()) {
assertTrue(Long.compareUnsigned(accountTransfers2.getTimestamp(), timestamp) > 0);
timestamp = accountTransfers2.getTimestamp();
assertTrue(accountBalances2.next());
assertEquals(accountTransfers2.getTimestamp(), accountBalances2.getTimestamp());
}
// No more results after that timestamp:
filter.setTimestampMin(timestamp + 1);
final var accountTransfers3 = client.getAccountTransfers(filter);
final var accountBalances3 = client.getAccountBalances(filter);
assertTrue(accountTransfers3.getLength() == 0);
assertTrue(accountBalances3.getLength() == 0);
}
{
// Querying transfers where:
// `debit_account_id=$account2Id OR credit_account_id=$account2Id
// ORDER BY timestamp DESC LIMIT 5`.
final var filter = new AccountFilter();
filter.setAccountId(account2Id);
filter.setTimestampMin(0);
filter.setTimestampMax(0);
filter.setLimit(5);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(true);
// First 5 items:
final var accountTransfers1 = client.getAccountTransfers(filter);
final var accountBalances1 = client.getAccountBalances(filter);
assertTrue(accountTransfers1.getLength() == 5);
assertTrue(accountTransfers1.getLength() == 5);
long timestamp = Long.MIN_VALUE; // MIN_VALUE is the unsigned MAX_VALUE.
while (accountTransfers1.next()) {
assertTrue(Long.compareUnsigned(accountTransfers1.getTimestamp(), timestamp) < 0);
timestamp = accountTransfers1.getTimestamp();
assertTrue(accountBalances1.next());
assertEquals(accountTransfers1.getTimestamp(), accountBalances1.getTimestamp());
}
// Next 5 items from this timestamp:
filter.setTimestampMax(timestamp - 1);
final var accountTransfers2 = client.getAccountTransfers(filter);
final var accountBalances2 = client.getAccountBalances(filter);
assertTrue(accountTransfers2.getLength() == 5);
assertTrue(accountBalances2.getLength() == 5);
while (accountTransfers2.next()) {
assertTrue(Long.compareUnsigned(accountTransfers2.getTimestamp(), timestamp) < 0);
timestamp = accountTransfers2.getTimestamp();
assertTrue(accountBalances2.next());
assertEquals(accountTransfers2.getTimestamp(), accountBalances2.getTimestamp());
}
// No more results before that timestamp:
filter.setTimestampMax(timestamp - 1);
final var accountTransfers3 = client.getAccountTransfers(filter);
final var accountBalances3 = client.getAccountBalances(filter);
assertTrue(accountTransfers3.getLength() == 0);
assertTrue(accountBalances3.getLength() == 0);
}
// For those tests it doesn't matter using the sync or async version. We use the async
// version here for test coverage purposes, but there's no need to duplicate the tests.
{
// Empty filter:
final var filter = new AccountFilter();
assertTrue(client.getAccountTransfersAsync(filter).get().getLength() == 0);
assertTrue(client.getAccountBalancesAsync(filter).get().getLength() == 0);
}
{
// Invalid account:
final var filter = new AccountFilter();
filter.setAccountId(0);
filter.setTimestampMin(0);
filter.setTimestampMax(0);
filter.setLimit(254);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(false);
assertTrue(client.getAccountTransfersAsync(filter).get().getLength() == 0);
assertTrue(client.getAccountBalancesAsync(filter).get().getLength() == 0);
}
{
// Invalid timestamp min:
final var filter = new AccountFilter();
filter.setAccountId(account2Id);
filter.setTimestampMin(-1L); // -1L == ulong max value
filter.setTimestampMax(0);
filter.setLimit(254);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(false);
assertTrue(client.getAccountTransfersAsync(filter).get().getLength() == 0);
assertTrue(client.getAccountBalancesAsync(filter).get().getLength() == 0);
}
{
// Invalid timestamp max:
final var filter = new AccountFilter();
filter.setAccountId(account2Id);
filter.setTimestampMin(0);
filter.setTimestampMax(-1L); // -1L == ulong max value
filter.setLimit(254);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(false);
assertTrue(client.getAccountTransfersAsync(filter).get().getLength() == 0);
assertTrue(client.getAccountBalancesAsync(filter).get().getLength() == 0);
}
{
// Invalid timestamp min > max:
final var filter = new AccountFilter();
filter.setAccountId(account2Id);
filter.setTimestampMin(-2L); // -2L == ulong max - 1
filter.setTimestampMax(1);
filter.setLimit(254);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(false);
assertTrue(client.getAccountTransfersAsync(filter).get().getLength() == 0);
assertTrue(client.getAccountBalancesAsync(filter).get().getLength() == 0);
}
{
// Zero limit:
final var filter = new AccountFilter();
filter.setAccountId(account2Id);
filter.setTimestampMin(0);
filter.setTimestampMax(0);
filter.setLimit(0);
filter.setDebits(true);
filter.setCredits(true);
filter.setReversed(false);
assertTrue(client.getAccountTransfersAsync(filter).get().getLength() == 0);
assertTrue(client.getAccountBalancesAsync(filter).get().getLength() == 0);
}
{
// Zero flags:
final var filter = new AccountFilter();
filter.setAccountId(account2Id);
filter.setTimestampMin(0);
filter.setTimestampMax(0);
filter.setLimit(0);
filter.setDebits(false);
filter.setCredits(false);
filter.setReversed(false);
assertTrue(client.getAccountTransfersAsync(filter).get().getLength() == 0);
assertTrue(client.getAccountBalancesAsync(filter).get().getLength() == 0);
}
}
@Test
public void testQueryAccounts() throws Throwable {
{
// Creating accounts.
final var accounts = new AccountBatch(10);
for (int i = 0; i < 10; i++) {
accounts.add();
accounts.setId(UInt128.id());
if (i % 2 == 0) {
accounts.setUserData128(1000L);
accounts.setUserData64(100L);
accounts.setUserData32(10);
} else {
accounts.setUserData128(2000L);
accounts.setUserData64(200L);
accounts.setUserData32(20);
}
accounts.setCode(999);
accounts.setLedger(720);
accounts.setFlags(TransferFlags.NONE);
}
final var createAccountsErrors = client.createAccounts(accounts);
assertTrue(createAccountsErrors.getLength() == 0);
}
{
// Querying accounts where:
// `user_data_128=1000 AND user_data_64=100 AND user_data_32=10
// AND code=999 AND ledger=720 ORDER BY timestamp ASC`.
final var filter = new QueryFilter();
filter.setUserData128(1000L);
filter.setUserData64(100L);
filter.setUserData32(10);
filter.setCode(999);
filter.setLedger(720);
filter.setLimit(254);
filter.setReversed(false);
final AccountBatch query = client.queryAccounts(filter);
assertTrue(query.getLength() == 5);
long timestamp = 0;
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) > 0);
timestamp = query.getTimestamp();
assertArrayEquals(filter.getUserData128(), query.getUserData128());
assertTrue(filter.getUserData64() == query.getUserData64());
assertTrue(filter.getUserData32() == query.getUserData32());
assertTrue(filter.getLedger() == query.getLedger());
assertTrue(filter.getCode() == query.getCode());
}
}
{
// Querying accounts where:
// `user_data_128=2000 AND user_data_64=200 AND user_data_32=20
// AND code=999 AND ledger=720 ORDER BY timestamp DESC`.
final var filter = new QueryFilter();
filter.setUserData128(2000L);
filter.setUserData64(200L);
filter.setUserData32(20);
filter.setCode(999);
filter.setLedger(720);
filter.setLimit(254);
filter.setReversed(true);
final AccountBatch query = client.queryAccounts(filter);
assertTrue(query.getLength() == 5);
long timestamp = Long.MIN_VALUE; // MIN_VALUE is the unsigned MAX_VALUE.
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) < 0);
timestamp = query.getTimestamp();
assertArrayEquals(filter.getUserData128(), query.getUserData128());
assertTrue(filter.getUserData64() == query.getUserData64());
assertTrue(filter.getUserData32() == query.getUserData32());
assertTrue(filter.getLedger() == query.getLedger());
assertTrue(filter.getCode() == query.getCode());
}
}
{
// Querying accounts where:
// `code=999 ORDER BY timestamp ASC`.
final var filter = new QueryFilter();
filter.setCode(999);
filter.setLimit(254);
filter.setReversed(false);
final AccountBatch query = client.queryAccounts(filter);
assertTrue(query.getLength() == 10);
long timestamp = 0L;
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) > 0);
timestamp = query.getTimestamp();
assertTrue(filter.getCode() == query.getCode());
}
}
{
// Querying accounts where:
// `code=999 ORDER BY timestamp DESC LIMIT 5`.
final var filter = new QueryFilter();
filter.setCode(999);
filter.setLimit(5);
filter.setReversed(true);
// First 5 items:
AccountBatch query = client.queryAccounts(filter);
assertTrue(query.getLength() == 5);
long timestamp = Long.MIN_VALUE; // MIN_VALUE is the unsigned MAX_VALUE.
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) < 0);
timestamp = query.getTimestamp();
assertTrue(filter.getCode() == query.getCode());
}
// Next 5 items from this timestamp:
filter.setTimestampMax(timestamp - 1);
query = client.queryAccounts(filter);
assertTrue(query.getLength() == 5);
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) < 0);
timestamp = query.getTimestamp();
assertTrue(filter.getCode() == query.getCode());
}
// No more results:
filter.setTimestampMax(timestamp - 1);
query = client.queryAccounts(filter);
assertTrue(query.getLength() == 0);
}
{
// Not found:
final var filter = new QueryFilter();
filter.setUserData64(200);
filter.setUserData32(10);
filter.setLimit(254);
filter.setReversed(false);
assertTrue(client.queryAccounts(filter).getLength() == 0);
}
}
@Test
public void testQueryTransfers() throws Throwable {
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
{
// Creating the accounts.
final var accounts = generateAccounts(account1Id, account2Id);
final var createAccountsErrors = client.createAccounts(accounts);
assertTrue(createAccountsErrors.getLength() == 0);
}
{
// Creating transfers.
final var transfers = new TransferBatch(10);
for (int i = 0; i < 10; i++) {
transfers.add();
transfers.setId(UInt128.id());
if (i % 2 == 0) {
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setUserData128(1000L);
transfers.setUserData64(100L);
transfers.setUserData32(10);
} else {
transfers.setCreditAccountId(account2Id);
transfers.setDebitAccountId(account1Id);
transfers.setUserData128(2000L);
transfers.setUserData64(200L);
transfers.setUserData32(20);
}
transfers.setCode(999);
transfers.setLedger(720);
transfers.setFlags(TransferFlags.NONE);
transfers.setAmount(100);
}
final var createTransfersErrors = client.createTransfers(transfers);
assertTrue(createTransfersErrors.getLength() == 0);
}
{
// Querying transfers where:
// `user_data_128=1000 AND user_data_64=100 AND user_data_32=10
// AND code=999 AND ledger=720 ORDER BY timestamp ASC`.
final var filter = new QueryFilter();
filter.setUserData128(1000L);
filter.setUserData64(100L);
filter.setUserData32(10);
filter.setCode(999);
filter.setLedger(720);
filter.setLimit(254);
filter.setReversed(false);
final TransferBatch query = client.queryTransfers(filter);
assertTrue(query.getLength() == 5);
long timestamp = 0;
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) > 0);
timestamp = query.getTimestamp();
assertArrayEquals(filter.getUserData128(), query.getUserData128());
assertTrue(filter.getUserData64() == query.getUserData64());
assertTrue(filter.getUserData32() == query.getUserData32());
assertTrue(filter.getLedger() == query.getLedger());
assertTrue(filter.getCode() == query.getCode());
}
}
{
// Querying transfers where:
// `user_data_128=2000 AND user_data_64=200 AND user_data_32=20
// AND code=999 AND ledger=720 ORDER BY timestamp DESC`.
final var filter = new QueryFilter();
filter.setUserData128(2000L);
filter.setUserData64(200L);
filter.setUserData32(20);
filter.setCode(999);
filter.setLedger(720);
filter.setLimit(254);
filter.setReversed(true);
final TransferBatch query = client.queryTransfers(filter);
assertTrue(query.getLength() == 5);
long timestamp = Long.MIN_VALUE; // MIN_VALUE is the unsigned MAX_VALUE.
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) < 0);
timestamp = query.getTimestamp();
assertArrayEquals(filter.getUserData128(), query.getUserData128());
assertTrue(filter.getUserData64() == query.getUserData64());
assertTrue(filter.getUserData32() == query.getUserData32());
assertTrue(filter.getLedger() == query.getLedger());
assertTrue(filter.getCode() == query.getCode());
}
}
{
// Querying transfers where:
// `code=999 ORDER BY timestamp ASC`.
final var filter = new QueryFilter();
filter.setCode(999);
filter.setLimit(254);
filter.setReversed(false);
final TransferBatch query = client.queryTransfers(filter);
assertTrue(query.getLength() == 10);
long timestamp = 0L;
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) > 0);
timestamp = query.getTimestamp();
assertTrue(filter.getCode() == query.getCode());
}
}
{
// Querying transfers where:
// `code=999 ORDER BY timestamp DESC LIMIT 5`.
final var filter = new QueryFilter();
filter.setCode(999);
filter.setLimit(5);
filter.setReversed(true);
// First 5 items:
TransferBatch query = client.queryTransfers(filter);
assertTrue(query.getLength() == 5);
long timestamp = Long.MIN_VALUE; // MIN_VALUE is the unsigned MAX_VALUE.
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) < 0);
timestamp = query.getTimestamp();
assertTrue(filter.getCode() == query.getCode());
}
// Next 5 items from this timestamp:
filter.setTimestampMax(timestamp - 1);
query = client.queryTransfers(filter);
assertTrue(query.getLength() == 5);
while (query.next()) {
assertTrue(Long.compareUnsigned(query.getTimestamp(), timestamp) < 0);
timestamp = query.getTimestamp();
assertTrue(filter.getCode() == query.getCode());
}
// No more results:
filter.setTimestampMax(timestamp - 1);
query = client.queryTransfers(filter);
assertTrue(query.getLength() == 0);
}
{
// Not found:
final var filter = new QueryFilter();
filter.setUserData64(200);
filter.setUserData32(10);
filter.setLimit(254);
filter.setReversed(false);
assertTrue(client.queryTransfers(filter).getLength() == 0);
}
}
@Test
public void testInvalidQueryFilter() throws Throwable {
// For those tests it doesn't matter using the sync or async version. We use the async
// version here for test coverage purposes, but there's no need to duplicate the tests.
{
// Empty filter with zero limit:
final var filter = new QueryFilter();
assertTrue(client.queryAccountsAsync(filter).get().getLength() == 0);
assertTrue(client.queryTransfersAsync(filter).get().getLength() == 0);
}
{
// Invalid timestamp min:
final var filter = new QueryFilter();
filter.setTimestampMin(-1L); // -1L == ulong max value
filter.setTimestampMax(0);
filter.setLimit(254);
assertTrue(client.queryAccountsAsync(filter).get().getLength() == 0);
assertTrue(client.queryTransfersAsync(filter).get().getLength() == 0);
}
{
// Invalid timestamp max:
final var filter = new QueryFilter();
filter.setTimestampMin(0);
filter.setTimestampMax(-1L); // -1L == ulong max value
filter.setLimit(254);
assertTrue(client.queryAccountsAsync(filter).get().getLength() == 0);
assertTrue(client.queryTransfersAsync(filter).get().getLength() == 0);
}
{
// Invalid timestamp min > max:
final var filter = new QueryFilter();
filter.setTimestampMin(-2); // -2L == ulong max - 1
filter.setTimestampMax(1);
filter.setLimit(254);
assertTrue(client.queryAccountsAsync(filter).get().getLength() == 0);
assertTrue(client.queryTransfersAsync(filter).get().getLength() == 0);
}
}
@Test
public void testImportedFlag() throws Throwable {
// Gets the last timestamp recorded and waits for 10ms so the
// timestamp can be used as reference for importing past movements.
var timestamp = getTimestampLast();
Thread.sleep(10);
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var transferId = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
while (accounts.next()) {
accounts.setFlags(AccountFlags.IMPORTED);
accounts.setTimestamp(timestamp + accounts.getPosition() + 1);
}
accounts.beforeFirst();
// Creating the accounts.
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
// Creating a transfer.
final var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(transferId);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode((short) 1);
transfers.setFlags(TransferFlags.IMPORTED);
transfers.setAmount(100);
transfers.setTimestamp(timestamp + accounts.getLength() + 1);
final var createTransferErrors = client.createTransfers(transfers);
assertTrue(createTransferErrors.getLength() == 0);
// Looking up and asserting the transfer.
final var lookupTransfers = client.lookupTransfers(new IdBatch(transferId));
assertEquals(1, lookupTransfers.getLength());
transfers.beforeFirst();
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertEquals(timestamp + accounts.getLength() + 1, lookupTransfers.getTimestamp());
}
@Test
public void testImportedFlagAsync() throws Throwable {
var timestamp = getTimestampLast();
Thread.sleep(10);
final var account1Id = UInt128.id();
final var account2Id = UInt128.id();
final var transferId = UInt128.id();
final var accounts = generateAccounts(account1Id, account2Id);
while (accounts.next()) {
accounts.setTimestamp(timestamp + accounts.getPosition() + 1);
accounts.setFlags(AccountFlags.IMPORTED);
}
accounts.beforeFirst();
// Creating the accounts.
CompletableFuture<CreateAccountResultBatch> future = client.createAccountsAsync(accounts);
final var createAccountErrors = future.get();
assertTrue(createAccountErrors.getLength() == 0);
// Creating a transfer.
final var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(transferId);
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode((short) 1);
transfers.setAmount(100);
transfers.setFlags(TransferFlags.IMPORTED);
transfers.setTimestamp(timestamp + accounts.getLength() + 1);
CompletableFuture<CreateTransferResultBatch> transfersFuture =
client.createTransfersAsync(transfers);
final var createTransferErrors = transfersFuture.get();
assertTrue(createTransferErrors.getLength() == 0);
// Looking up and asserting the transfer.
CompletableFuture<TransferBatch> lookupTransfersFuture =
client.lookupTransfersAsync(new IdBatch(transferId));
final var lookupTransfers = lookupTransfersFuture.get();
assertEquals(1, lookupTransfers.getLength());
transfers.beforeFirst();
assertTrue(transfers.next());
assertTrue(lookupTransfers.next());
assertTransfers(transfers, lookupTransfers);
assertEquals(timestamp + accounts.getLength() + 1, lookupTransfers.getTimestamp());
}
private long getTimestampLast() {
final var id = UInt128.id();
final var accounts = generateAccounts(id);
final var createAccountErrors = client.createAccounts(accounts);
assertTrue(createAccountErrors.getLength() == 0);
final var lookupAccounts = client.lookupAccounts(new IdBatch(id));
assertEquals(1, lookupAccounts.getLength());
assertTrue(lookupAccounts.next());
return lookupAccounts.getTimestamp();
}
private static void assertAccounts(AccountBatch account1, AccountBatch account2) {
assertArrayEquals(account1.getId(), account2.getId());
assertArrayEquals(account1.getUserData128(), account2.getUserData128());
assertEquals(account1.getUserData64(), account2.getUserData64());
assertEquals(account1.getUserData32(), account2.getUserData32());
assertEquals(account1.getLedger(), account2.getLedger());
assertEquals(account1.getCode(), account2.getCode());
assertEquals(account1.getFlags(), account2.getFlags());
}
private static void assertTransfers(TransferBatch transfer1, TransferBatch transfer2) {
assertArrayEquals(transfer1.getId(), transfer2.getId());
assertArrayEquals(transfer1.getDebitAccountId(), transfer2.getDebitAccountId());
assertArrayEquals(transfer1.getCreditAccountId(), transfer2.getCreditAccountId());
assertEquals(transfer1.getAmount(), transfer2.getAmount());
assertArrayEquals(transfer1.getPendingId(), transfer2.getPendingId());
assertArrayEquals(transfer1.getUserData128(), transfer2.getUserData128());
assertEquals(transfer1.getUserData64(), transfer2.getUserData64());
assertEquals(transfer1.getUserData32(), transfer2.getUserData32());
assertEquals(transfer1.getTimeout(), transfer2.getTimeout());
assertEquals(transfer1.getLedger(), transfer2.getLedger());
assertEquals(transfer1.getCode(), transfer2.getCode());
assertEquals(transfer1.getFlags(), transfer2.getFlags());
}
private static class TransferTask extends Thread {
public final Client client;
public CreateTransferResultBatch result;
public Throwable exception;
private byte[] account1Id;
private byte[] account2Id;
private CountDownLatch enterBarrier;
private CountDownLatch exitBarrier;
public TransferTask(Client client, byte[] account1Id, byte[] account2Id,
CountDownLatch enterBarrier, CountDownLatch exitBarrier) {
this.client = client;
this.result = null;
this.exception = null;
this.account1Id = account1Id;
this.account2Id = account2Id;
this.enterBarrier = enterBarrier;
this.exitBarrier = exitBarrier;
}
@Override
public synchronized void run() {
final var transfers = new TransferBatch(1);
transfers.add();
transfers.setId(UInt128.asBytes(UUID.randomUUID()));
transfers.setCreditAccountId(account1Id);
transfers.setDebitAccountId(account2Id);
transfers.setLedger(720);
transfers.setCode(1);
transfers.setAmount(100);
try {
enterBarrier.countDown();
enterBarrier.await();
result = client.createTransfers(transfers);
} catch (Throwable e) {
exception = e;
} finally {
exitBarrier.countDown();
}
}
}
private static class Server implements AutoCloseable {
public static final String TB_FILE = "./0_0.tigerbeetle.tests";
public static final String TB_SERVER = "../../../zig-out/bin/tigerbeetle";
private final Process process;
private String address;
public Server() throws IOException, Exception, InterruptedException {
cleanUp();
String exe;
switch (JNILoader.OS.getOS()) {
case windows:
exe = TB_SERVER + ".exe";
break;
default:
exe = TB_SERVER;
break;
}
final var format = Runtime.getRuntime().exec(new String[] {exe, "format", "--cluster=0",
"--replica=0", "--replica-count=1", "--development", TB_FILE});
if (format.waitFor() != 0) {
final var reader =
new BufferedReader(new InputStreamReader(format.getErrorStream()));
final var error = reader.lines().collect(Collectors.joining(". "));
throw new Exception("Format failed. " + error);
}
this.process = new ProcessBuilder()
.command(new String[] {exe, "start", "--addresses=0", "--development", TB_FILE})
.redirectOutput(Redirect.PIPE).redirectError(Redirect.INHERIT).start();
final var stdout = process.getInputStream();
try (final var reader = new BufferedReader(new InputStreamReader(stdout))) {
this.address = reader.readLine().trim();
}
}
public String getAddress() {
return address;
}
@Override
public void close() throws Exception {
cleanUp();
}
private void cleanUp() throws Exception {
try {
if (process != null && process.isAlive()) {
process.destroy();
}
final var file = new File("./" + TB_FILE);
file.delete();
} catch (Throwable any) {
throw new Exception("Cleanup has failed");
}
}
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/UInt128Test.java | package com.tigerbeetle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertSame;
import java.util.concurrent.CountDownLatch;
import java.math.BigInteger;
import java.util.UUID;
import org.junit.Test;
public class UInt128Test {
// bytes representing a pair of longs (100, 1000):
final static byte[] bytes = new byte[] {100, 0, 0, 0, 0, 0, 0, 0, -24, 3, 0, 0, 0, 0, 0, 0};
/// Consistency of U128 across Zig and the language clients.
/// It must be kept in sync with all platforms.
@Test
public void consistencyTest() {
// Decimal representation:
final long upper = Long.parseUnsignedLong("11647051514084770242");
final long lower = Long.parseUnsignedLong("15119395263638463974");
final var u128 = UInt128.asBigInteger(lower, upper);
assertEquals("214850178493633095719753766415838275046", u128.toString());
// Binary representation:
final byte[] binary = new byte[] {(byte) 0xe6, (byte) 0xe5, (byte) 0xe4, (byte) 0xe3,
(byte) 0xe2, (byte) 0xe1, (byte) 0xd2, (byte) 0xd1, (byte) 0xc2, (byte) 0xc1,
(byte) 0xb2, (byte) 0xb1, (byte) 0xa4, (byte) 0xa3, (byte) 0xa2, (byte) 0xa1};
final var bytes = UInt128.asBytes(lower, upper);
assertArrayEquals(binary, bytes);
// UUID representation:
final var guid = UUID.fromString("a1a2a3a4-b1b2-c1c2-d1d2-e1e2e3e4e5e6");
assertEquals(guid, UInt128.asUUID(bytes));
assertArrayEquals(bytes, UInt128.asBytes(guid));
assertEquals(u128, UInt128.asBigInteger(UInt128.asBytes(guid)));
}
@Test(expected = NullPointerException.class)
public void testAsLongNull() {
@SuppressWarnings("unused")
var nop = UInt128.asLong(null, UInt128.LeastSignificant);
assert false;
}
@Test(expected = IllegalArgumentException.class)
public void testAsLongInvalid() {
byte[] bytes = new byte[] {1, 2, 3, 4, 5, 6};
@SuppressWarnings("unused")
var nop = UInt128.asLong(bytes, UInt128.LeastSignificant);
assert false;
}
@Test
public void testAsLong() {
var ls = UInt128.asLong(bytes, UInt128.LeastSignificant);
var ms = UInt128.asLong(bytes, UInt128.MostSignificant);
assertEquals(100L, ls);
assertEquals(1000L, ms);
byte[] reverse = UInt128.asBytes(100, 1000);
assertArrayEquals(bytes, reverse);
}
@Test
public void testAsBytes() {
byte[] reverse = UInt128.asBytes(100, 1000);
assertArrayEquals(bytes, reverse);
}
@Test
public void testAsBytesFromSingleLong() {
byte[] singleLong = UInt128.asBytes(100L);
assertEquals(100L, UInt128.asLong(singleLong, UInt128.LeastSignificant));
assertEquals(0L, UInt128.asLong(singleLong, UInt128.MostSignificant));
}
@Test
public void testAsBytesZero() {
byte[] reverse = UInt128.asBytes(0, 0);
assertArrayEquals(new byte[16], reverse);
}
@Test(expected = NullPointerException.class)
public void testAsBytesUUIDNull() {
UUID uuid = null;
@SuppressWarnings("unused")
var nop = UInt128.asBytes(uuid);
assert false;
}
@Test
public void testAsBytesUUID() {
var uuid = new UUID(1000, 100);
byte[] reverse = UInt128.asBytes(uuid);
assertArrayEquals(bytes, reverse);
}
@Test
public void testAsUUID() {
var uuid = UInt128.asUUID(bytes);
assertEquals(new UUID(1000, 100), uuid);
}
@Test(expected = NullPointerException.class)
public void testAsUUIDNull() {
@SuppressWarnings("unused")
var nop = UInt128.asUUID(null);
assert false;
}
@Test(expected = IllegalArgumentException.class)
public void testAsUUIDInvalid() {
byte[] bytes = new byte[] {1, 2, 3, 4, 5, 6};
@SuppressWarnings("unused")
var nop = UInt128.asUUID(bytes);
assert false;
}
@Test(expected = NullPointerException.class)
public void testAsBytesBigIntegerNull() {
BigInteger bigint = null;
@SuppressWarnings("unused")
var nop = UInt128.asBytes(bigint);
assert false;
}
@Test
public void testAsBigIntegerFromLong() {
var bigint = UInt128.asBigInteger(100, 1000);
// Bigint representation of a pair of longs (100, 1000)
var reverse = BigInteger.valueOf(100)
.add(BigInteger.valueOf(1000).multiply(BigInteger.ONE.shiftLeft(64)));
assertEquals(reverse, bigint);
assertArrayEquals(bytes, UInt128.asBytes(bigint));
}
@Test
public void testAsBigIntegerFromBytes() {
var bigint = UInt128.asBigInteger(bytes);
assertEquals(UInt128.asBigInteger(100, 1000), bigint);
assertArrayEquals(bytes, UInt128.asBytes(bigint));
}
@Test(expected = NullPointerException.class)
public void testAsBigIntegerNull() {
@SuppressWarnings("unused")
var nop = UInt128.asBigInteger(null);
assert false;
}
@Test(expected = IllegalArgumentException.class)
public void testAsBigIntegerInvalid() {
byte[] bytes = new byte[] {1, 2, 3, 4, 5, 6};
@SuppressWarnings("unused")
var nop = UInt128.asBigInteger(bytes);
assert false;
}
@Test
public void testAsBigIntegerUnsigned() {
// @bitCast(u128, [2]i64{ -100, -1000 }) == 340282366920938445035077277795926146972
final var expected = new BigInteger("340282366920938445035077277795926146972");
assertEquals(expected, UInt128.asBigInteger(-100, -1000));
assertArrayEquals(UInt128.asBytes(expected), UInt128.asBytes(-100, -1000));
}
@Test
public void testAsBigIntegerZero() {
assertSame(BigInteger.ZERO, UInt128.asBigInteger(0, 0));
assertSame(BigInteger.ZERO, UInt128.asBigInteger(new byte[16]));
assertArrayEquals(new byte[16], UInt128.asBytes(BigInteger.ZERO));
}
@Test
public void testLittleEndian() {
// Reference test:
// https://github.com/microsoft/windows-rs/blob/f19edde93252381b7a1789bf856a3a67df23f6db/crates/tests/core/tests/guid.rs#L25-L31
final var bytes_expected = new byte[] {(byte) 0x8f, (byte) 0x8c, (byte) 0x2b, (byte) 0x05,
(byte) 0xa4, (byte) 0x53, (byte) 0x3a, (byte) 0x82, (byte) 0xfe, (byte) 0x42,
(byte) 0xd2, (byte) 0xc0, (byte) 0xef, (byte) 0x3f, (byte) 0xd6, (byte) 0x1f,};
final var u128 = UInt128.asBytes(Long.parseUnsignedLong("823a53a4052b8c8f", 16),
Long.parseUnsignedLong("1fd63fefc0d242fe", 16));
final var decimal_expected = new BigInteger("1fd63fefc0d242fe823a53a4052b8c8f", 16);
final var uuid_expected = UUID.fromString("1fd63fef-c0d2-42fe-823a-53a4052b8c8f");
assertEquals(decimal_expected, UInt128.asBigInteger(u128));
assertEquals(decimal_expected, UInt128.asBigInteger(bytes_expected));
assertEquals(decimal_expected, UInt128.asBigInteger(UInt128.asBytes(uuid_expected)));
assertEquals(uuid_expected, UInt128.asUUID(u128));
assertEquals(uuid_expected, UInt128.asUUID(bytes_expected));
assertEquals(uuid_expected, UInt128.asUUID(UInt128.asBytes(decimal_expected)));
assertArrayEquals(bytes_expected, u128);
assertArrayEquals(bytes_expected, UInt128.asBytes(uuid_expected));
assertArrayEquals(bytes_expected, UInt128.asBytes(decimal_expected));
}
@Test
public void testID() throws Exception {
{
// Generate IDs, sleeping for ~1ms occasionally to test intra-millisecond monotonicity.
var idA = UInt128.asBigInteger(UInt128.id());
for (int i = 0; i < 1_000_000; i++) {
if (i % 10_000 == 0) {
Thread.sleep(1);
}
var idB = UInt128.asBigInteger(UInt128.id());
assertTrue(idB.compareTo(idA) > 0);
// Use the generated ID as the new reference point for the next loop.
idA = idB;
}
}
final var threadExceptions = new Exception[100];
final var latchStart = new CountDownLatch(threadExceptions.length);
final var latchFinish = new CountDownLatch(threadExceptions.length);
for (int i = 0; i < threadExceptions.length; i++) {
final int threadIndex = i;
new Thread(() -> {
try {
// Wait for all threads to spawn before starting.
latchStart.countDown();
latchStart.await();
// Same as serial test above, but with smaller bounds.
var idA = UInt128.asBigInteger(UInt128.id());
for (int j = 0; j < 10_000; j++) {
if (j % 1000 == 0) {
Thread.sleep(1);
}
var idB = UInt128.asBigInteger(UInt128.id());
assertTrue(idB.compareTo(idA) > 0);
idA = idB;
}
} catch (Exception e) {
threadExceptions[threadIndex] = e; // Propagate exceptions to main thread.
} finally {
latchFinish.countDown(); // Make sure to unblock the main thread.
}
}).start();
}
latchFinish.await();
for (var exception : threadExceptions) {
if (exception != null)
throw exception;
}
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/AccountBalanceTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import org.junit.Test;
public class AccountBalanceTest {
@Test
public void testDefaultValues() {
final var balances = new AccountBalanceBatch(1);
balances.add();
assertEquals(0L, balances.getTimestamp());
assertEquals(BigInteger.ZERO, balances.getDebitsPending());
assertEquals(0L, balances.getDebitsPending(UInt128.LeastSignificant));
assertEquals(0L, balances.getDebitsPending(UInt128.MostSignificant));
assertEquals(BigInteger.ZERO, balances.getDebitsPosted());
assertEquals(0L, balances.getDebitsPosted(UInt128.LeastSignificant));
assertEquals(0L, balances.getDebitsPosted(UInt128.MostSignificant));
assertEquals(BigInteger.ZERO, balances.getCreditsPending());
assertEquals(0L, balances.getCreditsPending(UInt128.LeastSignificant));
assertEquals(0L, balances.getCreditsPending(UInt128.MostSignificant));
assertEquals(BigInteger.ZERO, balances.getCreditsPosted());
assertEquals(0L, balances.getCreditsPosted(UInt128.LeastSignificant));
assertEquals(0L, balances.getCreditsPosted(UInt128.MostSignificant));
assertArrayEquals(new byte[56], balances.getReserved());
}
@Test
public void testCreditsPending() {
final var balances = new AccountBalanceBatch(1);
balances.add();
final var value = new BigInteger("123456789012345678901234567890");
balances.setCreditsPending(value);
assertEquals(value, balances.getCreditsPending());
}
@Test
public void testCreditsPendingLong() {
final var balances = new AccountBalanceBatch(1);
balances.add();
balances.setCreditsPending(999);
assertEquals(BigInteger.valueOf(999), balances.getCreditsPending());
balances.setCreditsPending(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), balances.getCreditsPending());
assertEquals(999L, balances.getCreditsPending(UInt128.LeastSignificant));
assertEquals(1L, balances.getCreditsPending(UInt128.MostSignificant));
}
@Test
public void testCreditsPosted() {
final var balances = new AccountBalanceBatch(1);
balances.add();
final var value = new BigInteger("123456789012345678901234567890");
balances.setCreditsPosted(value);
assertEquals(value, balances.getCreditsPosted());
}
@Test
public void testCreditsPostedLong() {
final var balances = new AccountBalanceBatch(1);
balances.add();
balances.setCreditsPosted(999);
assertEquals(BigInteger.valueOf(999), balances.getCreditsPosted());
balances.setCreditsPosted(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), balances.getCreditsPosted());
assertEquals(999L, balances.getCreditsPosted(UInt128.LeastSignificant));
assertEquals(1L, balances.getCreditsPosted(UInt128.MostSignificant));
}
@Test
public void testDebitsPosted() {
final var balances = new AccountBalanceBatch(1);
balances.add();
final var value = new BigInteger("123456789012345678901234567890");
balances.setDebitsPosted(value);
assertEquals(value, balances.getDebitsPosted());
}
@Test
public void testDebitsPostedLong() {
final var balances = new AccountBalanceBatch(1);
balances.add();
balances.setDebitsPosted(999);
assertEquals(BigInteger.valueOf(999), balances.getDebitsPosted());
balances.setDebitsPosted(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), balances.getDebitsPosted());
assertEquals(999L, balances.getDebitsPosted(UInt128.LeastSignificant));
assertEquals(1L, balances.getDebitsPosted(UInt128.MostSignificant));
}
@Test
public void testDebitsPending() {
final var balances = new AccountBalanceBatch(1);
balances.add();
final var value = new BigInteger("123456789012345678901234567890");
balances.setDebitsPending(value);
assertEquals(value, balances.getDebitsPending());
}
@Test
public void testDebitsPendingLong() {
var balances = new AccountBalanceBatch(1);
balances.add();
balances.setDebitsPending(999);
assertEquals(BigInteger.valueOf(999), balances.getDebitsPending());
balances.setDebitsPending(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), balances.getDebitsPending());
assertEquals(999L, balances.getDebitsPending(UInt128.LeastSignificant));
assertEquals(1L, balances.getDebitsPending(UInt128.MostSignificant));
}
@Test
public void testReserved() {
var balances = new AccountBalanceBatch(1);
balances.add();
final var bytes = new byte[56];
for (byte i = 0; i < 56; i++) {
bytes[i] = i;
}
balances.setReserved(bytes);
assertArrayEquals(bytes, balances.getReserved());
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/AccountTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import org.junit.Test;
public class AccountTest {
@Test
public void testDefaultValues() {
var accounts = new AccountBatch(1);
accounts.add();
assertEquals(0L, accounts.getId(UInt128.LeastSignificant));
assertEquals(0L, accounts.getId(UInt128.MostSignificant));
assertEquals(BigInteger.ZERO, accounts.getDebitsPosted());
assertEquals(BigInteger.ZERO, accounts.getDebitsPending());
assertEquals(BigInteger.ZERO, accounts.getCreditsPosted());
assertEquals(BigInteger.ZERO, accounts.getCreditsPending());
assertEquals(0L, accounts.getUserData128(UInt128.LeastSignificant));
assertEquals(0L, accounts.getUserData128(UInt128.MostSignificant));
assertEquals(0L, accounts.getUserData64());
assertEquals(0, accounts.getUserData32());
assertEquals(0, accounts.getLedger());
assertEquals(AccountFlags.NONE, accounts.getFlags());
assertEquals(0L, accounts.getTimestamp());
}
@Test
public void testId() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setId(100, 200);
assertEquals(100L, accounts.getId(UInt128.LeastSignificant));
assertEquals(200L, accounts.getId(UInt128.MostSignificant));
}
@Test
public void testIdLong() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setId(100);
assertEquals(100L, accounts.getId(UInt128.LeastSignificant));
assertEquals(0L, accounts.getId(UInt128.MostSignificant));
}
@Test
public void testIdAsBytes() {
var accounts = new AccountBatch(1);
accounts.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
accounts.setId(id);
assertArrayEquals(id, accounts.getId());
}
public void testIdNull() {
byte[] id = null;
var accounts = new AccountBatch(1);
accounts.add();
accounts.setId(id);
assertArrayEquals(new byte[16], accounts.getId());
}
@Test(expected = IllegalArgumentException.class)
public void testIdInvalid() {
var accounts = new AccountBatch(1);
accounts.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
accounts.setId(id);
assert false;
}
@Test
public void testCreditsPending() {
var accounts = new AccountBatch(1);
accounts.add();
final var value = new BigInteger("123456789012345678901234567890");
accounts.setCreditsPending(value);
assertEquals(value, accounts.getCreditsPending());
}
@Test
public void testCreditsPendingLong() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setCreditsPending(999);
assertEquals(BigInteger.valueOf(999), accounts.getCreditsPending());
accounts.setCreditsPending(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), accounts.getCreditsPending());
assertEquals(999L, accounts.getCreditsPending(UInt128.LeastSignificant));
assertEquals(1L, accounts.getCreditsPending(UInt128.MostSignificant));
}
@Test
public void testCreditsPosted() {
var accounts = new AccountBatch(1);
accounts.add();
final var value = new BigInteger("123456789012345678901234567890");
accounts.setCreditsPosted(value);
assertEquals(value, accounts.getCreditsPosted());
}
@Test
public void testCreditsPostedLong() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setCreditsPosted(999);
assertEquals(BigInteger.valueOf(999), accounts.getCreditsPosted());
accounts.setCreditsPosted(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), accounts.getCreditsPosted());
assertEquals(999L, accounts.getCreditsPosted(UInt128.LeastSignificant));
assertEquals(1L, accounts.getCreditsPosted(UInt128.MostSignificant));
}
@Test
public void testDebitsPosted() {
var accounts = new AccountBatch(1);
accounts.add();
final var value = new BigInteger("123456789012345678901234567890");
accounts.setDebitsPosted(value);
assertEquals(value, accounts.getDebitsPosted());
}
@Test
public void testDebitsPostedLong() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setDebitsPosted(999);
assertEquals(BigInteger.valueOf(999), accounts.getDebitsPosted());
accounts.setDebitsPosted(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), accounts.getDebitsPosted());
assertEquals(999L, accounts.getDebitsPosted(UInt128.LeastSignificant));
assertEquals(1L, accounts.getDebitsPosted(UInt128.MostSignificant));
}
@Test
public void testDebitsPending() {
var accounts = new AccountBatch(1);
accounts.add();
final var value = new BigInteger("123456789012345678901234567890");
accounts.setDebitsPending(value);
assertEquals(value, accounts.getDebitsPending());
}
@Test
public void testDebitsPendingLong() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setDebitsPending(999);
assertEquals(BigInteger.valueOf(999), accounts.getDebitsPending());
accounts.setDebitsPending(999, 1);
assertEquals(UInt128.asBigInteger(999, 1), accounts.getDebitsPending());
assertEquals(999L, accounts.getDebitsPending(UInt128.LeastSignificant));
assertEquals(1L, accounts.getDebitsPending(UInt128.MostSignificant));
}
@Test
public void testUserData128Long() {
var accounts = new AccountBatch(2);
accounts.add();
accounts.setUserData128(100);
assertEquals(100L, accounts.getUserData128(UInt128.LeastSignificant));
assertEquals(0L, accounts.getUserData128(UInt128.MostSignificant));
}
@Test
public void testUserData128() {
var accounts = new AccountBatch(2);
accounts.add();
accounts.setUserData128(100, 200);
assertEquals(100L, accounts.getUserData128(UInt128.LeastSignificant));
assertEquals(200L, accounts.getUserData128(UInt128.MostSignificant));
}
@Test
public void testUserData128AsBytes() {
var accounts = new AccountBatch(1);
accounts.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
accounts.setUserData128(id);
assertArrayEquals(id, accounts.getUserData128());
}
@Test
public void testUserData128Null() {
var accounts = new AccountBatch(1);
accounts.add();
byte[] userData = null;
accounts.setUserData128(userData);
assertEquals(0L, accounts.getUserData128(UInt128.LeastSignificant));
assertEquals(0L, accounts.getUserData128(UInt128.MostSignificant));
}
@Test(expected = IllegalArgumentException.class)
public void testUserData128Invalid() {
var accounts = new AccountBatch(1);
accounts.add();
var id = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
accounts.setUserData128(id);
assert false;
}
@Test
public void testUserData64() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setUserData64(1000L);
assertEquals(1000L, accounts.getUserData64());
}
@Test
public void testUserData32() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setUserData32(100);
assertEquals(100, accounts.getUserData32());
}
@Test
public void testLedger() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setLedger(200);
assertEquals(200, accounts.getLedger());
}
@Test
public void testCode() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setCode(30);
assertEquals(30, accounts.getCode());
}
@Test
public void testCodeUnsignedValue() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setCode(60000);
assertEquals(60000, accounts.getCode());
}
@Test(expected = IllegalArgumentException.class)
public void testCodeNegative() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setCode(-1);
}
@Test(expected = IllegalArgumentException.class)
public void testCodeOverflow() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setCode(Integer.MAX_VALUE);
}
@Test
public void testReserved() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setReserved(0);
assertEquals(0, accounts.getReserved());
}
@Test
public void testFlags() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setFlags(AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS | AccountFlags.LINKED);
assertEquals((int) (AccountFlags.CREDITS_MUST_NOT_EXCEED_DEBITS | AccountFlags.LINKED),
accounts.getFlags());
}
@Test
public void testFlagsUnsignedValue() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setFlags(60000);
assertEquals(60000, accounts.getFlags());
}
@Test(expected = IllegalArgumentException.class)
public void testFlagsNegative() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setFlags(-1);
}
@Test(expected = IllegalArgumentException.class)
public void testFlagsOverflow() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setFlags(Integer.MAX_VALUE);
}
@Test
public void testTimestamp() {
var accounts = new AccountBatch(1);
accounts.add();
accounts.setTimestamp(1234567890);
assertEquals((long) 1234567890, accounts.getTimestamp());
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/CreateTransferResultTest.java | package com.tigerbeetle;
import org.junit.Assert;
import org.junit.Test;
public class CreateTransferResultTest {
@Test
public void testFromValue() {
var value = CreateTransferResult.DebitAccountIdMustNotBeIntMax.value;
Assert.assertEquals(CreateTransferResult.DebitAccountIdMustNotBeIntMax,
CreateTransferResult.fromValue(value));
}
@Test
public void testOrdinal() {
for (final var expected : CreateTransferResult.values()) {
final var actual = CreateTransferResult.fromValue(expected.value);
Assert.assertEquals(expected, actual);
}
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidValue() {
var value = 999;
CreateTransferResult.fromValue(value);
}
@Test(expected = IllegalArgumentException.class)
public void testNegativeValue() {
var value = -1;
CreateTransferResult.fromValue(value);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/TransferFlagsTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class TransferFlagsTest {
@Test
public void testFlags() {
assertTrue(TransferFlags.hasLinked(TransferFlags.LINKED));
assertTrue(TransferFlags.hasLinked(TransferFlags.LINKED | TransferFlags.PENDING));
assertTrue(TransferFlags
.hasLinked(TransferFlags.LINKED | TransferFlags.POST_PENDING_TRANSFER));
assertTrue(TransferFlags.hasPending(TransferFlags.PENDING));
assertTrue(TransferFlags.hasPending(TransferFlags.PENDING | TransferFlags.LINKED));
assertTrue(TransferFlags.hasPending(TransferFlags.LINKED | TransferFlags.PENDING));
assertTrue(TransferFlags.hasPostPendingTransfer(TransferFlags.POST_PENDING_TRANSFER));
assertTrue(TransferFlags.hasPostPendingTransfer(
TransferFlags.POST_PENDING_TRANSFER | TransferFlags.LINKED));
assertTrue(TransferFlags.hasPostPendingTransfer(
TransferFlags.POST_PENDING_TRANSFER | TransferFlags.PENDING));
assertTrue(TransferFlags.hasVoidPendingTransfer(TransferFlags.VOID_PENDING_TRANSFER));
assertTrue(TransferFlags.hasVoidPendingTransfer(
TransferFlags.VOID_PENDING_TRANSFER | TransferFlags.LINKED));
assertTrue(TransferFlags.hasVoidPendingTransfer(
TransferFlags.VOID_PENDING_TRANSFER | TransferFlags.PENDING));
assertFalse(TransferFlags.hasLinked(TransferFlags.NONE));
assertFalse(TransferFlags.hasLinked(TransferFlags.POST_PENDING_TRANSFER));
assertFalse(TransferFlags
.hasLinked(TransferFlags.PENDING | TransferFlags.POST_PENDING_TRANSFER));
assertFalse(TransferFlags.hasPending(TransferFlags.NONE));
assertFalse(TransferFlags.hasPending(TransferFlags.POST_PENDING_TRANSFER));
assertFalse(TransferFlags
.hasPending(TransferFlags.LINKED | TransferFlags.POST_PENDING_TRANSFER));
assertFalse(TransferFlags.hasVoidPendingTransfer(TransferFlags.NONE));
assertFalse(TransferFlags.hasVoidPendingTransfer(TransferFlags.LINKED));
assertFalse(
TransferFlags.hasVoidPendingTransfer(TransferFlags.LINKED | TransferFlags.PENDING));
assertFalse(TransferFlags.hasPostPendingTransfer(TransferFlags.NONE));
assertFalse(TransferFlags.hasPostPendingTransfer(TransferFlags.LINKED));
assertFalse(TransferFlags.hasPostPendingTransfer(
TransferFlags.LINKED | TransferFlags.VOID_PENDING_TRANSFER));
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/CreateAccountResultTest.java | package com.tigerbeetle;
import org.junit.Assert;
import org.junit.Test;
public class CreateAccountResultTest {
@Test
public void testFromValue() {
final var value = CreateAccountResult.Exists.value;
Assert.assertEquals(CreateAccountResult.Exists, CreateAccountResult.fromValue(value));
}
@Test
public void testOrdinal() {
for (final var expected : CreateAccountResult.values()) {
final var actual = CreateAccountResult.fromValue(expected.value);
Assert.assertEquals(expected, actual);
}
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidValue() {
var value = 999;
CreateAccountResult.fromValue(value);
}
@Test(expected = IllegalArgumentException.class)
public void testNegativeValue() {
var value = -1;
CreateAccountResult.fromValue(value);
}
}
|
0 | repos/tigerbeetle/src/clients/java/src/test/java/com | repos/tigerbeetle/src/clients/java/src/test/java/com/tigerbeetle/QueryFilterTest.java | package com.tigerbeetle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class QueryFilterTest {
@Test
public void testDefaultValues() {
final var queryFilter = new QueryFilter();
assertEquals(0L, queryFilter.getUserData128(UInt128.LeastSignificant));
assertEquals(0L, queryFilter.getUserData128(UInt128.MostSignificant));
assertEquals(0L, queryFilter.getUserData64());
assertEquals(0, queryFilter.getUserData32());
assertEquals(0, queryFilter.getLedger());
assertEquals(0, queryFilter.getCode());
assertEquals(0L, queryFilter.getTimestampMin());
assertEquals(0L, queryFilter.getTimestampMax());
assertEquals(0, queryFilter.getLimit());
assertEquals(false, queryFilter.getReversed());
}
@Test
public void testUserData128() {
final var queryFilter = new QueryFilter();
queryFilter.setUserData128(100, 200);
assertEquals(100L, queryFilter.getUserData128(UInt128.LeastSignificant));
assertEquals(200L, queryFilter.getUserData128(UInt128.MostSignificant));
}
@Test
public void testUserData128Long() {
final var queryFilter = new QueryFilter();
queryFilter.setUserData128(100);
assertEquals(100L, queryFilter.getUserData128(UInt128.LeastSignificant));
assertEquals(0L, queryFilter.getUserData128(UInt128.MostSignificant));
}
@Test
public void testUserData128AsBytes() {
final var queryFilter = new QueryFilter();
final var data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
queryFilter.setUserData128(data);
assertArrayEquals(data, queryFilter.getUserData128());
}
@Test
public void testUserData128Null() {
final var queryFilter = new QueryFilter();
final byte[] data = null;
queryFilter.setUserData128(data);
assertArrayEquals(new byte[16], queryFilter.getUserData128());
}
@Test(expected = IllegalArgumentException.class)
public void testUserData128Invalid() {
final var queryFilter = new QueryFilter();
final var data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
queryFilter.setUserData128(data);
assert false;
}
@Test
public void testUserData64() {
final var queryFilter = new QueryFilter();
queryFilter.setUserData64(100L);
assertEquals(100L, queryFilter.getUserData64());
}
@Test
public void testUserData32() {
final var queryFilter = new QueryFilter();
queryFilter.setUserData32(10);
assertEquals(10, queryFilter.getUserData32());
}
@Test
public void testLedger() {
final var queryFilter = new QueryFilter();
queryFilter.setLedger(99);
assertEquals(99, queryFilter.getLedger());
}
@Test
public void testCode() {
final var queryFilter = new QueryFilter();
queryFilter.setCode(1);
assertEquals(1, queryFilter.getCode());
}
@Test
public void testTimestampMin() {
final var queryFilter = new QueryFilter();
queryFilter.setTimestampMin(100L);
assertEquals(100, queryFilter.getTimestampMin());
}
@Test
public void testTimestampMax() {
final var queryFilter = new QueryFilter();
queryFilter.setTimestampMax(100L);
assertEquals(100, queryFilter.getTimestampMax());
}
@Test
public void testLimit() {
final var queryFilter = new QueryFilter();
queryFilter.setLimit(30);
assertEquals(30, queryFilter.getLimit());
}
@Test
public void testFlags() {
final var queryFilter = new QueryFilter();
assertEquals(false, queryFilter.getReversed());
queryFilter.setReversed(true);
assertEquals(true, queryFilter.getReversed());
queryFilter.setReversed(false);
assertEquals(false, queryFilter.getReversed());
}
@Test
public void testReserved() {
final var queryFilter = new QueryFilterBatch(1);
queryFilter.add();
// Empty array:
final var bytes = new byte[6];
assertArrayEquals(new byte[6], queryFilter.getReserved());
// Null == empty array:
queryFilter.setReserved(null);
for (byte i = 0; i < 6; i++) {
bytes[i] = i;
}
queryFilter.setReserved(bytes);
assertArrayEquals(bytes, queryFilter.getReserved());
}
@Test(expected = IllegalArgumentException.class)
public void testReservedInvalid() {
final var queryFilter = new QueryFilterBatch(1);
queryFilter.add();
queryFilter.setReserved(new byte[7]);
assert false;
}
}
|
0 | repos/tigerbeetle/src/clients/java | repos/tigerbeetle/src/clients/java/.vscode/settings.json | {
"java.project.sourcePaths": [
"src/main/java",
"src/test/java",
],
"java.configuration.updateBuildConfiguration": "automatic",
"java.format.enabled": true,
"java.format.settings.url": "eclipse-formatter.xml",
"cSpell.words": [
"tigerbeetle"
],
} |
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/dotnet/ci.zig | const std = @import("std");
const builtin = @import("builtin");
const log = std.log;
const assert = std.debug.assert;
const flags = @import("../../flags.zig");
const fatal = flags.fatal;
const Shell = @import("../../shell.zig");
const TmpTigerBeetle = @import("../../testing/tmp_tigerbeetle.zig");
pub fn tests(shell: *Shell, gpa: std.mem.Allocator) !void {
assert(shell.file_exists("TigerBeetle.sln"));
try shell.zig("build clients:dotnet -Drelease -Dconfig=production", .{});
try shell.zig("build -Drelease -Dconfig=production", .{});
try shell.exec("dotnet restore", .{});
try shell.exec("dotnet format --no-restore --verify-no-changes", .{});
// Unit tests.
try shell.exec("dotnet build --no-restore --configuration Release", .{});
// Disable coverage on CI, as it is flaky, see
// <https://github.com/coverlet-coverage/coverlet/issues/865>
try shell.exec(
\\dotnet test --no-restore
\\ /p:CollectCoverage=false
\\ /p:Threshold={threshold}
\\ /p:ThresholdType={threshold_type}
, .{
.threshold = "\"95,85,95\"", // sic, coverlet wants quotes inside the argument
.threshold_type = "\"line,branch,method\"",
});
// Integration tests.
inline for (.{ "basic", "two-phase", "two-phase-many", "walkthrough" }) |sample| {
log.info("testing sample '{s}'", .{sample});
try shell.pushd("./samples/" ++ sample);
defer shell.popd();
var tmp_beetle = try TmpTigerBeetle.init(gpa, .{});
defer tmp_beetle.deinit(gpa);
errdefer tmp_beetle.log_stderr();
try shell.env.put("TB_ADDRESS", tmp_beetle.port_str.slice());
try shell.exec("dotnet run", .{});
}
// Container smoke tests.
if (builtin.target.os.tag == .linux) {
// Here, we want to check that our package does not break horrible on upstream containers
// due to missing runtime dependencies, mismatched glibc ABI and similar issues.
//
// We don't necessary want to be able to _build_ code inside such a container, we only
// need to check that pre-built code runs successfully. So, build a package on host,
// mount it inside the container and smoke test.
//
// We run an sh script inside a container, because it is trivial. If it grows larger,
// we should consider running a proper zig program inside.
try shell.exec("dotnet pack --configuration Release", .{});
const image_tags = .{
"8.0", "8.0-alpine",
};
inline for (image_tags) |image_tag| {
const image = "mcr.microsoft.com/dotnet/sdk:" ++ image_tag;
log.info("testing docker image: '{s}'", .{image});
for (0..5) |attempt| {
if (attempt > 0) std.time.sleep(1 * std.time.ns_per_min);
if (shell.exec("docker image pull {image}", .{ .image = image })) {
break;
} else |_| {}
}
try shell.exec(
\\docker run
\\--security-opt seccomp=unconfined
\\--volume ./TigerBeetle/bin/Release:/host
\\{image}
\\sh
\\-c {script}
, .{
.image = image,
.script =
\\set -ex
\\mkdir test-project && cd test-project
\\dotnet nuget add source /host
\\dotnet new console
\\dotnet add package tigerbeetle --source /host > /dev/null
\\cat <<EOF > Program.cs
\\using System;
\\using TigerBeetle;
\\public class Program {
\\ public static void Main() {
\\ new Client(UInt128.Zero, new [] {"3001"}).Dispose();
\\ Console.WriteLine("SUCCESS");
\\ }
\\}
\\EOF
\\dotnet run
,
});
}
}
}
pub fn validate_release(shell: *Shell, gpa: std.mem.Allocator, options: struct {
version: []const u8,
tigerbeetle: []const u8,
}) !void {
var tmp_beetle = try TmpTigerBeetle.init(gpa, .{
.prebuilt = options.tigerbeetle,
});
defer tmp_beetle.deinit(gpa);
errdefer tmp_beetle.log_stderr();
try shell.env.put("TB_ADDRESS", tmp_beetle.port_str.slice());
try shell.exec("dotnet new console", .{});
try shell.exec("dotnet add package tigerbeetle --version {version}", .{
.version = options.version,
});
try Shell.copy_path(
shell.project_root,
"src/clients/dotnet/samples/basic/Program.cs",
shell.cwd,
"Program.cs",
);
try shell.exec("dotnet run", .{});
}
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/dotnet/dotnet_bindings.zig | const std = @import("std");
const vsr = @import("vsr");
const assert = std.debug.assert;
const stdx = vsr.stdx;
const tb = vsr.tigerbeetle;
const tb_client = vsr.tb_client;
const TypeMapping = struct {
name: []const u8,
visibility: enum { public, internal },
private_fields: []const []const u8 = &.{},
readonly_fields: []const []const u8 = &.{},
docs_link: ?[]const u8 = null,
constants: []const u8 = "",
pub fn is_private(comptime self: @This(), name: []const u8) bool {
inline for (self.private_fields) |field| {
if (std.mem.eql(u8, field, name)) {
return true;
}
} else return false;
}
pub fn is_read_only(comptime self: @This(), name: []const u8) bool {
inline for (self.readonly_fields) |field| {
if (std.mem.eql(u8, field, name)) {
return true;
}
} else return false;
}
};
const type_mappings = .{
.{ tb.AccountFlags, TypeMapping{
.name = "AccountFlags",
.visibility = .public,
.private_fields = &.{"padding"},
.docs_link = "reference/account#flags",
} },
.{ tb.TransferFlags, TypeMapping{
.name = "TransferFlags",
.visibility = .public,
.private_fields = &.{"padding"},
.docs_link = "reference/transfer#flags",
} },
.{ tb.AccountFilterFlags, TypeMapping{
.name = "AccountFilterFlags",
.visibility = .public,
.private_fields = &.{"padding"},
.docs_link = "reference/account-filter#flags",
} },
.{ tb.QueryFilterFlags, TypeMapping{
.name = "QueryFilterFlags",
.visibility = .public,
.private_fields = &.{"padding"},
.docs_link = "reference/query-filter#flags",
} },
.{ tb.Account, TypeMapping{
.name = "Account",
.visibility = .public,
.private_fields = &.{"reserved"},
.readonly_fields = &.{
"debits_pending",
"credits_pending",
"debits_posted",
"credits_posted",
},
.docs_link = "reference/account#",
} },
.{
tb.Transfer, TypeMapping{
.name = "Transfer",
.visibility = .public,
.private_fields = &.{"reserved"},
.readonly_fields = &.{},
.docs_link = "reference/transfer#",
.constants =
\\ public static UInt128 AmountMax => UInt128.MaxValue;
\\
,
},
},
.{ tb.CreateAccountResult, TypeMapping{
.name = "CreateAccountResult",
.visibility = .public,
.docs_link = "reference/requests/create_accounts#",
} },
.{ tb.CreateTransferResult, TypeMapping{
.name = "CreateTransferResult",
.visibility = .public,
.docs_link = "reference/requests/create_transfers#",
} },
.{ tb.CreateAccountsResult, TypeMapping{
.name = "CreateAccountsResult",
.visibility = .public,
} },
.{ tb.CreateTransfersResult, TypeMapping{
.name = "CreateTransfersResult",
.visibility = .public,
} },
.{ tb.AccountFilter, TypeMapping{
.name = "AccountFilter",
.visibility = .public,
.private_fields = &.{"reserved"},
.docs_link = "reference/account-filter#",
} },
.{ tb.AccountBalance, TypeMapping{
.name = "AccountBalance",
.visibility = .public,
.private_fields = &.{"reserved"},
.docs_link = "reference/account-balances#",
} },
.{ tb.QueryFilter, TypeMapping{
.name = "QueryFilter",
.visibility = .public,
.private_fields = &.{"reserved"},
.docs_link = "reference/query-filter#",
} },
.{ tb_client.tb_status_t, TypeMapping{
.name = "InitializationStatus",
.visibility = .public,
} },
.{ tb_client.tb_packet_status_t, TypeMapping{
.name = "PacketStatus",
.visibility = .public,
} },
.{ tb_client.tb_operation_t, TypeMapping{
.name = "TBOperation",
.visibility = .internal,
.private_fields = &.{ "reserved", "root", "register" },
} },
.{ tb_client.tb_packet_t, TypeMapping{
.name = "TBPacket",
.visibility = .internal,
.private_fields = &.{"reserved"},
} },
};
fn dotnet_type(comptime Type: type) []const u8 {
switch (@typeInfo(Type)) {
.Enum, .Struct => return comptime get_mapped_type_name(Type) orelse
@compileError("Type " ++ @typeName(Type) ++ " not mapped."),
.Int => |info| {
std.debug.assert(info.signedness == .unsigned);
return switch (info.bits) {
8 => "byte",
16 => "ushort",
32 => "uint",
64 => "ulong",
128 => "UInt128",
else => @compileError("invalid int type"),
};
},
.Optional => |info| switch (@typeInfo(info.child)) {
.Pointer => return dotnet_type(info.child),
else => @compileError("Unsupported optional type: " ++ @typeName(Type)),
},
.Pointer => |info| {
std.debug.assert(info.size != .Slice);
std.debug.assert(!info.is_allowzero);
return if (comptime get_mapped_type_name(info.child)) |name|
name ++ "*"
else
dotnet_type(info.child);
},
.Void, .Opaque => return "IntPtr",
else => @compileError("Unhandled type: " ++ @typeName(Type)),
}
}
fn get_mapped_type_name(comptime Type: type) ?[]const u8 {
inline for (type_mappings) |type_mapping| {
if (Type == type_mapping[0]) {
return type_mapping[1].name;
}
} else return null;
}
fn to_case(comptime input: []const u8, comptime case: enum { camel, pascal }) []const u8 {
// TODO(Zig): Cleanup when this is fixed after Zig 0.11.
// Without comptime blk, the compiler thinks slicing the output on return happens at runtime.
return comptime blk: {
var len: usize = 0;
var output: [input.len]u8 = undefined;
var iterator = std.mem.tokenize(u8, input, "_");
while (iterator.next()) |word| {
_ = std.ascii.lowerString(output[len..], word);
output[len] = std.ascii.toUpper(output[len]);
len += word.len;
}
output[0] = switch (case) {
.camel => std.ascii.toLower(output[0]),
.pascal => std.ascii.toUpper(output[0]),
};
break :blk stdx.comptime_slice(&output, len);
};
}
fn emit_enum(
buffer: *std.ArrayList(u8),
comptime Type: type,
comptime type_info: anytype,
comptime mapping: TypeMapping,
comptime int_type: []const u8,
) !void {
const is_packed_struct = @TypeOf(type_info) == std.builtin.Type.Struct;
if (is_packed_struct) {
assert(type_info.layout == .@"packed");
// Packed structs represented as Enum needs a Flags attribute:
try buffer.writer().print("[Flags]\n", .{});
}
try buffer.writer().print(
\\{s} enum {s} : {s}
\\{{
\\
, .{
@tagName(mapping.visibility),
mapping.name,
int_type,
});
if (is_packed_struct) {
// Packed structs represented as Enum needs a ZERO value:
try buffer.writer().print(
\\ None = 0,
\\
\\
, .{});
}
inline for (type_info.fields, 0..) |field, i| {
if (comptime mapping.is_private(field.name)) continue;
try emit_docs(buffer, mapping, field.name);
if (is_packed_struct) {
try buffer.writer().print(" {s} = 1 << {},\n\n", .{
to_case(field.name, .pascal),
i,
});
} else {
try buffer.writer().print(" {s} = {},\n\n", .{
to_case(field.name, .pascal),
@intFromEnum(@field(Type, field.name)),
});
}
}
try buffer.writer().print(
\\}}
\\
\\
, .{});
}
fn emit_struct(
buffer: *std.ArrayList(u8),
comptime type_info: anytype,
comptime mapping: TypeMapping,
comptime size: usize,
) !void {
try buffer.writer().print(
\\[StructLayout(LayoutKind.Sequential, Size = SIZE)]
\\{s} {s}struct {s}
\\{{
\\ public const int SIZE = {};
\\
\\{s}
\\
, .{
@tagName(mapping.visibility),
if (mapping.visibility == .internal) "unsafe " else "",
mapping.name,
size,
mapping.constants,
});
// Fixed len array are exposed as internal structs with stackalloc fields
// It's more efficient than exposing heap-allocated arrays using
// [MarshalAs(UnmanagedType.ByValArray)] attribute.
inline for (type_info.fields) |field| {
switch (@typeInfo(field.type)) {
.Array => |array| {
try buffer.writer().print(
\\ [StructLayout(LayoutKind.Sequential, Size = SIZE)]
\\ private unsafe struct {s}Data
\\ {{
\\ public const int SIZE = {};
\\
\\ private fixed byte raw[SIZE];
\\
\\ public byte[] GetData()
\\ {{
\\ fixed (void* ptr = raw)
\\ {{
\\ return new ReadOnlySpan<byte>(ptr, SIZE).ToArray();
\\ }}
\\ }}
\\
\\ public void SetData(byte[] value)
\\ {{
\\ if (value == null) throw new ArgumentNullException(nameof(value));
\\ if (value.Length != SIZE)
\\ {{
\\ throw new ArgumentException("Expected a byte[" + SIZE + "] array", nameof(value));
\\ }}
\\
\\ fixed (void* ptr = raw)
\\ {{
\\ value.CopyTo(new Span<byte>(ptr, SIZE));
\\ }}
\\ }}
\\ }}
\\
\\
, .{
to_case(field.name, .pascal),
array.len * @sizeOf(array.child),
});
},
else => {},
}
}
// Fields
inline for (type_info.fields) |field| {
const is_private = comptime mapping.is_private(field.name);
switch (@typeInfo(field.type)) {
.Array => try buffer.writer().print(
\\ {s} {s}Data {s};
\\
\\
,
.{
if (mapping.visibility == .internal and !is_private) "public" else "private",
to_case(field.name, .pascal),
to_case(field.name, .camel),
},
),
else => try buffer.writer().print(
\\ {s} {s} {s};
\\
\\
,
.{
if (mapping.visibility == .internal and !is_private) "public" else "private",
dotnet_type(field.type),
to_case(field.name, .camel),
},
),
}
}
if (mapping.visibility == .public) {
// Properties
inline for (type_info.fields) |field| {
try emit_docs(buffer, mapping, field.name);
const is_private = comptime mapping.is_private(field.name);
const is_read_only = comptime mapping.is_read_only(field.name);
switch (@typeInfo(field.type)) {
.Array => try buffer.writer().print(
\\ {s} byte[] {s} {{ get => {s}.GetData(); {s}set => {s}.SetData(value); }}
\\
\\
, .{
if (is_private) "internal" else "public",
to_case(field.name, .pascal),
to_case(field.name, .camel),
if (is_read_only and !is_private) "internal " else "",
to_case(field.name, .camel),
}),
else => try buffer.writer().print(
\\ {s} {s} {s} {{ get => {s}; {s}set => {s} = value; }}
\\
\\
, .{
if (is_private) "internal" else "public",
dotnet_type(field.type),
to_case(field.name, .pascal),
to_case(field.name, .camel),
if (is_read_only and !is_private) "internal " else "",
to_case(field.name, .camel),
}),
}
}
}
try buffer.writer().print(
\\}}
\\
\\
, .{});
}
fn emit_docs(buffer: anytype, comptime mapping: TypeMapping, comptime field: ?[]const u8) !void {
if (mapping.docs_link) |docs_link| {
try buffer.writer().print(
\\ /// <summary>
\\ /// https://docs.tigerbeetle.com/{s}{s}
\\ /// </summary>
\\
, .{
docs_link,
field orelse "",
});
}
}
pub fn generate_bindings(buffer: *std.ArrayList(u8)) !void {
@setEvalBranchQuota(100_000);
try buffer.writer().print(
\\//////////////////////////////////////////////////////////
\\// This file was auto-generated by dotnet_bindings.zig //
\\// Do not manually modify. //
\\//////////////////////////////////////////////////////////
\\
\\using System;
\\using System.Runtime.InteropServices;
\\
\\namespace TigerBeetle;
\\
\\
, .{});
// Emit C# declarations.
inline for (type_mappings) |type_mapping| {
const ZigType = type_mapping[0];
const mapping = type_mapping[1];
switch (@typeInfo(ZigType)) {
.Struct => |info| switch (info.layout) {
.auto => @compileError(
"Only packed or extern structs are supported: " ++ @typeName(ZigType),
),
.@"packed" => try emit_enum(
buffer,
ZigType,
info,
mapping,
comptime dotnet_type(
std.meta.Int(.unsigned, @bitSizeOf(ZigType)),
),
),
.@"extern" => try emit_struct(
buffer,
info,
mapping,
@sizeOf(ZigType),
),
},
.Enum => |info| try emit_enum(
buffer,
ZigType,
info,
mapping,
comptime dotnet_type(std.meta.Int(.unsigned, @bitSizeOf(ZigType))),
),
else => @compileError("Type cannot be represented: " ++ @typeName(ZigType)),
}
}
// Emit function declarations.
// TODO: use `std.meta.declaractions` and generate with pub + export functions.
// Zig 0.9.1 has `decl.data.Fn.arg_names` but it's currently/incorrectly a zero-sized slice.
try buffer.writer().print(
\\internal static class TBClient
\\{{
\\ private const string LIB_NAME = "tb_client";
\\
\\ [DllImport(LIB_NAME, CallingConvention = CallingConvention.Cdecl)]
\\ public static unsafe extern InitializationStatus tb_client_init(
\\ IntPtr* out_client,
\\ UInt128Extensions.UnsafeU128 cluster_id,
\\ byte* address_ptr,
\\ uint address_len,
\\ IntPtr on_completion_ctx,
\\ delegate* unmanaged[Cdecl]<IntPtr, IntPtr, TBPacket*, byte*, uint, void> on_completion_fn
\\ );
\\
\\ [DllImport(LIB_NAME, CallingConvention = CallingConvention.Cdecl)]
\\ public static unsafe extern InitializationStatus tb_client_init_echo(
\\ IntPtr* out_client,
\\ UInt128Extensions.UnsafeU128 cluster_id,
\\ byte* address_ptr,
\\ uint address_len,
\\ IntPtr on_completion_ctx,
\\ delegate* unmanaged[Cdecl]<IntPtr, IntPtr, TBPacket*, byte*, uint, void> on_completion_fn
\\ );
\\
\\ [DllImport(LIB_NAME, CallingConvention = CallingConvention.Cdecl)]
\\ public static unsafe extern void tb_client_submit(
\\ IntPtr client,
\\ TBPacket* packet
\\ );
\\
\\ [DllImport(LIB_NAME, CallingConvention = CallingConvention.Cdecl)]
\\ public static unsafe extern void tb_client_deinit(
\\ IntPtr client
\\ );
\\}}
\\
\\
, .{});
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var buffer = std.ArrayList(u8).init(allocator);
try generate_bindings(&buffer);
try std.io.getStdOut().writeAll(buffer.items);
}
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/dotnet/docs.zig | const builtin = @import("builtin");
const std = @import("std");
const assert = std.debug.assert;
const Docs = @import("../docs_types.zig").Docs;
pub const DotnetDocs = Docs{
.directory = "dotnet",
.markdown_name = "cs",
.extension = "cs",
.proper_name = ".NET",
.test_source_path = "",
.name = "tigerbeetle-dotnet",
.description =
\\The TigerBeetle client for .NET.
,
.prerequisites =
\\* .NET >= 8.0.
\\
\\And if you do not already have NuGet.org as a package
\\source, make sure to add it:
\\
\\```console
\\dotnet nuget add source https://api.nuget.org/v3/index.json -n nuget.org
\\```
,
.project_file_name = "",
.project_file = "",
.test_file_name = "Program",
.install_commands =
\\dotnet new console
\\dotnet add package tigerbeetle
,
.run_commands = "dotnet run",
.examples = "",
.client_object_documentation =
\\The `Client` class is thread-safe and for better performance, a
\\single instance should be shared between multiple concurrent
\\tasks. Multiple clients can be instantiated in case of connecting
\\to more than one TigerBeetle cluster.
,
.create_accounts_documentation =
\\The `UInt128` fields like `ID`, `UserData128`, `Amount` and
\\account balances have a few extension methods to make it easier
\\to convert 128-bit little-endian unsigned integers between
\\`BigInteger`, `byte[]`, and `Guid`.
\\
\\See the class [UInt128Extensions](/src/clients/dotnet/TigerBeetle/UInt128Extensions.cs)
\\for more details.
,
.account_flags_documentation =
\\To toggle behavior for an account, combine enum values stored in the
\\`AccountFlags` object with bitwise-or:
\\
\\* `AccountFlags.None`
\\* `AccountFlags.Linked`
\\* `AccountFlags.DebitsMustNotExceedCredits`
\\* `AccountFlags.CreditsMustNotExceedDebits`
\\* `AccountFlags.History`
,
.create_accounts_errors_documentation = "",
.create_transfers_documentation = "",
.create_transfers_errors_documentation = "",
.transfer_flags_documentation =
\\To toggle behavior for an account, combine enum values stored in the
\\`TransferFlags` object with bitwise-or:
\\
\\* `TransferFlags.None`
\\* `TransferFlags.Linked`
\\* `TransferFlags.Pending`
\\* `TransferFlags.PostPendingTransfer`
\\* `TransferFlags.VoidPendingTransfer`
,
};
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/dotnet/LICENSE.txt |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
|
0 | repos/tigerbeetle/src/clients | repos/tigerbeetle/src/clients/dotnet/README.md | ---
title: .NET
---
<!-- This file is generated by [/src/scripts/client_readmes.zig](/src/scripts/client_readmes.zig). -->
# tigerbeetle-dotnet
The TigerBeetle client for .NET.
## Prerequisites
Linux >= 5.6 is the only production environment we
support. But for ease of development we also support macOS and Windows.
* .NET >= 8.0.
And if you do not already have NuGet.org as a package
source, make sure to add it:
```console
dotnet nuget add source https://api.nuget.org/v3/index.json -n nuget.org
```
## Setup
First, create a directory for your project and `cd` into the directory.
Then, install the TigerBeetle client:
```console
dotnet new console
dotnet add package tigerbeetle
```
Now, create `Program.cs` and copy this into it:
```cs
using System;
using TigerBeetle;
// Validate import works.
Console.WriteLine("SUCCESS");
```
Finally, build and run:
```console
dotnet 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/dotnet/samples/basic/): Create two accounts and transfer an amount between them.
* [Two-Phase Transfer](/src/clients/dotnet/samples/two-phase/): Create two accounts and start a pending transfer between
them, then post the transfer.
* [Many Two-Phase Transfers](/src/clients/dotnet/samples/two-phase-many/): Create two accounts and start a number of pending transfer
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.
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`.
```cs
var tbAddress = Environment.GetEnvironmentVariable("TB_ADDRESS");
var clusterID = UInt128.Zero;
var addresses = new[] { tbAddress != null ? tbAddress : "3000" };
using (var client = new Client(clusterID, addresses))
{
// Use client
}
```
The `Client` class is thread-safe and for better performance, a
single instance should be shared between multiple concurrent
tasks. Multiple clients can be instantiated in case of connecting
to more than one TigerBeetle cluster.
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).
```cs
var accounts = new[] {
new Account
{
Id = 137,
UserData128 = Guid.NewGuid().ToUInt128(),
UserData64 = 1000,
UserData32 = 100,
Ledger = 1,
Code = 718,
Flags = AccountFlags.None,
},
};
var createAccountsError = client.CreateAccounts(accounts);
```
The `UInt128` fields like `ID`, `UserData128`, `Amount` and
account balances have a few extension methods to make it easier
to convert 128-bit little-endian unsigned integers between
`BigInteger`, `byte[]`, and `Guid`.
See the class [UInt128Extensions](/src/clients/dotnet/TigerBeetle/UInt128Extensions.cs)
for more details.
### 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, combine enum values stored in the
`AccountFlags` object with bitwise-or:
* `AccountFlags.None`
* `AccountFlags.Linked`
* `AccountFlags.DebitsMustNotExceedCredits`
* `AccountFlags.CreditsMustNotExceedDebits`
* `AccountFlags.History`
For example, to link two accounts where the first account
additionally has the `debits_must_not_exceed_credits` constraint:
```cs
var account0 = new Account { /* ... account values ... */ };
var account1 = new Account { /* ... account values ... */ };
account0.Flags = AccountFlags.Linked;
createAccountsError = client.CreateAccounts(new[] { account0, account1 });
```
### 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).
```cs
var account2 = new Account { /* ... account values ... */ };
var account3 = new Account { /* ... account values ... */ };
var account4 = new Account { /* ... account values ... */ };
createAccountsError = client.CreateAccounts(new[] { account2, account3, account4 });
foreach (var error in createAccountsError)
{
Console.WriteLine("Error creating account {0}: {1}", error.Index, error.Result);
return;
}
```
## 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.
```cs
accounts = client.LookupAccounts(new UInt128[] { 137, 138 });
```
## 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).
```cs
var transfers = new[] {
new Transfer
{
Id = 1,
DebitAccountId = 1,
CreditAccountId = 2,
Amount = 10,
UserData128 = 2000,
UserData64 = 200,
UserData32 = 2,
Timeout = 0,
Ledger = 1,
Code = 1,
Flags = TransferFlags.None,
}
};
var createTransfersError = client.CreateTransfers(transfers);
```
### 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).
```cs
foreach (var error in createTransfersError)
{
Console.WriteLine("Error creating account {0}: {1}", error.Index, error.Result);
return;
}
```
## Batching
TigerBeetle performance is maximized when you batch
API requests. The client does not do this automatically for
you. So, for example, you *can* insert 1 million transfers
one at a time like so:
```cs
foreach (var t in transfers)
{
createTransfersError = client.CreateTransfers(new[] { t });
// Error handling omitted.
}
```
But the insert rate will be a *fraction* of
potential. Instead, **always batch what you can**.
The maximum batch size is set in the TigerBeetle server. The default
is 8190.
```cs
var BATCH_SIZE = 8190;
for (int i = 0; i < transfers.Length; i += BATCH_SIZE)
{
var batchSize = BATCH_SIZE;
if (i + BATCH_SIZE > transfers.Length)
{
batchSize = transfers.Length - i;
}
createTransfersError = client.CreateTransfers(transfers[i..batchSize]);
// 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 an account, combine enum values stored in the
`TransferFlags` object with bitwise-or:
* `TransferFlags.None`
* `TransferFlags.Linked`
* `TransferFlags.Pending`
* `TransferFlags.PostPendingTransfer`
* `TransferFlags.VoidPendingTransfer`
For example, to link `transfer0` and `transfer1`:
```cs
var transfer0 = new Transfer { /* ... account values ... */ };
var transfer1 = new Transfer { /* ... account values ... */ };
transfer0.Flags = TransferFlags.Linked;
createTransfersError = client.CreateTransfers(new Transfer[] { transfer0, transfer1 });
```
### 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.
```cs
transfers = new Transfer[] { new Transfer {
Id = 2,
// Post the entire pending amount.
Amount = Transfer.AmountMax,
PendingId = 1,
Flags = TransferFlags.PostPendingTransfer,
}};
createTransfersError = client.CreateTransfers(transfers);
// 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.
```cs
transfers = new Transfer[] { new Transfer {
Id = 2,
PendingId = 1,
Flags = TransferFlags.PostPendingTransfer,
}};
createTransfersError = client.CreateTransfers(transfers);
// 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.
```cs
transfers = client.LookupTransfers(new UInt128[] { 1, 2 });
```
## 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.
```cs
var filter = new AccountFilter
{
AccountId = 2,
TimestampMin = 0, // No filter by Timestamp.
TimestampMax = 0, // No filter by Timestamp.
Limit = 10, // Limit to ten transfers at most.
Flags = AccountFilterFlags.Debits | // Include transfer from the debit side.
AccountFilterFlags.Credits | // Include transfer from the credit side.
AccountFilterFlags.Reversed, // Sort by timestamp in reverse-chronological order.
};
transfers = client.GetAccountTransfers(filter);
```
## 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.
```cs
filter = new AccountFilter
{
AccountId = 2,
TimestampMin = 0, // No filter by Timestamp.
TimestampMax = 0, // No filter by Timestamp.
Limit = 10, // Limit to ten balances at most.
Flags = AccountFilterFlags.Debits | // Include transfer from the debit side.
AccountFilterFlags.Credits | // Include transfer from the credit side.
AccountFilterFlags.Reversed, // Sort by timestamp in reverse-chronological order.
};
var account_balances = client.GetAccountBalances(filter);
```
## 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.
```cs
var query_filter = new QueryFilter
{
UserData128 = 1000, // Filter by UserData.
UserData64 = 100,
UserData32 = 10,
Code = 1, // Filter by Code.
Ledger = 0, // No filter by Ledger.
TimestampMin = 0, // No filter by Timestamp.
TimestampMax = 0, // No filter by Timestamp.
Limit = 10, // Limit to ten balances at most.
Flags = QueryFilterFlags.Reversed, // Sort by timestamp in reverse-chronological order.
};
var query_accounts = client.QueryAccounts(query_filter);
```
## 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.
```cs
query_filter = new QueryFilter
{
UserData128 = 1000, // Filter by UserData
UserData64 = 100,
UserData32 = 10,
Code = 1, // Filter by Code
Ledger = 0, // No filter by Ledger
TimestampMin = 0, // No filter by Timestamp.
TimestampMax = 0, // No filter by Timestamp.
Limit = 10, // Limit to ten balances at most.
Flags = QueryFilterFlags.Reversed, // Sort by timestamp in reverse-chronological order.
};
var query_transfers = client.QueryTransfers(query_filter);
```
## 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`.
```cs
var batch = new System.Collections.Generic.List<Transfer>();
// An individual transfer (successful):
batch.Add(new Transfer { Id = 1, /* ... rest of transfer ... */ });
// A chain of 4 transfers (the last transfer in the chain closes the chain with linked=false):
batch.Add(new Transfer { Id = 2, /* ... rest of transfer ... */ Flags = TransferFlags.Linked }); // Commit/rollback.
batch.Add(new Transfer { Id = 3, /* ... rest of transfer ... */ Flags = TransferFlags.Linked }); // Commit/rollback.
batch.Add(new Transfer { Id = 2, /* ... rest of transfer ... */ Flags = TransferFlags.Linked }); // Fail with exists
batch.Add(new Transfer { Id = 4, /* ... rest of transfer ... */ }); // Fail without committing
// An individual transfer (successful):
// This should not see any effect from the failed chain above.
batch.Add(new Transfer { Id = 2, /* ... rest of transfer ... */ });
// A chain of 2 transfers (the first transfer fails the chain):
batch.Add(new Transfer { Id = 2, /* ... rest of transfer ... */ Flags = TransferFlags.Linked });
batch.Add(new Transfer { Id = 3, /* ... rest of transfer ... */ });
// A chain of 2 transfers (successful):
batch.Add(new Transfer { Id = 3, /* ... rest of transfer ... */ Flags = TransferFlags.Linked });
batch.Add(new Transfer { Id = 4, /* ... rest of transfer ... */ });
createTransfersError = client.CreateTransfers(batch.ToArray());
// 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.
```cs
// First, load and import all accounts with their timestamps from the historical source.
var accountsBatch = new System.Collections.Generic.List<Account>();
for (var index = 0; index < historicalAccounts.Length; index++)
{
var account = historicalAccounts[index];
// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
account.Timestamp = historicalTimestamp;
// Set the account as `imported`.
account.Flags = AccountFlags.Imported;
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalAccounts.Length - 1)
{
account.Flags |= AccountFlags.Linked;
}
accountsBatch.Add(account);
}
createAccountsError = client.CreateAccounts(accountsBatch.ToArray());
// Error handling omitted.
// Then, load and import all transfers with their timestamps from the historical source.
var transfersBatch = new System.Collections.Generic.List<Transfer>();
for (var index = 0; index < historicalTransfers.Length; index++)
{
var transfer = historicalTransfers[index];
// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
transfer.Timestamp = historicalTimestamp;
// Set the account as `imported`.
transfer.Flags = TransferFlags.Imported;
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalTransfers.Length - 1)
{
transfer.Flags |= TransferFlags.Linked;
}
transfersBatch.Add(transfer);
}
createTransfersError = client.CreateTransfers(transfersBatch.ToArray());
// 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.
```
|
0 | repos/tigerbeetle/src/clients/dotnet | repos/tigerbeetle/src/clients/dotnet/TigerBeetle.Tests/IntegrationTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TigerBeetle.Tests;
[TestClass]
public class IntegrationTests
{
private static Account[] GenerateAccounts() => new[]
{
new Account
{
Id = ID.Create(),
UserData128 = 1000,
UserData64 = 1001,
UserData32 = 1002,
Flags = AccountFlags.None,
Ledger = 1,
Code = 1,
},
new Account
{
Id = ID.Create(),
UserData128 = 1000,
UserData64 = 1001,
UserData32 = 1002,
Flags = AccountFlags.None,
Ledger = 1,
Code = 2,
},
};
// Created by the test initializer:
private static TBServer server = null!;
private static Client client = null!;
[ClassInitialize]
public static void Initialize(TestContext _)
{
server = new TBServer();
client = new Client(0, new string[] { server.Address });
}
[ClassCleanup]
public static void Cleanup()
{
client.Dispose();
server.Dispose();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ConstructorWithNullReplicaAddresses()
{
string[]? addresses = null;
_ = new Client(0, addresses!);
}
[TestMethod]
public void ConstructorWithNullReplicaAddressElement()
{
try
{
var addresses = new string?[] { "3000", null };
_ = new Client(0, addresses!);
Assert.Fail();
}
catch (InitializationException exception)
{
Assert.AreEqual(InitializationStatus.AddressInvalid, exception.Status);
}
}
[TestMethod]
public void ConstructorWithEmptyReplicaAddresses()
{
try
{
_ = new Client(0, Array.Empty<string>());
Assert.Fail();
}
catch (InitializationException exception)
{
Assert.AreEqual(InitializationStatus.AddressInvalid, exception.Status);
}
}
[TestMethod]
public void ConstructorWithEmptyReplicaAddressElement()
{
try
{
_ = new Client(0, new string[] { "" });
Assert.Fail();
}
catch (InitializationException exception)
{
Assert.AreEqual(InitializationStatus.AddressInvalid, exception.Status);
}
}
[TestMethod]
public void ConstructorWithInvalidReplicaAddresses()
{
try
{
var addresses = Enumerable.Range(3000, 3100).Select(x => x.ToString()).ToArray();
_ = new Client(0, addresses);
Assert.Fail();
}
catch (InitializationException exception)
{
Assert.AreEqual(InitializationStatus.AddressLimitExceeded, exception.Status);
}
}
[TestMethod]
public void ConstructorAndFinalizer()
{
// No using here, we want to test the finalizer
var client = new Client(1, new string[] { "3000" });
Assert.IsTrue(client.ClusterID == 1);
}
[TestMethod]
public void CreateAccount()
{
var accounts = GenerateAccounts();
var okResult = client.CreateAccount(accounts[0]);
Assert.IsTrue(okResult == CreateAccountResult.Ok);
var lookupAccount = client.LookupAccount(accounts[0].Id);
Assert.IsNotNull(lookupAccount);
AssertAccount(accounts[0], lookupAccount.Value);
var existsResult = client.CreateAccount(accounts[0]);
Assert.IsTrue(existsResult == CreateAccountResult.Exists);
}
[TestMethod]
public async Task CreateAccountAsync()
{
var accounts = GenerateAccounts();
var okResult = await client.CreateAccountAsync(accounts[0]);
Assert.IsTrue(okResult == CreateAccountResult.Ok);
var lookupAccount = await client.LookupAccountAsync(accounts[0].Id);
Assert.IsNotNull(lookupAccount);
AssertAccount(accounts[0], lookupAccount.Value);
var existsResult = await client.CreateAccountAsync(accounts[0]);
Assert.IsTrue(existsResult == CreateAccountResult.Exists);
}
[TestMethod]
public void CreateAccounts()
{
var accounts = GenerateAccounts();
var results = client.CreateAccounts(accounts);
Assert.IsTrue(results.Length == 0);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
}
[TestMethod]
public async Task CreateAccountsAsync()
{
var accounts = GenerateAccounts();
var results = await client.CreateAccountsAsync(accounts);
Assert.IsTrue(results.Length == 0);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
}
[TestMethod]
public void CreateTransfers()
{
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
};
var transferResults = client.CreateTransfers(new[] { transfer });
Assert.IsTrue(transferResults.Length == 0);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
var lookupTransfers = client.LookupTransfers(new UInt128[] { transfer.Id });
Assert.IsTrue(lookupTransfers.Length == 1);
AssertTransfer(transfer, lookupTransfers[0]);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, transfer.Amount);
}
[TestMethod]
public async Task CreateTransfersAsync()
{
var accounts = GenerateAccounts();
var accountResults = await client.CreateAccountsAsync(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
};
var transferResults = await client.CreateTransfersAsync(new[] { transfer });
Assert.IsTrue(transferResults.Length == 0);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
var lookupTransfers = await client.LookupTransfersAsync(new UInt128[] { transfer.Id });
Assert.IsTrue(lookupTransfers.Length == 1);
AssertTransfer(transfer, lookupTransfers[0]);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, transfer.Amount);
}
[TestMethod]
public void CreateTransfer()
{
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
};
var successResult = client.CreateTransfer(transfer);
Assert.IsTrue(successResult == CreateTransferResult.Ok);
var lookupTransfer = client.LookupTransfer(transfer.Id);
Assert.IsTrue(lookupTransfer != null);
AssertTransfer(transfer, lookupTransfer!.Value);
var existsResult = client.CreateTransfer(transfer);
Assert.IsTrue(existsResult == CreateTransferResult.Exists);
}
[TestMethod]
public async Task CreateTransferAsync()
{
var accounts = GenerateAccounts();
var accountResults = await client.CreateAccountsAsync(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
};
var successResult = await client.CreateTransferAsync(transfer);
Assert.IsTrue(successResult == CreateTransferResult.Ok);
var lookupTransfer = await client.LookupTransferAsync(transfer.Id);
Assert.IsTrue(lookupTransfer != null);
AssertTransfer(transfer, lookupTransfer!.Value);
var existsResult = await client.CreateTransferAsync(transfer);
Assert.IsTrue(existsResult == CreateTransferResult.Exists);
}
[TestMethod]
public void CreatePendingTransfersAndPost()
{
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Timeout = uint.MaxValue,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Pending,
};
var result = client.CreateTransfer(transfer);
Assert.IsTrue(result == CreateTransferResult.Ok);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
var postTransfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
PendingId = transfer.Id,
Ledger = 1,
Code = 1,
Flags = TransferFlags.PostPendingTransfer,
};
var postResult = client.CreateTransfer(postTransfer);
Assert.IsTrue(postResult == CreateTransferResult.Ok);
lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, transfer.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPending, (UInt128)0);
}
[TestMethod]
public async Task CreatePendingTransfersAndPostAsync()
{
var accounts = GenerateAccounts();
var accountResults = await client.CreateAccountsAsync(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Timeout = uint.MaxValue,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Pending,
};
var result = await client.CreateTransferAsync(transfer);
Assert.IsTrue(result == CreateTransferResult.Ok);
var lookupAccounts = await client.LookupAccountsAsync(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
var postTransfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
PendingId = transfer.Id,
Ledger = 1,
Code = 1,
Flags = TransferFlags.PostPendingTransfer,
};
var postResult = await client.CreateTransferAsync(postTransfer);
Assert.IsTrue(postResult == CreateTransferResult.Ok);
lookupAccounts = await client.LookupAccountsAsync(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, transfer.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPending, (UInt128)0);
}
[TestMethod]
public void CreatePendingTransfersAndVoid()
{
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Timeout = uint.MaxValue,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Pending,
};
var result = client.CreateTransfer(transfer);
Assert.IsTrue(result == CreateTransferResult.Ok);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
var postTransfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
Flags = TransferFlags.VoidPendingTransfer,
PendingId = transfer.Id,
};
var postResult = client.CreateTransfer(postTransfer);
Assert.IsTrue(postResult == CreateTransferResult.Ok);
lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, (UInt128)0);
}
[TestMethod]
public async Task CreatePendingTransfersAndVoidAsync()
{
var accounts = GenerateAccounts();
var accountResults = await client.CreateAccountsAsync(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Timeout = uint.MaxValue,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Pending,
};
var result = await client.CreateTransferAsync(transfer);
Assert.IsTrue(result == CreateTransferResult.Ok);
var lookupAccounts = await client.LookupAccountsAsync(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
var postTransfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
PendingId = transfer.Id,
Ledger = 1,
Code = 1,
Flags = TransferFlags.VoidPendingTransfer,
};
var postResult = await client.CreateTransferAsync(postTransfer);
Assert.IsTrue(postResult == CreateTransferResult.Ok);
lookupAccounts = await client.LookupAccountsAsync(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, (UInt128)0);
}
[TestMethod]
public void CreatePendingTransfersAndVoidExpired()
{
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Timeout = 1,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Pending,
};
var result = client.CreateTransfer(transfer);
Assert.IsTrue(result == CreateTransferResult.Ok);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
// We need to wait 1s for the server to expire the transfer, however the
// server can pulse the expiry operation anytime after the timeout,
// so adding an extra delay to avoid flaky tests.
const long EXTRA_WAIT_TIME = 250;
Thread.Sleep(TimeSpan.FromSeconds(transfer.Timeout)
.Add(TimeSpan.FromMilliseconds(EXTRA_WAIT_TIME)));
// Looking up the accounts again for the updated balance.
lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
var postTransfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
Flags = TransferFlags.VoidPendingTransfer,
PendingId = transfer.Id,
};
var postResult = client.CreateTransfer(postTransfer);
Assert.IsTrue(postResult == CreateTransferResult.PendingTransferExpired);
}
[TestMethod]
public async Task CreatePendingTransfersAndVoidExpiredAsync()
{
var accounts = GenerateAccounts();
var accountResults = await client.CreateAccountsAsync(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Timeout = 1,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Pending,
};
var result = await client.CreateTransferAsync(transfer);
Assert.IsTrue(result == CreateTransferResult.Ok);
var lookupAccounts = await client.LookupAccountsAsync(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, transfer.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
// Waiting for the transfer to expire:
// Do not use Task.Delay here as it seems to be less precise.
// Waiting for the transfer to expire:
Thread.Sleep(TimeSpan.FromSeconds(transfer.Timeout).Add(TimeSpan.FromMilliseconds(1)));
var postTransfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
PendingId = transfer.Id,
Ledger = 1,
Code = 1,
Flags = TransferFlags.VoidPendingTransfer,
};
var postResult = await client.CreateTransferAsync(postTransfer);
Assert.IsTrue(postResult == CreateTransferResult.PendingTransferExpired);
lookupAccounts = await client.LookupAccountsAsync(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.AreEqual(lookupAccounts[0].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (UInt128)0);
}
[TestMethod]
public void CreateLinkedTransfers()
{
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer1 = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Linked,
};
var transfer2 = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[1].Id,
DebitAccountId = accounts[0].Id,
Amount = 49,
Ledger = 1,
Code = 1,
Flags = TransferFlags.None,
};
var transferResults = client.CreateTransfers(new[] { transfer1, transfer2 });
Assert.IsTrue(transferResults.All(x => x.Result == CreateTransferResult.Ok));
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
var lookupTransfers = client.LookupTransfers(new UInt128[] { transfer1.Id, transfer2.Id });
Assert.IsTrue(lookupTransfers.Length == 2);
AssertTransfer(transfer1, lookupTransfers[0]);
AssertTransfer(transfer2, lookupTransfers[1]);
Assert.AreEqual(lookupAccounts[0].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, transfer1.Amount);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, transfer2.Amount);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, transfer2.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, transfer1.Amount);
}
[TestMethod]
public async Task CreateLinkedTransfersAsync()
{
var accounts = GenerateAccounts();
var accountResults = await client.CreateAccountsAsync(accounts);
Assert.IsTrue(accountResults.Length == 0);
var transfer1 = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Linked,
};
var transfer2 = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[1].Id,
DebitAccountId = accounts[0].Id,
Amount = 49,
Ledger = 1,
Code = 1,
Flags = TransferFlags.None,
};
var transferResults = await client.CreateTransfersAsync(new[] { transfer1, transfer2 });
Assert.IsTrue(transferResults.All(x => x.Result == CreateTransferResult.Ok));
var lookupAccounts = await client.LookupAccountsAsync(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
var lookupTransfers = await client.LookupTransfersAsync(new UInt128[] { transfer1.Id, transfer2.Id });
Assert.IsTrue(lookupTransfers.Length == 2);
AssertTransfer(transfer1, lookupTransfers[0]);
AssertTransfer(transfer2, lookupTransfers[1]);
Assert.AreEqual(lookupAccounts[0].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].CreditsPosted, transfer1.Amount);
Assert.AreEqual(lookupAccounts[0].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, transfer2.Amount);
Assert.AreEqual(lookupAccounts[1].CreditsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, transfer2.Amount);
Assert.AreEqual(lookupAccounts[1].DebitsPending, (UInt128)0);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, transfer1.Amount);
}
[TestMethod]
public void CreateClosingTransfer()
{
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var closingTransfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 0,
Ledger = 1,
Code = 1,
Flags = TransferFlags.ClosingDebit | TransferFlags.ClosingCredit | TransferFlags.Pending,
};
var result = client.CreateTransfer(closingTransfer);
Assert.IsTrue(result == CreateTransferResult.Ok);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
Assert.AreNotEqual(lookupAccounts[0].Flags, accounts[0].Flags);
Assert.IsTrue(lookupAccounts[0].Flags.HasFlag(AccountFlags.Closed));
Assert.AreNotEqual(lookupAccounts[1].Flags, accounts[1].Flags);
Assert.IsTrue(lookupAccounts[1].Flags.HasFlag(AccountFlags.Closed));
var voidingTransfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
PendingId = closingTransfer.Id,
Ledger = 1,
Code = 1,
Flags = TransferFlags.VoidPendingTransfer,
};
var voidingResult = client.CreateTransfer(voidingTransfer);
Assert.IsTrue(voidingResult == CreateTransferResult.Ok);
lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
Assert.IsFalse(lookupAccounts[0].Flags.HasFlag(AccountFlags.Closed));
Assert.IsFalse(lookupAccounts[1].Flags.HasFlag(AccountFlags.Closed));
}
[TestMethod]
public void CreateAccountTooMuchData()
{
const int TOO_MUCH_DATA = 10_000;
var accounts = new Account[TOO_MUCH_DATA];
for (int i = 0; i < TOO_MUCH_DATA; i++)
{
accounts[i] = new Account
{
Id = ID.Create(),
Code = 1,
Ledger = 1
};
}
try
{
_ = client.CreateAccounts(accounts);
Assert.Fail();
}
catch (RequestException requestException)
{
Assert.AreEqual(PacketStatus.TooMuchData, requestException.Status);
}
}
[TestMethod]
public async Task CreateAccountTooMuchDataAsync()
{
const int TOO_MUCH_DATA = 10_000;
var accounts = new Account[TOO_MUCH_DATA];
for (int i = 0; i < TOO_MUCH_DATA; i++)
{
accounts[i] = new Account
{
Id = ID.Create(),
Code = 1,
Ledger = 1
};
}
try
{
_ = await client.CreateAccountsAsync(accounts);
Assert.Fail();
}
catch (RequestException requestException)
{
Assert.AreEqual(PacketStatus.TooMuchData, requestException.Status);
}
}
[TestMethod]
public void CreateTransferTooMuchData()
{
const int TOO_MUCH_DATA = 10_000;
var transfers = new Transfer[TOO_MUCH_DATA];
for (int i = 0; i < TOO_MUCH_DATA; i++)
{
transfers[i] = new Transfer
{
Id = ID.Create(),
Code = 1,
Ledger = 1
};
}
try
{
_ = client.CreateTransfers(transfers);
Assert.Fail();
}
catch (RequestException requestException)
{
Assert.AreEqual(PacketStatus.TooMuchData, requestException.Status);
}
}
[TestMethod]
public async Task CreateTransferTooMuchDataAsync()
{
const int TOO_MUCH_DATA = 10_000;
var transfers = new Transfer[TOO_MUCH_DATA];
for (int i = 0; i < TOO_MUCH_DATA; i++)
{
transfers[i] = new Transfer
{
Id = ID.Create(),
DebitAccountId = 1,
CreditAccountId = 2,
Code = 1,
Ledger = 1,
Amount = 100,
};
}
try
{
_ = await client.CreateTransfersAsync(transfers);
Assert.Fail();
}
catch (RequestException requestException)
{
Assert.AreEqual(PacketStatus.TooMuchData, requestException.Status);
}
}
[TestMethod]
public void TestGetAccountTransfers()
{
var accounts = GenerateAccounts();
accounts[0].Flags |= AccountFlags.History;
accounts[1].Flags |= AccountFlags.History;
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
// Creating a transfer.
var transfers = new Transfer[10];
for (int i = 0; i < 10; i++)
{
transfers[i] = new Transfer
{
Id = ID.Create(),
// Swap the debit and credit accounts:
CreditAccountId = i % 2 == 0 ? accounts[0].Id : accounts[1].Id,
DebitAccountId = i % 2 == 0 ? accounts[1].Id : accounts[0].Id,
Ledger = 1,
Code = 2,
Flags = TransferFlags.None,
Amount = 100
};
}
var createTransferErrors = client.CreateTransfers(transfers);
Assert.IsTrue(createTransferErrors.Length == 0);
{
// Querying transfers where:
// `debit_account_id=$account1Id OR credit_account_id=$account1Id
// ORDER BY timestamp ASC`.
var filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = 0,
TimestampMax = 0,
Limit = 254,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits
};
var account_transfers = client.GetAccountTransfers(filter);
var account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 10);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
ulong timestamp = 0;
for (int i = 0; i < account_transfers.Length; i++)
{
var transfer = account_transfers[i];
Assert.IsTrue(transfer.Timestamp > timestamp);
timestamp = transfer.Timestamp;
var balance = account_balances[i];
Assert.IsTrue(balance.Timestamp == transfer.Timestamp);
}
}
{
// Querying transfers where:
// `debit_account_id=$account2Id OR credit_account_id=$account2Id
// ORDER BY timestamp DESC`.
var filter = new AccountFilter
{
AccountId = accounts[1].Id,
TimestampMin = 0,
TimestampMax = 0,
Limit = 254,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits | AccountFilterFlags.Reversed
};
var account_transfers = client.GetAccountTransfers(filter);
var account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 10);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
ulong timestamp = ulong.MaxValue;
for (int i = 0; i < account_transfers.Length; i++)
{
var transfer = account_transfers[i];
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
var balance = account_balances[i];
Assert.IsTrue(balance.Timestamp == transfer.Timestamp);
}
}
{
// Querying transfers where:
// `debit_account_id=$account1Id
// ORDER BY timestamp ASC`.
var filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = 0,
TimestampMax = 0,
Limit = 254,
Flags = AccountFilterFlags.Debits
};
var account_transfers = client.GetAccountTransfers(filter);
var account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 5);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
ulong timestamp = 0;
for (int i = 0; i < account_transfers.Length; i++)
{
var transfer = account_transfers[i];
Assert.IsTrue(transfer.Timestamp > timestamp);
timestamp = transfer.Timestamp;
var balance = account_balances[i];
Assert.IsTrue(balance.Timestamp == transfer.Timestamp);
}
}
{
// Querying transfers where:
// `credit_account_id=$account2Id
// ORDER BY timestamp DESC`.
var filter = new AccountFilter
{
AccountId = accounts[1].Id,
TimestampMin = 1,
TimestampMax = ulong.MaxValue - 1,
Limit = 254,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Reversed
};
var account_transfers = client.GetAccountTransfers(filter);
var account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 5);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
ulong timestamp = ulong.MaxValue;
for (int i = 0; i < account_transfers.Length; i++)
{
var transfer = account_transfers[i];
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
var balance = account_balances[i];
Assert.IsTrue(balance.Timestamp == transfer.Timestamp);
}
}
{
// Querying transfers where:
// `debit_account_id=$account1Id OR credit_account_id=$account1Id
// ORDER BY timestamp ASC LIMIT 5`.
var filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = 0,
TimestampMax = 0,
Limit = 5,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits
};
// First 5 items:
var account_transfers = client.GetAccountTransfers(filter);
var account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 5);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
ulong timestamp = 0;
for (int i = 0; i < account_transfers.Length; i++)
{
var transfer = account_transfers[i];
Assert.IsTrue(transfer.Timestamp > timestamp);
timestamp = transfer.Timestamp;
var balance = account_balances[i];
Assert.IsTrue(balance.Timestamp == transfer.Timestamp);
}
// Next 5 items from this timestamp:
filter.TimestampMin = timestamp + 1;
account_transfers = client.GetAccountTransfers(filter);
account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 5);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
for (int i = 0; i < account_transfers.Length; i++)
{
var transfer = account_transfers[i];
Assert.IsTrue(transfer.Timestamp > timestamp);
timestamp = transfer.Timestamp;
var balance = account_balances[i];
Assert.IsTrue(balance.Timestamp == transfer.Timestamp);
}
// No more pages after that:
filter.TimestampMin = timestamp + 1;
account_transfers = client.GetAccountTransfers(filter);
account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 0);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
}
{
// Querying transfers where:
// `debit_account_id=$account2Id OR credit_account_id=$account2Id
// ORDER BY timestamp DESC LIMIT 5`.
var filter = new AccountFilter
{
AccountId = accounts[1].Id,
TimestampMin = 0,
TimestampMax = 0,
Limit = 5,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits | AccountFilterFlags.Reversed
};
// First 5 items:
var account_transfers = client.GetAccountTransfers(filter);
var account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 5);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
ulong timestamp = ulong.MaxValue;
for (int i = 0; i < account_transfers.Length; i++)
{
var transfer = account_transfers[i];
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
var balance = account_balances[i];
Assert.IsTrue(balance.Timestamp == transfer.Timestamp);
}
// Next 5 items from this timestamp:
filter.TimestampMax = timestamp - 1;
account_transfers = client.GetAccountTransfers(filter);
account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 5);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
for (int i = 0; i < account_transfers.Length; i++)
{
var transfer = account_transfers[i];
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
var balance = account_balances[i];
Assert.IsTrue(balance.Timestamp == transfer.Timestamp);
}
// No more pages after that:
filter.TimestampMax = timestamp - 1;
account_transfers = client.GetAccountTransfers(filter);
account_balances = client.GetAccountBalances(filter);
Assert.IsTrue(account_transfers.Length == 0);
Assert.IsTrue(account_balances.Length == account_transfers.Length);
}
{
// Empty filter:
Assert.IsTrue(client.GetAccountTransfers(new AccountFilter { }).Length == 0);
Assert.IsTrue(client.GetAccountBalances(new AccountFilter { }).Length == 0);
// Invalid account
var filter = new AccountFilter
{
AccountId = 0,
TimestampMin = 0,
TimestampMax = 0,
Limit = 254,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits,
};
Assert.IsTrue(client.GetAccountTransfers(filter).Length == 0);
Assert.IsTrue(client.GetAccountBalances(filter).Length == 0);
// Invalid timestamp min
filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = ulong.MaxValue,
TimestampMax = 0,
Limit = 254,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits,
};
Assert.IsTrue(client.GetAccountTransfers(filter).Length == 0);
Assert.IsTrue(client.GetAccountBalances(filter).Length == 0);
// Invalid timestamp max
filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = 0,
TimestampMax = ulong.MaxValue,
Limit = 254,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits,
};
Assert.IsTrue(client.GetAccountTransfers(filter).Length == 0);
Assert.IsTrue(client.GetAccountBalances(filter).Length == 0);
// Invalid timestamp range
filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = ulong.MaxValue - 1,
TimestampMax = 1,
Limit = 254,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits,
};
Assert.IsTrue(client.GetAccountTransfers(filter).Length == 0);
Assert.IsTrue(client.GetAccountBalances(filter).Length == 0);
// Zero limit
filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = 0,
TimestampMax = 0,
Limit = 0,
Flags = AccountFilterFlags.Credits | AccountFilterFlags.Debits,
};
Assert.IsTrue(client.GetAccountTransfers(filter).Length == 0);
Assert.IsTrue(client.GetAccountBalances(filter).Length == 0);
// Empty flags
filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = 0,
TimestampMax = 0,
Limit = 254,
Flags = (AccountFilterFlags)0,
};
Assert.IsTrue(client.GetAccountTransfers(filter).Length == 0);
Assert.IsTrue(client.GetAccountBalances(filter).Length == 0);
// Invalid flags
filter = new AccountFilter
{
AccountId = accounts[0].Id,
TimestampMin = 0,
TimestampMax = 0,
Limit = 254,
Flags = (AccountFilterFlags)0xFFFF,
};
Assert.IsTrue(client.GetAccountTransfers(filter).Length == 0);
Assert.IsTrue(client.GetAccountBalances(filter).Length == 0);
}
}
[TestMethod]
public void TestQueryAccounts()
{
{
// Creating accounts.
var accounts = new Account[10];
for (int i = 0; i < 10; i++)
{
accounts[i] = new Account
{
Id = ID.Create()
};
if (i % 2 == 0)
{
accounts[i].UserData128 = 1000L;
accounts[i].UserData64 = 100;
accounts[i].UserData32 = 10;
}
else
{
accounts[i].UserData128 = 2000L;
accounts[i].UserData64 = 200;
accounts[i].UserData32 = 20;
}
accounts[i].Ledger = 1;
accounts[i].Code = 999;
accounts[i].Flags = AccountFlags.None;
}
var createAccountsErrors = client.CreateAccounts(accounts);
Assert.IsTrue(createAccountsErrors.Length == 0);
}
{
// Querying accounts where:
// `user_data_128=1000 AND user_data_64=100 AND user_data_32=10
// AND code=999 AND ledger=1 ORDER BY timestamp ASC`.
var filter = new QueryFilter
{
UserData128 = 1000,
UserData64 = 100,
UserData32 = 10,
Code = 999,
Ledger = 1,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Account[] query = client.QueryAccounts(filter);
Assert.IsTrue(query.Length == 5);
ulong timestamp = 0;
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp > timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.UserData128, transfer.UserData128);
Assert.AreEqual(filter.UserData64, transfer.UserData64);
Assert.AreEqual(filter.UserData32, transfer.UserData32);
Assert.AreEqual(filter.Ledger, transfer.Ledger);
Assert.AreEqual(filter.Code, transfer.Code);
}
}
{
// Querying accounts where:
// `user_data_128=2000 AND user_data_64=200 AND user_data_32=20
// AND code=999 AND ledger=1 ORDER BY timestamp ASC`.
var filter = new QueryFilter
{
UserData128 = 2000,
UserData64 = 200,
UserData32 = 20,
Code = 999,
Ledger = 1,
Limit = 254,
Flags = QueryFilterFlags.Reversed,
};
Account[] query = client.QueryAccounts(filter);
Assert.IsTrue(query.Length == 5);
ulong timestamp = ulong.MaxValue;
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.UserData128, transfer.UserData128);
Assert.AreEqual(filter.UserData64, transfer.UserData64);
Assert.AreEqual(filter.UserData32, transfer.UserData32);
Assert.AreEqual(filter.Ledger, transfer.Ledger);
Assert.AreEqual(filter.Code, transfer.Code);
}
}
{
// Querying account where:
// code=999 ORDER BY timestamp ASC`.
var filter = new QueryFilter
{
Code = 999,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Account[] query = client.QueryAccounts(filter);
Assert.IsTrue(query.Length == 10);
ulong timestamp = 0;
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp > timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.Code, transfer.Code);
}
}
{
// Querying accounts where:
// code=999 ORDER BY timestamp DESC LIMIT 5`.
var filter = new QueryFilter
{
Code = 999,
Limit = 5,
Flags = QueryFilterFlags.Reversed,
};
// First 5 items:
Account[] query = client.QueryAccounts(filter);
Assert.IsTrue(query.Length == 5);
ulong timestamp = ulong.MaxValue;
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.Code, transfer.Code);
}
// Next 5 items:
filter.TimestampMax = timestamp - 1;
query = client.QueryAccounts(filter);
Assert.IsTrue(query.Length == 5);
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.Code, transfer.Code);
}
// No more results:
filter.TimestampMax = timestamp - 1;
query = client.QueryAccounts(filter);
Assert.IsTrue(query.Length == 0);
}
{
// Not found:
var filter = new QueryFilter
{
UserData64 = 200,
UserData32 = 10,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Account[] query = client.QueryAccounts(filter);
Assert.IsTrue(query.Length == 0);
}
}
[TestMethod]
public void TestQueryTransfers()
{
var accounts = GenerateAccounts();
{
var accountsResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountsResults.Length == 0);
}
{
// Creating transfers.
var transfers = new Transfer[10];
for (int i = 0; i < 10; i++)
{
transfers[i] = new Transfer
{
Id = ID.Create()
};
if (i % 2 == 0)
{
transfers[i].CreditAccountId = accounts[0].Id;
transfers[i].DebitAccountId = accounts[1].Id;
transfers[i].UserData128 = 1000L;
transfers[i].UserData64 = 100;
transfers[i].UserData32 = 10;
}
else
{
transfers[i].CreditAccountId = accounts[1].Id;
transfers[i].DebitAccountId = accounts[0].Id;
transfers[i].UserData128 = 2000L;
transfers[i].UserData64 = 200;
transfers[i].UserData32 = 20;
}
transfers[i].Ledger = 1;
transfers[i].Code = 999;
transfers[i].Flags = TransferFlags.None;
transfers[i].Amount = 100;
}
var createTransfersErrors = client.CreateTransfers(transfers);
Assert.IsTrue(createTransfersErrors.Length == 0);
}
{
// Querying transfers where:
// `user_data_128=1000 AND user_data_64=100 AND user_data_32=10
// AND code=999 AND ledger=1 ORDER BY timestamp ASC`.
var filter = new QueryFilter
{
UserData128 = 1000,
UserData64 = 100,
UserData32 = 10,
Code = 999,
Ledger = 1,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Transfer[] query = client.QueryTransfers(filter);
Assert.IsTrue(query.Length == 5);
ulong timestamp = 0;
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp > timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.UserData128, transfer.UserData128);
Assert.AreEqual(filter.UserData64, transfer.UserData64);
Assert.AreEqual(filter.UserData32, transfer.UserData32);
Assert.AreEqual(filter.Ledger, transfer.Ledger);
Assert.AreEqual(filter.Code, transfer.Code);
}
}
{
// Querying transfers where:
// `user_data_128=2000 AND user_data_64=200 AND user_data_32=20
// AND code=999 AND ledger=1 ORDER BY timestamp ASC`.
var filter = new QueryFilter
{
UserData128 = 2000,
UserData64 = 200,
UserData32 = 20,
Code = 999,
Ledger = 1,
Limit = 254,
Flags = QueryFilterFlags.Reversed,
};
Transfer[] query = client.QueryTransfers(filter);
Assert.IsTrue(query.Length == 5);
ulong timestamp = ulong.MaxValue;
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.UserData128, transfer.UserData128);
Assert.AreEqual(filter.UserData64, transfer.UserData64);
Assert.AreEqual(filter.UserData32, transfer.UserData32);
Assert.AreEqual(filter.Ledger, transfer.Ledger);
Assert.AreEqual(filter.Code, transfer.Code);
}
}
{
// Querying transfers where:
// code=999 ORDER BY timestamp ASC`.
var filter = new QueryFilter
{
Code = 999,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Transfer[] query = client.QueryTransfers(filter);
Assert.IsTrue(query.Length == 10);
ulong timestamp = 0;
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp > timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.Code, transfer.Code);
}
}
{
// Querying transfers where:
// code=999 ORDER BY timestamp DESC LIMIT 5`.
var filter = new QueryFilter
{
Code = 999,
Limit = 5,
Flags = QueryFilterFlags.Reversed,
};
// First 5 items:
Transfer[] query = client.QueryTransfers(filter);
Assert.IsTrue(query.Length == 5);
ulong timestamp = ulong.MaxValue;
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.Code, transfer.Code);
}
// Next 5 items:
filter.TimestampMax = timestamp - 1;
query = client.QueryTransfers(filter);
Assert.IsTrue(query.Length == 5);
foreach (var transfer in query)
{
Assert.IsTrue(transfer.Timestamp < timestamp);
timestamp = transfer.Timestamp;
Assert.AreEqual(filter.Code, transfer.Code);
}
// No more results:
filter.TimestampMax = timestamp - 1;
query = client.QueryTransfers(filter);
Assert.IsTrue(query.Length == 0);
}
{
// Not found:
var filter = new QueryFilter
{
UserData64 = 200,
UserData32 = 10,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Transfer[] query = client.QueryTransfers(filter);
Assert.IsTrue(query.Length == 0);
}
}
[TestMethod]
public void TestInvalidQueryFilter()
{
{
// Empty filter with zero limit:
Assert.IsTrue(client.QueryAccounts(new QueryFilter { }).Length == 0);
Assert.IsTrue(client.QueryTransfers(new QueryFilter { }).Length == 0);
}
{
// Invalid timestamp min
var filter = new QueryFilter
{
TimestampMin = ulong.MaxValue,
TimestampMax = 0,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Assert.IsTrue(client.QueryAccounts(filter).Length == 0);
Assert.IsTrue(client.QueryTransfers(filter).Length == 0);
}
{
// Invalid timestamp max
var filter = new QueryFilter
{
TimestampMin = 0,
TimestampMax = ulong.MaxValue,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Assert.IsTrue(client.QueryAccounts(filter).Length == 0);
Assert.IsTrue(client.QueryTransfers(filter).Length == 0);
}
{
// Invalid timestamp range
var filter = new QueryFilter
{
TimestampMin = ulong.MaxValue - 1,
TimestampMax = 1,
Limit = 254,
Flags = QueryFilterFlags.None,
};
Assert.IsTrue(client.QueryAccounts(filter).Length == 0);
Assert.IsTrue(client.QueryTransfers(filter).Length == 0);
}
{
// Invalid flags
var filter = new QueryFilter
{
TimestampMin = 0,
TimestampMax = 0,
Limit = 254,
Flags = (QueryFilterFlags)0xFFFF,
};
Assert.IsTrue(client.QueryAccounts(filter).Length == 0);
Assert.IsTrue(client.QueryTransfers(filter).Length == 0);
}
}
[TestMethod]
[DoNotParallelize]
public void ImportedFlag()
{
// Gets the last timestamp recorded and waits for 10ms so the
// timestamp can be used as reference for importing past movements.
var timestamp = GetTimestampLast();
Thread.Sleep(10);
var accounts = GenerateAccounts();
for (int i = 0; i < accounts.Length; i++)
{
accounts[i].Flags = AccountFlags.Imported;
accounts[i].Timestamp = timestamp + (ulong)(i + 1);
}
var results = client.CreateAccounts(accounts);
Assert.IsTrue(results.Length == 0);
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
for (int i = 0; i < accounts.Length; i++)
{
Assert.AreEqual(accounts[i].Timestamp, timestamp + (ulong)(i + 1));
}
var transfer = new Transfer
{
Id = ID.Create(),
DebitAccountId = accounts[0].Id,
CreditAccountId = accounts[1].Id,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Imported,
Amount = 10,
Timestamp = timestamp + (ulong)(accounts.Length + 1),
};
var createTransferResult = client.CreateTransfer(transfer);
Assert.AreEqual(CreateTransferResult.Ok, createTransferResult);
var lookupTransfer = client.LookupTransfer(transfer.Id);
Assert.IsNotNull(lookupTransfer);
AssertTransfer(transfer, lookupTransfer.Value);
Assert.AreEqual(transfer.Timestamp, lookupTransfer.Value.Timestamp);
}
[TestMethod]
[DoNotParallelize]
public async Task ImportedFlagAsync()
{
// Gets the last timestamp recorded and waits for 10ms so the
// timestamp can be used as reference for importing past movements.
var timestamp = GetTimestampLast();
Thread.Sleep(10);
var accounts = GenerateAccounts();
for (int i = 0; i < accounts.Length; i++)
{
accounts[i].Flags = AccountFlags.Imported;
accounts[i].Timestamp = timestamp + (ulong)(i + 1);
}
var results = await client.CreateAccountsAsync(accounts);
Assert.IsTrue(results.Length == 0);
var lookupAccounts = await client.LookupAccountsAsync(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
for (int i = 0; i < accounts.Length; i++)
{
Assert.AreEqual(accounts[i].Timestamp, timestamp + (ulong)(i + 1));
}
var transfer = new Transfer
{
Id = ID.Create(),
DebitAccountId = accounts[0].Id,
CreditAccountId = accounts[1].Id,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Imported,
Amount = 10,
Timestamp = timestamp + (ulong)(accounts.Length + 1),
};
var createTransferResult = await client.CreateTransferAsync(transfer);
Assert.AreEqual(CreateTransferResult.Ok, createTransferResult);
var lookupTransfer = await client.LookupTransferAsync(transfer.Id);
Assert.IsNotNull(lookupTransfer);
AssertTransfer(transfer, lookupTransfer.Value);
Assert.AreEqual(transfer.Timestamp, lookupTransfer.Value.Timestamp);
}
private static ulong GetTimestampLast()
{
// Inserts a dummy transfer just to retrieve the lastest timestamp
// recorded by the cluster.
// Must be used only in "DoNotParallelize" tests.
var dummy_account = GenerateAccounts()[0];
var okResult = client.CreateAccount(dummy_account);
Assert.IsTrue(okResult == CreateAccountResult.Ok);
var lookup = client.LookupAccount(dummy_account.Id);
Assert.IsNotNull(lookup);
return lookup.Value.Timestamp;
}
/// <summary>
/// This test asserts that a single Client can be shared by multiple concurrent tasks
/// </summary>
[TestMethod]
public void ConcurrencyTest() => ConcurrencyTest(isAsync: false);
[TestMethod]
public void ConcurrencyTestAsync() => ConcurrencyTest(isAsync: true);
private void ConcurrencyTest(bool isAsync)
{
const int TASKS_QTY = 100_000;
using var client = new Client(0, new[] { server.Address });
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var tasks = new Task<CreateTransferResult>[TASKS_QTY];
async Task<CreateTransferResult> asyncAction(Transfer transfer)
{
return await client.CreateTransferAsync(transfer);
}
CreateTransferResult syncAction(Transfer transfer)
{
return client.CreateTransfer(transfer);
}
for (int i = 0; i < TASKS_QTY; i++)
{
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 1,
Ledger = 1,
Code = 1,
};
// Starts multiple requests.
// Wraps the syncAction into a Task for unified logic handling both async and sync tests.
tasks[i] = isAsync ? asyncAction(transfer) : Task.Run(() => syncAction(transfer));
}
Task.WhenAll(tasks).Wait();
Assert.IsTrue(tasks.All(x => x.Result == CreateTransferResult.Ok));
var lookupAccounts = client.LookupAccounts(new[] { accounts[0].Id, accounts[1].Id });
AssertAccounts(accounts, lookupAccounts);
// Assert that all tasks ran to the conclusion
Assert.AreEqual(lookupAccounts[0].CreditsPosted, (uint)TASKS_QTY);
Assert.AreEqual(lookupAccounts[0].DebitsPosted, 0LU);
Assert.AreEqual(lookupAccounts[1].CreditsPosted, 0LU);
Assert.AreEqual(lookupAccounts[1].DebitsPosted, (uint)TASKS_QTY);
}
/// <summary>
/// This test asserts that Client.Dispose() will wait for any ongoing request to complete
/// And new requests will fail with ObjectDisposedException.
/// </summary>
[TestMethod]
public void ConcurrentTasksDispose() => ConcurrentTasksDispose(isAsync: false);
[TestMethod]
public void ConcurrentTasksDisposeAsync() => ConcurrentTasksDispose(isAsync: true);
private void ConcurrentTasksDispose(bool isAsync)
{
const int TASKS_QTY = 32;
using var client = new Client(0, new[] { server.Address });
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
var tasks = new Task<CreateTransferResult>[TASKS_QTY];
for (int i = 0; i < TASKS_QTY; i++)
{
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
};
/// Starts multiple tasks.
var task = isAsync ? client.CreateTransferAsync(transfer) : Task.Run(() => client.CreateTransfer(transfer));
tasks[i] = task;
}
// Waiting for just one task, the others may be pending.
Task.WaitAny(tasks);
// Disposes the client, waiting all placed requests to finish.
client.Dispose();
try
{
// Ignoring exceptions from the tasks.
Task.WhenAll(tasks).Wait();
}
catch { }
// Asserting that either the task failed or succeeded,
// at least one must be succeeded.
Assert.IsTrue(tasks.Any(x => !x.IsFaulted && x.Result == CreateTransferResult.Ok));
Assert.IsTrue(tasks.All(x => x.IsFaulted || x.Result == CreateTransferResult.Ok));
}
[TestMethod]
[ExpectedException(typeof(ObjectDisposedException))]
public void DisposedClient()
{
using var client = new Client(0, new[] { server.Address });
var accounts = GenerateAccounts();
var accountResults = client.CreateAccounts(accounts);
Assert.IsTrue(accountResults.Length == 0);
client.Dispose();
var transfer = new Transfer
{
Id = ID.Create(),
CreditAccountId = accounts[0].Id,
DebitAccountId = accounts[1].Id,
Amount = 100,
Ledger = 1,
Code = 1,
};
_ = client.CreateTransfers(new[] { transfer });
Assert.Fail();
}
private static void AssertAccounts(Account[] expected, Account[] actual)
{
Assert.AreEqual(expected.Length, actual.Length);
for (int i = 0; i < actual.Length; i++)
{
AssertAccount(actual[i], expected[i]);
}
}
private static void AssertAccount(Account a, Account b)
{
Assert.AreEqual(a.Id, b.Id);
Assert.AreEqual(a.UserData128, b.UserData128);
Assert.AreEqual(a.UserData64, b.UserData64);
Assert.AreEqual(a.UserData32, b.UserData32);
Assert.AreEqual(a.Flags, b.Flags);
Assert.AreEqual(a.Code, b.Code);
Assert.AreEqual(a.Ledger, b.Ledger);
}
private static void AssertTransfer(Transfer a, Transfer b)
{
Assert.AreEqual(a.Id, b.Id);
Assert.AreEqual(a.DebitAccountId, b.DebitAccountId);
Assert.AreEqual(a.CreditAccountId, b.CreditAccountId);
Assert.AreEqual(a.Amount, b.Amount);
Assert.AreEqual(a.PendingId, b.PendingId);
Assert.AreEqual(a.UserData128, b.UserData128);
Assert.AreEqual(a.UserData64, b.UserData64);
Assert.AreEqual(a.UserData32, b.UserData32);
Assert.AreEqual(a.Timeout, b.Timeout);
Assert.AreEqual(a.Flags, b.Flags);
Assert.AreEqual(a.Code, b.Code);
Assert.AreEqual(a.Ledger, b.Ledger);
}
private static bool AssertException<T>(Exception exception) where T : Exception
{
while (exception is AggregateException aggregateException && aggregateException.InnerException != null)
{
exception = aggregateException.InnerException;
}
return exception is T;
}
}
internal class TBServer : IDisposable
{
// Path relative from /TigerBeetle.Test/bin/<framework>/<release>/<platform> :
private const string PROJECT_ROOT = "../../../../..";
private const string TB_PATH = PROJECT_ROOT + "/../../../zig-out/bin";
private const string TB_EXE = "tigerbeetle";
private const string TB_SERVER = TB_PATH + "/" + TB_EXE;
private readonly Process process;
private readonly string dataFile;
public string Address { get; }
public TBServer()
{
dataFile = Path.GetRandomFileName();
{
using var format = new Process();
format.StartInfo.FileName = TB_SERVER;
format.StartInfo.Arguments = $"format --cluster=0 --replica=0 --replica-count=1 --development ./{dataFile}";
format.StartInfo.RedirectStandardError = true;
format.Start();
var formatStderr = format.StandardError.ReadToEnd();
format.WaitForExit();
if (format.ExitCode != 0) throw new InvalidOperationException($"format failed, ExitCode={format.ExitCode} stderr:\n{formatStderr}");
}
process = new Process();
process.StartInfo.FileName = TB_SERVER;
process.StartInfo.Arguments = $"start --addresses=0 --development ./{dataFile}";
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
Address = process.StandardOutput.ReadLine()!.Trim();
}
public void Dispose()
{
process.Kill();
process.WaitForExit();
process.Dispose();
File.Delete($"./{dataFile}");
}
}
|
0 | repos/tigerbeetle/src/clients/dotnet | repos/tigerbeetle/src/clients/dotnet/TigerBeetle.Tests/TigerBeetle.Tests.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<LangVersion>10</LangVersion>
<DebugType>Full</DebugType>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<UseCurrentRuntimeIdentifier>true</UseCurrentRuntimeIdentifier>
<SelfContained>false</SelfContained>
<RollForward>LatestMajor</RollForward>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="3.2.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.msbuild" Version="3.2.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<Content Include="..\TigerBeetle\runtimes\$(RuntimeIdentifier)\native\*.*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
<PackageReference Include="MSTest.TestAdapter" Version="3.0.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TigerBeetle\TigerBeetle.csproj" />
</ItemGroup>
</Project>
|
0 | repos/tigerbeetle/src/clients/dotnet | repos/tigerbeetle/src/clients/dotnet/TigerBeetle.Tests/EchoTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace TigerBeetle.Tests;
[TestClass]
public class EchoTests
{
private const int HEADER_SIZE = 256; // @sizeOf(vsr.Header)
private const int MESSAGE_SIZE_MAX = 1024 * 1024; // config.message_size_max
private static readonly int TRANSFER_SIZE = Marshal.SizeOf(typeof(Transfer));
private static readonly int ITEMS_PER_BATCH = (MESSAGE_SIZE_MAX - HEADER_SIZE) / TRANSFER_SIZE;
[TestMethod]
public void Accounts()
{
var rnd = new Random(1);
using var client = new EchoClient(0, new[] { "3000" });
var batch = GetRandom<Account>(rnd);
var reply = client.Echo(batch);
Assert.IsTrue(batch.SequenceEqual(reply));
}
[TestMethod]
public async Task AccountsAsync()
{
var rnd = new Random(2);
using var client = new EchoClient(0, new[] { "3000" });
var batch = GetRandom<Account>(rnd);
var reply = await client.EchoAsync(batch);
Assert.IsTrue(batch.SequenceEqual(reply));
}
[TestMethod]
public void Transfers()
{
var rnd = new Random(3);
using var client = new EchoClient(0, new[] { "3000" });
var batch = GetRandom<Transfer>(rnd);
var reply = client.Echo(batch);
Assert.IsTrue(batch.SequenceEqual(reply));
}
[TestMethod]
public async Task TransfersAsync()
{
var rnd = new Random(4);
using var client = new EchoClient(0, new[] { "3000" });
var batch = GetRandom<Transfer>(rnd);
var reply = await client.EchoAsync(batch);
Assert.IsTrue(batch.SequenceEqual(reply));
}
[TestMethod]
public async Task ConcurrentAccountsAsync()
{
const int MAX_CONCURRENCY = 64;
var rnd = new Random(5);
using var client = new EchoClient(0, new[] { "3000" });
const int MAX_REPETITIONS = 5;
for (int repetition = 0; repetition < MAX_REPETITIONS; repetition++)
{
var list = new List<(Account[] batch, Task<Account[]> task)>();
for (int i = 0; i < MAX_CONCURRENCY; i++)
{
var batch = GetRandom<Account>(rnd);
var task = client.EchoAsync(batch);
list.Add((batch, task));
}
foreach (var (batch, task) in list)
{
var reply = await task;
Assert.IsTrue(batch.SequenceEqual(reply));
}
}
}
[TestMethod]
public void ConcurrentTransfers()
{
const int MAX_CONCURRENCY = 64;
var rnd = new Random(6);
using var client = new EchoClient(0, new[] { "3000" });
const int MAX_REPETITIONS = 5;
for (int repetition = 0; repetition < MAX_REPETITIONS; repetition++)
{
var barrier = new Barrier(MAX_CONCURRENCY);
var list = new List<ThreadContext>();
for (int i = 0; i < MAX_CONCURRENCY; i++)
{
var batch = GetRandom<Transfer>(rnd);
var threadContext = new ThreadContext(client, barrier, batch);
list.Add(threadContext);
}
foreach (var item in list)
{
var reply = item.Wait();
Assert.IsTrue(item.Batch.SequenceEqual(reply));
}
}
}
private class ThreadContext
{
private readonly Thread thread;
private readonly Transfer[] batch;
private Transfer[]? reply = null;
private Exception? exception;
public Transfer[] Batch => batch;
public ThreadContext(EchoClient client, Barrier barrier, Transfer[] batch)
{
this.batch = batch;
this.thread = new Thread(new ParameterizedThreadStart(Run));
this.thread.Start((client, barrier));
}
private void Run(object? state)
{
try
{
var (client, barrier) = ((EchoClient, Barrier))state!;
barrier.SignalAndWait();
reply = client.Echo(batch);
}
catch (Exception exception)
{
this.exception = exception;
}
}
public Transfer[] Wait()
{
thread.Join();
return reply ?? throw exception!;
}
}
private static T[] GetRandom<T>(Random rnd)
where T : unmanaged
{
var size = rnd.Next(1, ITEMS_PER_BATCH);
var buffer = new byte[size * Marshal.SizeOf(typeof(T))];
rnd.NextBytes(buffer);
return MemoryMarshal.Cast<byte, T>(buffer).ToArray();
}
}
|
0 | repos/tigerbeetle/src/clients/dotnet | repos/tigerbeetle/src/clients/dotnet/TigerBeetle.Tests/UInt128Tests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
namespace TigerBeetle.Tests;
[TestClass]
public class UInt128Tests
{
/// <summary>
/// Consistency of U128 across Zig and the language clients.
/// It must be kept in sync with all platforms.
/// </summary>
[TestMethod]
public void ConsistencyTest()
{
// Decimal representation:
ulong upper = 11647051514084770242;
ulong lower = 15119395263638463974;
var u128 = new UInt128(upper, lower);
Assert.AreEqual("214850178493633095719753766415838275046", u128.ToString());
// Binary representation:
byte[] binary = new byte[] {
0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1,
0xd2, 0xd1,
0xc2, 0xc1,
0xb2, 0xb1,
0xa4, 0xa3, 0xa2, 0xa1,
};
Assert.IsTrue(binary.SequenceEqual(u128.ToArray()));
// GUID representation:
var guid = Guid.Parse("a1a2a3a4-b1b2-c1c2-d1d2-e1e2e3e4e5e6");
Assert.AreEqual(guid, u128.ToGuid());
Assert.AreEqual(u128, guid.ToUInt128());
}
[TestMethod]
public void GuidConversion()
{
Guid guid = Guid.Parse("A945C62A-4CC7-425B-B44A-893577632902");
UInt128 value = guid.ToUInt128();
Assert.AreEqual(value, guid.ToUInt128());
Assert.AreEqual(guid, value.ToGuid());
}
[TestMethod]
public void GuidMaxConversion()
{
Guid guid = Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff");
UInt128 value = guid.ToUInt128();
Assert.AreEqual(value, guid.ToUInt128());
Assert.AreEqual(guid, value.ToGuid());
}
[TestMethod]
public void ArrayConversion()
{
byte[] array = new byte[16] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 };
UInt128 value = array.ToUInt128();
Assert.IsTrue(value.ToArray().SequenceEqual(array));
Assert.IsTrue(array.SequenceEqual(value.ToArray()));
Assert.IsTrue(value.Equals(array.ToUInt128()));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullArrayConversion()
{
byte[] array = null!;
_ = array.ToUInt128();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void EmptyArrayConversion()
{
byte[] array = new byte[0];
_ = array.ToUInt128();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void InvalidArrayConversion()
{
// Expected ArgumentException.
byte[] array = new byte[17];
_ = array.ToUInt128();
}
[TestMethod]
public void BigIntegerConversion()
{
var checkConversion = (BigInteger bigInteger) =>
{
UInt128 uint128 = bigInteger.ToUInt128();
Assert.AreEqual(uint128, bigInteger.ToUInt128());
Assert.AreEqual(bigInteger, uint128.ToBigInteger());
Assert.IsTrue(uint128.Equals(bigInteger.ToUInt128()));
};
checkConversion(BigInteger.Parse("0"));
checkConversion(BigInteger.Parse("1"));
checkConversion(BigInteger.Parse("123456789012345678901234567890123456789"));
checkConversion(new BigInteger(uint.MaxValue));
checkConversion(new BigInteger(ulong.MaxValue));
}
[TestMethod]
[ExpectedException(typeof(OverflowException))]
public void BigIntegerNegative()
{
// Expected OverflowException.
_ = BigInteger.MinusOne.ToUInt128();
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void BigIntegerExceedU128()
{
// Expected ArgumentOutOfRangeException.
BigInteger bigInteger = BigInteger.Parse("9999999999999999999999999999999999999999");
_ = bigInteger.ToUInt128();
}
[TestMethod]
public void LittleEndian()
{
// Reference test:
// https://github.com/microsoft/windows-rs/blob/f19edde93252381b7a1789bf856a3a67df23f6db/crates/tests/core/tests/guid.rs#L25-L31
byte[] bytes_expected = new byte[16] {
0x8f,0x8c,0x2b,0x05,0xa4,0x53,
0x3a,0x82,
0xfe,0x42,
0xd2,0xc0,
0xef,0x3f,0xd6,0x1f,
};
UInt128 decimal_expected = UInt128.Parse("1fd63fefc0d242fe823a53a4052b8c8f", NumberStyles.HexNumber);
BigInteger bigint_expected = BigInteger.Parse("1fd63fefc0d242fe823a53a4052b8c8f", NumberStyles.HexNumber);
Guid guid_expected = Guid.Parse("1fd63fef-c0d2-42fe-823a-53a4052b8c8f");
Assert.AreEqual(decimal_expected, bytes_expected.ToUInt128());
Assert.AreEqual(decimal_expected, bigint_expected.ToUInt128());
Assert.AreEqual(decimal_expected, guid_expected.ToUInt128());
Assert.IsTrue(bytes_expected.SequenceEqual(decimal_expected.ToArray()));
Assert.IsTrue(bytes_expected.SequenceEqual(bytes_expected.ToUInt128().ToArray()));
Assert.IsTrue(bytes_expected.SequenceEqual(bigint_expected.ToUInt128().ToArray()));
Assert.IsTrue(bytes_expected.SequenceEqual(guid_expected.ToUInt128().ToArray()));
}
[TestMethod]
public void IDCreation()
{
var verifier = () =>
{
UInt128 idA = ID.Create();
for (int i = 0; i < 1_000_000; i++)
{
if (i % 1_000 == 0)
{
Thread.Sleep(1);
}
UInt128 idB = ID.Create();
Assert.IsTrue(idB.CompareTo(idA) > 0);
idA = idB;
}
};
// Verify monotonic IDs locally.
verifier();
// Verify monotonic IDs across multiple threads.
var concurrency = 10;
var startBarrier = new Barrier(concurrency);
Parallel.For(0, concurrency, (_, _) =>
{
startBarrier.SignalAndWait();
verifier();
});
}
}
|
0 | repos/tigerbeetle/src/clients/dotnet | repos/tigerbeetle/src/clients/dotnet/TigerBeetle.Tests/BindingTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace TigerBeetle.Tests;
[TestClass]
public class BindingTests
{
[TestMethod]
public void Accounts()
{
var account = new Account();
account.Id = 100;
Assert.AreEqual(account.Id, (UInt128)100);
account.UserData128 = 101;
Assert.AreEqual(account.UserData128, (UInt128)101);
account.UserData64 = 102;
Assert.AreEqual(account.UserData64, (ulong)102L);
account.UserData32 = 103;
Assert.AreEqual(account.UserData32, (uint)103);
account.Reserved = 0;
Assert.AreEqual(account.Reserved, (uint)0);
account.Ledger = 104;
Assert.AreEqual(account.Ledger, (uint)104);
account.Code = 105;
Assert.AreEqual(account.Code, (ushort)105);
var flags = AccountFlags.Linked | AccountFlags.DebitsMustNotExceedCredits | AccountFlags.CreditsMustNotExceedDebits;
account.Flags = flags;
Assert.AreEqual(account.Flags, flags);
account.DebitsPending = 1001;
Assert.AreEqual(account.DebitsPending, (UInt128)1001);
account.CreditsPending = 1002;
Assert.AreEqual(account.CreditsPending, (UInt128)1002);
account.DebitsPosted = 1003;
Assert.AreEqual(account.DebitsPosted, (UInt128)1003);
account.CreditsPosted = 1004;
Assert.AreEqual(account.CreditsPosted, (UInt128)1004);
account.Timestamp = 99_999;
Assert.AreEqual(account.Timestamp, (ulong)99_999);
}
[TestMethod]
public void AccountsDefault()
{
var account = new Account(); ;
Assert.AreEqual(account.Id, UInt128.Zero);
Assert.AreEqual(account.UserData128, UInt128.Zero);
Assert.AreEqual(account.UserData64, (ulong)0);
Assert.AreEqual(account.UserData32, (uint)0);
Assert.AreEqual(account.Reserved, (uint)0);
Assert.AreEqual(account.Ledger, (uint)0);
Assert.AreEqual(account.Code, (ushort)0);
Assert.AreEqual(account.Flags, AccountFlags.None);
Assert.AreEqual(account.DebitsPending, (UInt128)0);
Assert.AreEqual(account.CreditsPending, (UInt128)0);
Assert.AreEqual(account.DebitsPosted, (UInt128)0);
Assert.AreEqual(account.CreditsPosted, (UInt128)0);
Assert.AreEqual(account.Timestamp, (UInt128)0);
}
[TestMethod]
public void AccountsSerialize()
{
var expected = new byte[Account.SIZE];
using (var writer = new BinaryWriter(new MemoryStream(expected)))
{
writer.Write(10L); // Id (lsb)
writer.Write(11L); // Id (msb)
writer.Write(100L); // DebitsPending (lsb)
writer.Write(110L); // DebitsPending (msb)
writer.Write(200L); // DebitsPosted (lsb)
writer.Write(210L); // DebitsPosted (msb)
writer.Write(300L); // CreditPending (lsb)
writer.Write(310L); // CreditPending (msb)
writer.Write(400L); // CreditsPosted (lsb)
writer.Write(410L); // CreditsPosted (msb)
writer.Write(1000L); // UserData128 (lsb)
writer.Write(1100L); // UserData128 (msb)
writer.Write(2000L); // UserData64
writer.Write(3000); // UserData32
writer.Write(0); // Reserved
writer.Write(720); // Ledger
writer.Write((short)1); // Code
writer.Write((short)1); // Flags
writer.Write(999L); // Timestamp
}
var account = new Account
{
Id = new UInt128(11L, 10L),
DebitsPending = new UInt128(110L, 100L),
DebitsPosted = new UInt128(210L, 200L),
CreditsPending = new UInt128(310L, 300L),
CreditsPosted = new UInt128(410L, 400L),
UserData128 = new UInt128(1100L, 1000L),
UserData64 = 2000L,
UserData32 = 3000,
Ledger = 720,
Code = 1,
Flags = AccountFlags.Linked,
Timestamp = 999,
};
var serialized = MemoryMarshal.AsBytes<Account>(new Account[] { account }).ToArray();
Assert.IsTrue(expected.SequenceEqual(serialized));
}
[TestMethod]
public void CreateAccountsResults()
{
var result = new CreateAccountsResult();
result.Index = 1;
Assert.AreEqual(result.Index, (uint)1);
result.Result = CreateAccountResult.Exists;
Assert.AreEqual(result.Result, CreateAccountResult.Exists);
}
[TestMethod]
public void Transfers()
{
var transfer = new Transfer();
transfer.Id = 100;
Assert.AreEqual(transfer.Id, (UInt128)100);
transfer.DebitAccountId = 101;
Assert.AreEqual(transfer.DebitAccountId, (UInt128)101);
transfer.CreditAccountId = 102;
Assert.AreEqual(transfer.CreditAccountId, (UInt128)102);
transfer.Amount = 1001;
Assert.AreEqual(transfer.Amount, (UInt128)1001);
transfer.PendingId = 103;
Assert.AreEqual(transfer.PendingId, (UInt128)103);
transfer.UserData128 = 104;
Assert.AreEqual(transfer.UserData128, (UInt128)104);
transfer.UserData64 = 105;
Assert.AreEqual(transfer.UserData64, (ulong)105);
transfer.UserData32 = 106;
Assert.AreEqual(transfer.UserData32, (uint)106);
transfer.Timeout = 107;
Assert.AreEqual(transfer.Timeout, (uint)107);
transfer.Ledger = 108;
Assert.AreEqual(transfer.Ledger, (uint)108);
transfer.Code = 109;
Assert.AreEqual(transfer.Code, (ushort)109);
var flags = TransferFlags.Linked | TransferFlags.PostPendingTransfer | TransferFlags.VoidPendingTransfer;
transfer.Flags = flags;
Assert.AreEqual(transfer.Flags, flags);
transfer.Timestamp = 99_999;
Assert.AreEqual(transfer.Timestamp, (ulong)99_999);
}
[TestMethod]
public void TransferDefault()
{
var transfer = new Transfer();
Assert.AreEqual(transfer.Id, (UInt128)0);
Assert.AreEqual(transfer.DebitAccountId, (UInt128)0);
Assert.AreEqual(transfer.CreditAccountId, (UInt128)0);
Assert.AreEqual(transfer.Amount, (UInt128)0);
Assert.AreEqual(transfer.PendingId, (UInt128)0);
Assert.AreEqual(transfer.UserData128, (UInt128)0);
Assert.AreEqual(transfer.UserData64, (ulong)0);
Assert.AreEqual(transfer.UserData32, (uint)0);
Assert.AreEqual(transfer.Timeout, (uint)0);
Assert.AreEqual(transfer.Ledger, (uint)0);
Assert.AreEqual(transfer.Code, (ushort)0);
Assert.AreEqual(transfer.Flags, TransferFlags.None);
Assert.AreEqual(transfer.Timestamp, (ulong)0);
}
[TestMethod]
public void TransfersSerialize()
{
var expected = new byte[Transfer.SIZE];
using (var writer = new BinaryWriter(new MemoryStream(expected)))
{
writer.Write(10L); // Id (lsb)
writer.Write(11L); // Id (msb)
writer.Write(100L); // DebitAccountId (lsb)
writer.Write(110L); // DebitAccountId (msb)
writer.Write(200L); // CreditAccountId (lsb)
writer.Write(210L); // CreditAccountId (msb)
writer.Write(300L); // Amount (lsb)
writer.Write(310L); // Amount (msb)
writer.Write(400L); // PendingId (lsb)
writer.Write(410L); // PendingId (msb)
writer.Write(1000L); // UserData128 (lsb)
writer.Write(1100L); // UserData128 (msb)
writer.Write(2000L); // UserData64
writer.Write(3000); // UserData32
writer.Write(999); // Timeout
writer.Write(720); // Ledger
writer.Write((short)1); // Code
writer.Write((short)1); // Flags
writer.Write(99_999L); // Timestamp
}
var transfer = new Transfer
{
Id = new UInt128(11L, 10L),
DebitAccountId = new UInt128(110L, 100L),
CreditAccountId = new UInt128(210L, 200L),
Amount = new UInt128(310L, 300L),
PendingId = new UInt128(410L, 400L),
UserData128 = new UInt128(1100L, 1000L),
UserData64 = 2000L,
UserData32 = 3000,
Timeout = 999,
Ledger = 720,
Code = 1,
Flags = TransferFlags.Linked,
Timestamp = 99_999,
};
var serialized = MemoryMarshal.AsBytes<Transfer>(new Transfer[] { transfer }).ToArray();
Assert.IsTrue(expected.SequenceEqual(serialized));
}
[TestMethod]
public void CreateTransfersResults()
{
var result = new CreateTransfersResult();
result.Index = 1;
Assert.AreEqual(result.Index, (uint)1);
result.Result = CreateTransferResult.Exists;
Assert.AreEqual(result.Result, CreateTransferResult.Exists);
}
}
|
0 | repos/tigerbeetle/src/clients/dotnet | repos/tigerbeetle/src/clients/dotnet/TigerBeetle.Tests/RequestTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace TigerBeetle.Tests;
[TestClass]
public class RequestTests
{
[TestMethod]
[ExpectedException(typeof(AssertionException))]
public async Task UnexpectedOperation()
{
var callback = new CallbackSimulator<Account, UInt128>(
TBOperation.LookupAccounts,
(byte)99,
null,
PacketStatus.Ok,
delay: 100,
isAsync: true
);
var task = callback.Run();
Assert.IsFalse(task.IsCompleted);
_ = await task;
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(AssertionException))]
public async Task InvalidSizeOperation()
{
var buffer = new byte[Account.SIZE + 1];
var callback = new CallbackSimulator<Account, UInt128>(
TBOperation.LookupAccounts,
(byte)TBOperation.LookupAccounts,
buffer,
PacketStatus.Ok,
delay: 100,
isAsync: true
);
var task = callback.Run();
Assert.IsFalse(task.IsCompleted);
_ = await task;
Assert.Fail();
}
[TestMethod]
public async Task RequestException()
{
foreach (var isAsync in new bool[] { true, false })
{
var buffer = new byte[Account.SIZE];
var callback = new CallbackSimulator<Account, UInt128>(
TBOperation.LookupAccounts,
(byte)TBOperation.LookupAccounts,
buffer,
PacketStatus.TooMuchData,
delay: 100,
isAsync
);
var task = callback.Run();
Assert.IsFalse(task.IsCompleted);
try
{
_ = await task;
Assert.Fail();
}
catch (RequestException exception)
{
Assert.AreEqual(PacketStatus.TooMuchData, exception.Status);
}
}
}
[TestMethod]
public async Task Success()
{
foreach (var isAsync in new bool[] { true, false })
{
var buffer = MemoryMarshal.Cast<Account, byte>(new Account[]
{
new Account
{
Id = 1,
UserData128 = 2,
UserData64 = 3,
UserData32 = 4,
Code = 5,
Ledger = 6,
Flags = AccountFlags.Linked,
}
}).ToArray();
var callback = new CallbackSimulator<Account, UInt128>(
TBOperation.LookupAccounts,
(byte)TBOperation.LookupAccounts,
buffer,
PacketStatus.Ok,
delay: 100,
isAsync
);
var task = callback.Run();
Assert.IsFalse(task.IsCompleted);
var accounts = await task;
Assert.IsTrue(accounts.Length == 1);
Assert.IsTrue(accounts[0].Id == 1);
Assert.IsTrue(accounts[0].UserData128 == 2);
Assert.IsTrue(accounts[0].UserData64 == 3);
Assert.IsTrue(accounts[0].UserData32 == 4);
Assert.IsTrue(accounts[0].Code == 5);
Assert.IsTrue(accounts[0].Ledger == 6);
Assert.IsTrue(accounts[0].Flags == AccountFlags.Linked);
}
}
private class CallbackSimulator<TResult, TBody>
where TResult : unmanaged
where TBody : unmanaged
{
private readonly Request<TResult, TBody> request;
private readonly byte receivedOperation;
private readonly Memory<byte> buffer;
private readonly PacketStatus status;
private readonly int delay;
public CallbackSimulator(TBOperation operation, byte receivedOperation, Memory<byte> buffer, PacketStatus status, int delay, bool isAsync)
{
unsafe
{
this.request = isAsync ? new AsyncRequest<TResult, TBody>(operation) : new BlockingRequest<TResult, TBody>(operation);
this.receivedOperation = receivedOperation;
this.buffer = buffer;
this.status = status;
this.delay = delay;
}
}
public Task<TResult[]> Run()
{
Task.Run(() =>
{
unsafe
{
Task.Delay(delay).Wait();
request.Complete(status, receivedOperation, buffer.Span);
}
});
if (request is AsyncRequest<TResult, TBody> asyncRequest)
{
return asyncRequest.Wait();
}
else if (request is BlockingRequest<TResult, TBody> blockingRequest)
{
return Task.Run(() => blockingRequest.Wait());
}
else
{
throw new NotImplementedException();
}
}
}
}
|
0 | repos/tigerbeetle/src/clients/dotnet | repos/tigerbeetle/src/clients/dotnet/TigerBeetle.Tests/ExceptionTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace TigerBeetle.Tests;
[TestClass]
public class ExceptionTests
{
[TestMethod]
public void AssertTrue()
{
// Should not throw an exception
// when the condition is true.
AssertionException.AssertTrue(true);
}
[TestMethod]
[ExpectedException(typeof(AssertionException))]
public void AssertFalse()
{
// Expected AssertionException.
AssertionException.AssertTrue(false);
}
[TestMethod]
public void AssertFalseWithMessage()
{
try
{
AssertionException.AssertTrue(false, "hello {0}", "world");
// Should not be reachable:
Assert.Fail();
}
catch (AssertionException exception)
{
Assert.AreEqual("hello world", exception.Message);
}
}
[TestMethod]
public void AssertTrueWithMessage()
{
AssertionException.AssertTrue(true, "unreachable");
}
[TestMethod]
public void InitializationException()
{
foreach (InitializationStatus status in (InitializationStatus[])Enum.GetValues(typeof(InitializationStatus)))
{
var exception = new InitializationException(status);
var unknownMessage = "Unknown error status " + status;
if (status == InitializationStatus.Success)
{
Assert.AreEqual(unknownMessage, exception.Message);
}
else
{
Assert.AreNotEqual(unknownMessage, exception.Message);
}
}
}
[TestMethod]
public void RequestException()
{
foreach (PacketStatus status in (PacketStatus[])Enum.GetValues(typeof(PacketStatus)))
{
var exception = new RequestException(status);
var unknownMessage = "Unknown error status " + status;
if (status == PacketStatus.Ok || status == PacketStatus.ClientShutdown)
{
Assert.AreEqual(unknownMessage, exception.Message);
}
else
{
Assert.AreNotEqual(unknownMessage, exception.Message);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.