How flash-oss/medici works
1. What this repo is
- medici is a TypeScript/Mongoose library that implements a double-entry accounting ledger on MongoDB.
- The core abstraction is a Book: a logical partition of journals and transactions identified by a book name.
2. Public API surface
- src/index.ts exports the main entry points: Book, Entry, mongoTransaction, schema registration helpers, index sync helpers, and custom error types.
- Book is the primary façade. Entry is the fluent builder used to assemble a journal before commit.
3. Core write flow
- A caller creates an Entry, adds debits and credits, then commits it through the Book.
- The commit path validates accounting invariants, especially that the journal balances to zero.
- On success, Medici writes a journal document plus its child transaction documents.
4. Persistence model
- The main MongoDB-backed entities are modeled in src/models/: journal, transaction, balance, and lock.
- Journals store the high-level event metadata; transactions store account-level lines.
- Key journal fields are duplicated onto transactions so most reads can avoid populating/joining the journal collection.
5. Read/query flow
- Balance and ledger queries go through parsing helpers under src/helper/parse/.
- Query input is split into:
- structural fields like account, date range, and journal references
- arbitrary metadata filters
- The parser uses the transaction schema to decide whether a field belongs at the top level or inside meta.
6. Balance caching subsystem
- .balance() can use a snapshot cache stored in the medici_balances collection.
- The flow is: find the latest snapshot, aggregate only newer transactions, then combine the two results.
- This cache is time-based and TTL-backed, so it is a distinct subsystem from the canonical ledger data.
7. Consistency and concurrency
- The repo supports MongoDB sessions and ACID-style transactions via mongoTransaction.
- A lock model and writelockAccounts() are used to make balance checks reliable inside a transaction.
- This is the main boundary between ordinary reads/writes and stronger consistency guarantees.
8. Voiding and reversal logic
- Voiding does not delete history. Instead, the original journal is marked voided and an equal/opposite reversing journal is created.
- handleVoidMemo and related helpers manage default void memo behavior and propagation of void metadata.
- This keeps the ledger auditable and preserves accounting integrity.
9. Schema customization and index management
- The library supports replacing the default journal/transaction schemas with custom Mongoose schemas.
- setTransactionSchema, setJournalSchema, initModels, and syncIndexes coordinate model initialization and index enforcement.
- extractObjectIdKeysFromSchema and index helpers exist so custom schema fields still participate correctly in querying and performance tuning.
10. Safety and data-shaping helpers
- Helpers such as flattenObject, safeSetKeyToMetaObject, isPrototypeAttribute, and addReversedTransactions protect against prototype pollution and normalize user input into Mongo-friendly shapes.
- The codebase is deliberately defensive because user-supplied account names, metadata, and query filters all influence persistence and read paths.
11. Error boundary
- Domain-specific failures are isolated under src/errors/.
- Errors distinguish constructor/validation problems, missing journals, invalid account paths, consistency failures, and void-related conflicts.
- This gives the architecture a clear separation between normal application behavior and ledger invariant violations.
12. Operational/tooling layer
- The repo is TypeScript-first, tested with spec files under spec/, and benchmarked with scripts under bench/.
- CI workflows and lint/type configs are present, but they support the library rather than define runtime behavior.
- The external dependency that materially shapes the architecture is MongoDB via Mongoose, with some operations intentionally using the lower-level MongoDB driver semantics for transactions and consistency.
Main entry points: Book.ts Book · transaction.ts Transaction · MediciError.ts Medici Error · index.ts Index
Components 25
Public API
Primary entry points exposed to library consumers.
- Index · Package surface exporting the library entry points.
src/index.ts
Ledger Core
Book and entry flow for composing and committing journals.
Mongo Models
Canonical collections and model wiring for ledger data.
- Journal · High-level journal records with event metadata and void state.
src/models/journal.ts - Transaction · Account-level ledger lines; duplicates key journal fields for read efficiency.
src/models/transaction.ts - Balance · Cached balance snapshots stored for fast balance queries.
src/models/balance.ts - Lock · Lock records used to coordinate stronger consistency during writes.
src/models/lock.ts
Read Path
Query parsing and balance computation, including cache use.
- Balance Parse · Splits balance query input into structural fields and metadata filters.
src/helper/parse/parseBalanceQuery.ts - Filter Parse · Normalizes arbitrary filter conditions for ledger and balance lookups.
src/helper/parse/parseFilterQuery.ts - Account Parse · Resolves account-related query fields and boundaries.
src/helper/parse/parseAccountField.ts
Consistency
Transactions, locking, and void/reversal behavior.
- Mongo Tx · Wraps MongoDB session/transaction execution for ACID-style writes.
src/helper/mongoTransaction.ts - Write Lock · Applies account locks so balance checks stay reliable inside transactions.
- Void Memo · Builds and propagates default void memo and reversal metadata.
src/helper/handleVoidMemo.ts - Reverse Tx · Creates opposite transactions for voided journals.
src/helper/addReversedTransactions.ts
Helpers
Shared normalization, schema, and setup utilities.
- Init Models · Initializes or rebinds Mongoose models for the library.
src/helper/initModels.ts - Sync Indexes · Coordinates index enforcement across customizable schemas.
src/helper/syncIndexes.ts - ObjectId Keys · Finds ObjectId-bearing paths in custom schemas for query/index support.
src/helper/extractObjectIdKeysFromSchema.ts - Flatten · Flattens nested objects into Mongo-friendly field shapes.
src/helper/flattenObject.ts - Safe Meta · Writes metadata defensively while avoiding prototype pollution.
src/helper/safeSetKeyToMetaObject.ts
Errors
Domain-specific failure types.
- Medici Error · Shared base class for domain errors.
src/errors/MediciError.ts - Not Found · Raised when a referenced journal cannot be found.
src/errors/JournalNotFoundError.ts - Consistency · Raised when balance or write invariants fail.
src/errors/ConsistencyError.ts - Account Path · Raised for invalid account path lengths.
src/errors/InvalidAccountPathLengthError.ts - Voided Journal · Raised when an already voided journal is voided again.
src/errors/JournalAlreadyVoidedError.ts - Transaction · Raised for transaction-level validation and write failures.
src/errors/TransactionError.ts
Connections 42
- Index → Book: exports · Public API exports the main ledger façade.
- Index → Entry: exports · Public API exports the journal builder.
- Index → Mongo Tx: exports · Public API exposes transaction wrapper.
- Index → Init Models: exports · Public API exposes model/schema helpers.
- Index → Sync Indexes: exports · Public API exposes index synchronization.
- Index → Medici Error: exports · Public API re-exports error types.
- Book → Entry: builds · Book accepts entries and commits them.
- Book → Journal: writes · Commit path persists journal documents.
- Book → Transaction: writes · Commit path persists transaction lines.
- Book → Consistency: throws · Book enforces accounting and consistency invariants.
- Entry → Filter Parse: uses · Entry and commit flow normalize user-provided fields.
- Book → Balance Parse: uses · Balance queries are parsed before aggregation.
- Book → Filter Parse: uses · Ledger queries are split into structural and meta filters.
- Book → Account Parse: uses · Account-specific query fields are normalized.
- Book → Mongo Tx: wraps · Write operations can run inside MongoDB sessions.
- Book → Write Lock: coordinates · Strong balance checks rely on account locking.
- Book → Void Memo: voids · Voiding flow prepares memo and reversal metadata.
- Book → Reverse Tx: voids · Voiding creates reversing transactions instead of deleting history.
- Book → Not Found: throws · Lookup and void flows can fail when a journal is missing.
- Book → Voided Journal: throws · Voiding an already voided journal is rejected.
- Balance Parse → Balance: reads · Balance query parser drives snapshot and aggregation logic.
- Filter Parse → Transaction: targets · Filter parsing uses transaction schema shape.
- Account Parse → Transaction: targets · Account field parsing depends on transaction schema layout.
- Balance → Transaction: aggregates · Snapshot cache is combined with newer transactions.
- Balance → Journal: references · Balance snapshots are anchored to journal/transaction history.
- Mongo Tx → Lock: uses · Transactional writes can acquire and release locks.
- Mongo Tx → Medici Error: wraps · Transaction wrapper propagates domain failures.
- Void Memo → Reverse Tx: feeds · Void memo handling informs reversal transaction creation.
- Init Models → Journal: binds · Model initialization wires the journal schema.
- Init Models → Transaction: binds · Model initialization wires the transaction schema.
- Init Models → Balance: binds · Model initialization wires the balance cache model.
- Init Models → Lock: binds · Model initialization wires the lock model.
- Sync Indexes → Journal: syncs · Index management enforces journal indexes.
- Sync Indexes → Transaction: syncs · Index management enforces transaction indexes.
- ObjectId Keys → Transaction: supports · Custom schema support needs ObjectId path discovery.
- Flatten → Safe Meta: supports · Flattening and safe metadata shaping work together.
- Safe Meta → Transaction: protects · Metadata normalization feeds persistence safely.
- Medici Error → Consistency: base · Consistency failures derive from the shared error base.
- Medici Error → Account Path: base · Account path validation errors derive from the shared error base.
- Medici Error → Transaction: base · Transaction errors derive from the shared error base.
- Medici Error → Not Found: base · Missing journal errors derive from the shared error base.
- Medici Error → Voided Journal: base · Void conflicts derive from the shared error base.