-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-account.ts
More file actions
executable file
·209 lines (179 loc) · 5.54 KB
/
create-account.ts
File metadata and controls
executable file
·209 lines (179 loc) · 5.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// TigerBeetle
import {
createClient,
id as generateId,
Client,
CreateAccountError,
Account,
} from "tigerbeetle-node";
// Sqlite
import Database from "better-sqlite3";
// Resonate
import { Resonate, Context } from "@resonatehq/sdk";
// Initialize Resonate
const resonate = new Resonate({
url: "http://localhost:8001",
});
// TigerBeetle client
const tbClient = createClient({
cluster_id: 0n,
replica_addresses: ["3000"],
});
// Sqlite client
const sqClient = new Database("./bin/accounts.db");
// Set dependencies in Resonate
resonate.setDependency("tbClient", tbClient);
resonate.setDependency("sqClient", sqClient);
// Register functions with Resonate
resonate.register("createAccount", createAccount);
export type Result =
| { type: "created" }
| { type: "exists_same" }
| { type: "exists_diff" };
/**
* Create account in SQLite (System of Reference)
*
* An record here is a staged record, but does not determine the account's existance
*
*/
function sqCreateAccount(context: Context, uuid: string, guid: string): Result {
const db = context.getDependency<Database.Database>("sqClient");
try {
db.prepare("INSERT INTO accounts (uuid, guid) VALUES (?, ?)").run(
uuid,
guid,
);
return { type: "created" };
} catch (error: any) {
// SQLite constraint violation (UNIQUE constraint on uuid or guid)
if (
error.code === "SQLITE_CONSTRAINT_PRIMARYKEY" ||
error.code === "SQLITE_CONSTRAINT" ||
error.code === "SQLITE_CONSTRAINT_UNIQUE" ||
error.message?.includes("UNIQUE constraint failed")
) {
const existing = db
.prepare("SELECT guid FROM accounts WHERE uuid = ?")
.get(uuid) as { guid: string } | undefined;
if (existing && existing.guid === guid) {
return { type: "exists_same" };
} else {
return { type: "exists_diff" };
}
}
throw new Error(`Failed to create account in SQLite: ${error.message}`);
}
}
/**
* Create account in TigerBeetle (System of Record)
*
* An record here is a committed record and does determines the account's existance
*
*/
async function tbCreateAccount(
context: Context,
guid: string,
): Promise<Result> {
const client = context.getDependency<Client>("tbClient");
const account: Account = {
id: BigInt(guid),
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,
};
// Try to create the account
const errors = await client.createAccounts([account]);
// Success case: account was created
if (errors.length === 0) {
return { type: "created" };
}
const error = errors[0];
// Account exists with the same properties (idempotent)
if (error.result === CreateAccountError.exists) {
return { type: "exists_same" };
}
// Account exists with different properties
if (
error.result === CreateAccountError.exists_with_different_flags ||
error.result === CreateAccountError.exists_with_different_user_data_128 ||
error.result === CreateAccountError.exists_with_different_user_data_64 ||
error.result === CreateAccountError.exists_with_different_user_data_32 ||
error.result === CreateAccountError.exists_with_different_ledger ||
error.result === CreateAccountError.exists_with_different_code
) {
return { type: "exists_diff" };
}
// For any other error, throw
throw new Error(`Failed to create account: ${JSON.stringify(error)}`);
}
/**
* Create account using the dthe "Write Last, Read First" principle with
* Resonate's automatic checkpointing and reliable resumption:
*
* 1. Generate TigerBeetle ID (guid)
* 2. Write to SQLite (system of reference - stages the record)
* 3. Write to TigerBeetle (system of record - commits the account)
*
* Resonate guarantees:
* - Eventual completion via language-integrated checkpointing
* - Reliable resumption after disruptions (restarts from beginning, skips completed steps)
*/
function* createAccount(
context: Context,
uuid: string,
): Generator<any, { uuid: string; guid: string }, any> {
// Generate a random account id
const guid = yield* context.run(function (context: Context) {
return generateId().toString();
});
// Create account in SQLite
const sqResult = yield* context.run(sqCreateAccount, uuid, guid);
// Panic and alert the operator if the account exists
// but with different values
yield* context.panic(sqResult.type == "exists_diff");
// Create account in TigerBeetle
const tbResult = yield* context.run(tbCreateAccount, guid);
// Panic and alert the operator if the account exists
// but with different values
yield* context.panic(tbResult.type == "exists_diff");
// Panic and alert the operator if ordering was violated
yield* context.panic(
sqResult.type == "created" && tbResult.type == "exists_same",
);
return { uuid, guid };
}
async function main() {
// Get UUID from command line arguments
const uuid = process.argv[2];
if (!uuid) {
console.error("Usage: tsx create-account.ts <uuid>");
console.error("Example: tsx create-account.ts user-123");
process.exit(1);
}
try {
const result = await resonate.run(
`create-account-${uuid}`,
createAccount,
uuid,
);
resonate.stop();
console.log(`UUID: ${result.uuid}`);
console.log(`GUID: ${result.guid}`);
} catch (error) {
console.error("Error:", error);
process.exit(1);
} finally {
sqClient.close();
tbClient.destroy();
}
}
main().catch(console.error);