1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Where a ledger is kept: the [`Store`] contract, the in-memory
//! [`MemoryStore`] and the one SQL implementation [`SqlStore`].
//!
//! A store decides nothing. Its [`write`](Store::write) takes the ledger's
//! single-writer lock inside one transaction, hands the rule core a bounded
//! [`Snapshot`] of exactly the state the operation needs (asking [`plan`]
//! which facts), runs [`execute`], persists the [`WriteSet`] and commits. Its
//! reads answer from indexes, never by scanning history, each in one read
//! snapshot that never waits for the writer.
//!
//! - **One ledger per store**: one PostgreSQL schema, one SQLite file, one
//! memory state. PostgreSQL stores of many schemas share one connection
//! pool (`SqlStore::with_schema`).
//! - **Create once, open always**: [`create`](Store::create) writes the
//! genesis record (and, on SQL, the schema); calling it again with the same
//! genesis is a no-op, so every replica may call it at start-up.
//! [`open`](Store::open) never changes anything and refuses a database of
//! another schema or ledger. There are no migrations.
//! - **Locks**: SQLite `BEGIN IMMEDIATE` (one writer per file); PostgreSQL
//! `READ COMMITTED` pinned per transaction plus a transaction advisory
//! lock keyed by the schema and the ledger id, so two schemas never wait
//! for each other — even holding the same ledger id. Readers take no lock.
//! - **Audit**: everything a store keeps is part of its projection
//! ([`ProjectionPart`]: every table, every column) and is compared with
//! the replay of its log; reads that hand a stored record on verify it
//! first (its id derives from its key, its leaf hashes to the stored leaf
//! hash).
//! - **Erasure**: [`erase_memo`](Store::erase_memo) removes an entry's memo
//! text and salt (and its draft fingerprint) without changing any hash.
//! When to erase is the caller's decision, tied to the end of the
//! retention period.
//!
//! `Ledger<S>` drives a store; implementers of a new store check it with the
//! public conformance suite (`doubleentry::testing`, feature `testing`).
pub
use Future;
pub use ;
pub use MemoryStore;
pub use honest;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use Postgres;
pub use Sqlite;
pub use ;
// The store protocol of the rule core — the operation, its outcome, the
// write set, the read plan and every view a `Fact` carries — the replay an
// audit runs, and the log's node numbering: everything an implementer of a
// third-party store needs, one path each.
pub use crate;
pub use crate;
pub use crateTree;
use crateRejection;
use crateHash;
use crate;
use crate::;
/// The identifier of the schema this crate writes, recorded in every store
/// it creates; any other identifier is refused.
pub const SCHEMA_ID: &str = "doubleentry/1";
/// The error of a write whose read plan did not converge — a bug guard,
/// never a silent "absent".
pub
/// The backend contract: where one ledger is kept.
///
/// Eighteen primitives: the lifecycle ([`create`](Self::create),
/// [`open`](Self::open)), the write pipeline ([`write`](Self::write)), the
/// log, the indexes, the values and the one erasable datum. Proofs at any
/// historical size, statements, reports and audit are built once over these
/// by the façade. Every method returns a `Send` future; implementers may
/// write `async fn`. Every method fails only with [`StoreError`].
///
/// A store is a cheap handle (a pool, an `Arc`) and is used generically as
/// `Ledger<S>`; it is not a trait object. To choose a store at run time,
/// wrap the candidates in an enum of your own:
///
/// ```
/// # #[cfg(feature = "sqlite")]
/// # mod example {
/// use doubleentry::store::*;
/// use doubleentry::{AccountHandle, AccountRef, Balance, Currency, EntryId, Layer, PeriodId, log::Hash, record::Genesis, store::BalanceKey};
/// use doubleentry::{HoldCursor, Page, PageRead, Rejection};
///
/// /// The store this service was configured with.
/// #[derive(Clone)]
/// pub enum AnyStore {
/// Memory(MemoryStore),
/// Sqlite(SqlStore<Sqlite>),
/// }
///
/// macro_rules! delegate {
/// ($self:ident, $store:ident => $call:expr) => {
/// match $self {
/// AnyStore::Memory($store) => $call.await,
/// AnyStore::Sqlite($store) => $call.await,
/// }
/// };
/// }
///
/// impl Store<2> for AnyStore {
/// async fn create(&self, genesis: &Genesis) -> Result<LedgerInfo, StoreError> {
/// delegate!(self, s => s.create(genesis))
/// }
/// async fn open(&self) -> Result<LedgerInfo, StoreError> {
/// delegate!(self, s => s.open())
/// }
/// async fn write(&self, op: &Op<2>) -> Result<Result<Done<2>, Rejection>, StoreError> {
/// delegate!(self, s => s.write(op))
/// }
/// async fn size(&self) -> Result<u64, StoreError> {
/// delegate!(self, s => s.size())
/// }
/// async fn read_leaves(&self, read: &LeafRead) -> Result<Page<Leaf, Position>, StoreError> {
/// delegate!(self, s => s.read_leaves(read))
/// }
/// async fn read_nodes(&self, ids: &[u64]) -> Result<Vec<Hash>, StoreError> {
/// delegate!(self, s => s.read_nodes(ids))
/// }
/// async fn seals(&self, through: Option<u64>) -> Result<Vec<SealRow>, StoreError> {
/// delegate!(self, s => s.seals(through))
/// }
/// async fn accounts(&self, refs: &[AccountRef]) -> Result<Vec<Option<AccountRow>>, StoreError> {
/// delegate!(self, s => s.accounts(refs))
/// }
/// async fn account_records(
/// &self,
/// handle: AccountHandle,
/// page: PageRead<Position>,
/// ) -> Result<Page<Leaf, Position>, StoreError> {
/// delegate!(self, s => s.account_records(handle, page))
/// }
/// async fn entry(
/// &self,
/// by: EntryRef<'_>,
/// through: Option<u64>,
/// ) -> Result<Option<StoredEntry>, StoreError> {
/// delegate!(self, s => s.entry(by, through))
/// }
/// async fn holds(&self, read: &HoldRead) -> Result<Page<HoldRow<2>, HoldCursor>, StoreError> {
/// delegate!(self, s => s.holds(read))
/// }
/// async fn clearings(
/// &self,
/// key: BalanceKey,
/// page: PageRead<Position>,
/// ) -> Result<Page<Leaf, Position>, StoreError> {
/// delegate!(self, s => s.clearings(key, page))
/// }
/// async fn projection(&self, read: &ProjectionRead) -> Result<ProjectionPage<2>, StoreError> {
/// delegate!(self, s => s.projection(read))
/// }
/// async fn seal_nodes(
/// &self,
/// period: &PeriodId,
/// currency: Currency,
/// layer: Layer,
/// ids: &[(u32, u32)],
/// ) -> Result<Option<Vec<Option<Hash>>>, StoreError> {
/// delegate!(self, s => s.seal_nodes(period, currency, layer, ids))
/// }
/// async fn balances(
/// &self,
/// read: &BalanceRead,
/// ) -> Result<Page<(BalanceKey, Balance), BalanceKey>, StoreError> {
/// delegate!(self, s => s.balances(read))
/// }
/// async fn postings(
/// &self,
/// read: &PostingRead,
/// ) -> Result<Page<PostingLine<2>, PostingCursor>, StoreError> {
/// delegate!(self, s => s.postings(read))
/// }
/// async fn memo(&self, id: EntryId) -> Result<Option<Memo>, StoreError> {
/// delegate!(self, s => s.memo(id))
/// }
/// async fn erase_memo(&self, id: EntryId) -> Result<Erasure, StoreError> {
/// delegate!(self, s => s.erase_memo(id))
/// }
/// }
/// # }
/// ```