build(deps): Bump golang.org/x/sync from 0.21.0 to 0.22.0
Bumps golang.org/x/sync from 0.21.0 to 0.22.0.
updated-dependencies:
- dependency-name: golang.org/x/sync dependency-version: 0.22.0 dependency-type: direct:production update-type: version-update:semver-minor …
Signed-off-by: dependabot[bot] support@github.com
版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9
京公网安备 11010802047560号
bbolt
bbolt is a fork of Ben Johnson’s Bolt key/value store. The purpose of this fork is to provide the Go community with an active maintenance and development target for Bolt; the goal is improved reliability and stability. bbolt includes bug fixes, performance enhancements, and features not found in Bolt while preserving backwards compatibility with the Bolt API.
Bolt is a pure Go key/value store inspired by Howard Chu’s LMDB project. The goal of the project is to provide a simple, fast, and reliable database for projects that don’t require a full database server such as Postgres or MySQL.
Since Bolt is meant to be used as such a low-level piece of functionality, simplicity is key. The API will be small and only focus on getting values and setting values. That’s it.
Project Status
Bolt is stable, the API is fixed, and the file format is fixed. Full unit test coverage and randomized black box testing are used to ensure database consistency and thread safety. Bolt is currently used in high-load production environments serving databases as large as 1TB. Many companies such as Shopify and Heroku use Bolt-backed services every day.
Project versioning
bbolt uses semantic versioning. API should not change between patch and minor releases. New minor versions may add additional features to the API.
Table of Contents
Getting Started
Installing
To start using
bbolt, install Go and rungo get:This will retrieve the library and update your
go.modandgo.sumfiles.To run the command line utility, execute:
Run
go installto install thebboltcommand line utility into your$GOBINpath, which defaults to$GOPATH/binor$HOME/go/binif theGOPATHenvironment variable is not set.Importing bbolt
To use bbolt as an embedded key-value store, import as:
Opening a database
The top-level object in Bolt is a
DB. It is represented as a single file on your disk and represents a consistent snapshot of your data.To open your database, simply use the
bolt.Open()function:Please note that Bolt obtains a file lock on the data file so multiple processes cannot open the same database at the same time. Opening an already open Bolt database will cause it to hang until the other process closes it. To prevent an indefinite wait you can pass a timeout option to the
Open()function:Transactions
Bolt allows only one read-write transaction at a time but allows as many read-only transactions as you want at a time. Each transaction has a consistent view of the data as it existed when the transaction started.
Individual transactions and all objects created from them (e.g. buckets, keys) are not thread safe. To work with data in multiple goroutines you must start a transaction for each one or use locking to ensure only one goroutine accesses a transaction at a time. Creating transaction from the
DBis thread safe.Transactions should not depend on one another and generally shouldn’t be opened simultaneously in the same goroutine. This can cause a deadlock as the read-write transaction needs to periodically re-map the data file but it cannot do so while any read-only transaction is open. Even a nested read-only transaction can cause a deadlock, as the child transaction can block the parent transaction from releasing its resources.
Read-write transactions
To start a read-write transaction, you can use the
DB.Update()function:Inside the closure, you have a consistent view of the database. You commit the transaction by returning
nilat the end. You can also rollback the transaction at any point by returning an error. All database operations are allowed inside a read-write transaction.Always check the return error as it will report any disk failures that can cause your transaction to not complete. If you return an error within your closure it will be passed through.
Read-only transactions
To start a read-only transaction, you can use the
DB.View()function:You also get a consistent view of the database within this closure, however, no mutating operations are allowed within a read-only transaction. You can only retrieve buckets, retrieve values, and copy the database within a read-only transaction.
Batch read-write transactions
Each
DB.Update()waits for disk to commit the writes. This overhead can be minimized by combining multiple updates with theDB.Batch()function:Concurrent Batch calls are opportunistically combined into larger transactions. Batch is only useful when there are multiple goroutines calling it.
The trade-off is that
Batchcan call the given function multiple times, if parts of the transaction fail. The function must be idempotent and side effects must take effect only after a successful return fromDB.Batch().For example: don’t display messages from inside the function, instead set variables in the enclosing scope:
Managing transactions manually
The
DB.View()andDB.Update()functions are wrappers around theDB.Begin()function. These helper functions will start the transaction, execute a function, and then safely close your transaction if an error is returned. This is the recommended way to use Bolt transactions.However, sometimes you may want to manually start and end your transactions. You can use the
DB.Begin()function directly but please be sure to close the transaction.The first argument to
DB.Begin()is a boolean stating if the transaction should be writable.Using buckets
Buckets are collections of key/value pairs within the database. All keys in a bucket must be unique. You can create a bucket using the
Tx.CreateBucket()function:You can retrieve an existing bucket using the
Tx.Bucket()function:You can also create a bucket only if it doesn’t exist by using the
Tx.CreateBucketIfNotExists()function. It’s a common pattern to call this function for all your top-level buckets after you open your database so you can guarantee that they exist for future transactions.To delete a bucket, simply call the
Tx.DeleteBucket()function.You can also iterate over all existing top-level buckets with
Tx.ForEach():Using key/value pairs
To save a key/value pair to a bucket, use the
Bucket.Put()function:This will set the value of the
"answer"key to"42"in theMyBucketbucket. To retrieve this value, we can use theBucket.Get()function:The
Get()function does not return an error because its operation is guaranteed to work (unless there is some kind of system failure). If the key exists then it will return its byte slice value. If it doesn’t exist then it will returnnil. It’s important to note that you can have a zero-length value set to a key which is different than the key not existing.Use the
Bucket.Delete()function to delete a key from the bucket:This will delete the key
answersfrom the bucketMyBucket.Please note that values returned from
Get()are only valid while the transaction is open. If you need to use a value outside of the transaction then you must usecopy()to copy it to another byte slice.Autoincrementing integer for the bucket
By using the
NextSequence()function, you can let Bolt determine a sequence which can be used as the unique identifier for your key/value pairs. See the example below.Iterating over keys
Bolt stores its keys in byte-sorted order within a bucket. This makes sequential iteration over these keys extremely fast. To iterate over keys we’ll use a
Cursor:The cursor allows you to move to a specific point in the list of keys and move forward or backward through the keys one at a time.
The following functions are available on the cursor:
Each of those functions has a return signature of
(key []byte, value []byte). You must seek to a position usingFirst(),Last(), orSeek()before callingNext()orPrev(). If you do not seek to a position then these functions will return anilkey.When you have iterated to the end of the cursor, then
Next()will return anilkey and the cursor still points to the last element if present. When you have iterated to the beginning of the cursor, thenPrev()will return anilkey and the cursor still points to the first element if present.If you remove key/value pairs during iteration, the cursor may automatically move to the next position if present in current node each time removing a key. When you call
c.Next()after removing a key, it may skip one key/value pair. Refer to pull/611 to get more detailed info.During iteration, if the key is non-
nilbut the value isnil, that means the key refers to a bucket rather than a value. UseBucket.Bucket()to access the sub-bucket.Prefix scans
To iterate over a key prefix, you can combine
Seek()andbytes.HasPrefix():Range scans
Another common use case is scanning over a range such as a time range. If you use a sortable time encoding such as RFC3339 then you can query a specific date range like this:
Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.
ForEach()
You can also use the function
ForEach()if you know you’ll be iterating over all the keys in a bucket:Please note that keys and values in
ForEach()are only valid while the transaction is open. If you need to use a key or value outside of the transaction, you must usecopy()to copy it to another byte slice.Nested buckets
You can also store a bucket in a key to create nested buckets. The API is the same as the bucket management API on the
DBobject:Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.
Database backups
Bolt is a single file so it’s easy to backup. You can use the
Tx.WriteTo()function to write a consistent view of the database to a writer. If you call this from a read-only transaction, it will perform a hot backup and not block your other database reads and writes.By default, it will use a regular file handle which will utilize the operating system’s page cache. See the
Txdocumentation for information about optimizing for larger-than-RAM datasets.One common use case is to backup over HTTP so you can use tools like
cURLto do database backups:Then you can backup using this command:
Or you can open your browser to
http://localhost/backupand it will download automatically.If you want to backup to another file you can use the
Tx.CopyFile()helper function.Statistics
The database keeps a running count of many of the internal operations it performs so you can better understand what’s going on. By grabbing a snapshot of these stats at two points in time we can see what operations were performed in that time range.
For example, we could start a goroutine to log stats every 10 seconds:
It’s also useful to pipe these stats to a service such as statsd for monitoring or to provide an HTTP endpoint that will perform a fixed-length sample.
Read-Only Mode
Sometimes it is useful to create a shared, read-only Bolt database. To this, set the
Options.ReadOnlyflag when opening your database. Read-only mode uses a shared lock to allow multiple processes to read from the database but it will block any processes from opening the database in read-write mode.Mobile Use (iOS/Android)
Bolt is able to run on mobile devices by leveraging the binding feature of the gomobile tool. Create a struct that will contain your database logic and a reference to a
*bolt.DBwith a initializing constructor that takes in a filepath where the database file will be stored. Neither Android nor iOS require extra permissions or cleanup from using this method.Database logic should be defined as methods on this wrapper struct.
To initialize this struct from the native language (both platforms now sync their local storage to the cloud. These snippets disable that functionality for the database file):
Android
iOS
Resources
For more information on getting started with Bolt, check out the following articles:
Comparison with other databases
Postgres, MySQL, & other relational databases
Relational databases structure data into rows and are only accessible through the use of SQL. This approach provides flexibility in how you store and query your data but also incurs overhead in parsing and planning SQL statements. Bolt accesses all data by a byte slice key. This makes Bolt fast to read and write data by key but provides no built-in support for joining values together.
Most relational databases (with the exception of SQLite) are standalone servers that run separately from your application. This gives your systems flexibility to connect multiple application servers to a single database server but also adds overhead in serializing and transporting data over the network. Bolt runs as a library included in your application so all data access has to go through your application’s process. This brings data closer to your application but limits multi-process access to the data.
LevelDB, RocksDB
LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that they are libraries bundled into the application, however, their underlying structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes random writes by using a write ahead log and multi-tiered, sorted files called SSTables. Bolt uses a B+tree internally and only a single file. Both approaches have trade-offs.
If you require a high random write throughput (>10,000 w/sec) or you need to use spinning disks then LevelDB could be a good choice. If your application is read-heavy or does a lot of range scans then Bolt could be a good choice.
One other important consideration is that LevelDB does not have transactions. It supports batch writing of key/values pairs and it supports read snapshots but it will not give you the ability to do a compare-and-swap operation safely. Bolt supports fully serializable ACID transactions.
LMDB
Bolt was originally a port of LMDB so it is architecturally similar. Both use a B+tree, have ACID semantics with fully serializable transactions, and support lock-free MVCC using a single writer and multiple readers.
The two projects have somewhat diverged. LMDB heavily focuses on raw performance while Bolt has focused on simplicity and ease of use. For example, LMDB allows several unsafe actions such as direct writes for the sake of performance. Bolt opts to disallow actions which can leave the database in a corrupted state. The only exception to this in Bolt is
DB.NoSync.There are also a few differences in API. LMDB requires a maximum mmap size when opening an
mdb_envwhereas Bolt will handle incremental mmap resizing automatically. LMDB overloads the getter and setter functions with multiple flags whereas Bolt splits these specialized cases into their own functions.Caveats & Limitations
It’s important to pick the right tool for the job and Bolt is no exception. Here are a few things to note when evaluating and using Bolt:
Bolt is good for read intensive workloads. Sequential write performance is also fast but random writes can be slow. You can use
DB.Batch()or add a write-ahead log to help mitigate this issue.Bolt uses a B+tree internally so there can be a lot of random page access. SSDs provide a significant performance boost over spinning disks.
Try to avoid long running read transactions. Bolt uses copy-on-write so old pages cannot be reclaimed while an old transaction is using them.
Byte slices returned from Bolt are only valid during a transaction. Once the transaction has been committed or rolled back then the memory they point to can be reused by a new page or can be unmapped from virtual memory and you’ll see an
unexpected fault addresspanic when accessing it.Bolt uses an exclusive write lock on the database file so it cannot be shared by multiple processes.
Be careful when using
Bucket.FillPercent. Setting a high fill percent for buckets that have random inserts will cause your database to have very poor page utilization.Use larger buckets in general. Smaller buckets causes poor page utilization once they become larger than the page size (typically 4KB).
Bulk loading a lot of random writes into a new bucket can be slow as the page will not split until the transaction is committed. Randomly inserting more than 100,000 key/value pairs into a single new bucket in a single transaction is not advised.
Bolt uses a memory-mapped file so the underlying operating system handles the caching of the data. Typically, the OS will cache as much of the file as it can in memory and will release memory as needed to other processes. This means that Bolt can show very high memory usage when working with large databases. However, this is expected and the OS will release memory as needed. Bolt can handle databases much larger than the available physical RAM, provided its memory-map fits in the process virtual address space. It may be problematic on 32-bits systems.
The data structures in the Bolt database are memory mapped so the data file will be endian specific. This means that you cannot copy a Bolt file from a little endian machine to a big endian machine and have it work. For most users this is not a concern since most modern CPUs are little endian.
Because of the way pages are laid out on disk, Bolt cannot truncate data files and return free pages back to the disk. Instead, Bolt maintains a free list of unused pages within its data file. These free pages can be reused by later transactions. This works well for many use cases as databases generally tend to grow. However, it’s important to note that deleting large chunks of data will not allow you to reclaim that space on disk.
For more information on page allocation, see this comment.
Removing key/values pairs in a bucket during iteration on the bucket using cursor may not work properly. Each time when removing a key/value pair, the cursor may automatically move to the next position if present. When users call
c.Next()after removing a key, it may skip one key/value pair. Refer to https://github.com/etcd-io/bbolt/pull/611 for more detailed info.Bolt db can be corrupted during the initialization phase due to abrupt power failure.
Reading the Source
Bolt is a relatively small code base (<5KLOC) for an embedded, serializable, transactional key/value database so it can be a good starting point for people interested in how databases work.
The best places to start are the main entry points into Bolt:
Open()- Initializes the reference to the database. It’s responsible for creating the database if it doesn’t exist, obtaining an exclusive lock on the file, reading the meta pages, & memory-mapping the file.DB.Begin()- Starts a read-only or read-write transaction depending on the value of thewritableargument. This requires briefly obtaining the “meta” lock to keep track of open transactions. Only one read-write transaction can exist at a time so the “rwlock” is acquired during the life of a read-write transaction.Bucket.Put()- Writes a key/value pair into a bucket. After validating the arguments, a cursor is used to traverse the B+tree to the page and position where the key & value will be written. Once the position is found, the bucket materializes the underlying page and the page’s parent pages into memory as “nodes”. These nodes are where mutations occur during read-write transactions. These changes get flushed to disk during commit.Bucket.Get()- Retrieves a key/value pair from a bucket. This uses a cursor to move to the page & position of a key/value pair. During a read-only transaction, the key and value data is returned as a direct reference to the underlying mmap file so there’s no allocation overhead. For read-write transactions, this data may reference the mmap file or one of the in-memory node values.Cursor- This object is simply for traversing the B+tree of on-disk pages or in-memory nodes. It can seek to a specific key, move to the first or last value, or it can move forward or backward. The cursor handles the movement up and down the B+tree transparently to the end user.Tx.Commit()- Converts the in-memory dirty nodes and the list of free pages into pages to be written to disk. Writing to disk then occurs in two phases. First, the dirty pages are written to disk and anfsync()occurs. Second, a new meta page with an incremented transaction ID is written and anotherfsync()occurs. This two phase write ensures that partially written data pages are ignored in the event of a crash since the meta page pointing to them is never written. Partially written meta pages are invalidated because they are written with a checksum.If you have additional notes that could be helpful for others, please submit them via pull request.
Known Issues
bbolt might run into data corruption issue on Linux when the feature ext4: fast commit, which was introduced in linux kernel version v5.10, is enabled. The fixes to the issue are included in stable LTS patchlevels 5.10.94+ and 5.15.17+ (ftruncate tracking), plus 5.15.27+ (ineligible-commit fallback). Linux 5.17 includes these fixes as well, but 5.17 is not an LTS release. Please refer to links below,
Please also refer to the discussion in https://github.com/etcd-io/bbolt/issues/562.
Writing a value with a length of 0 will always result in reading back an empty
[]byte{}value. Please refer to issues/726#issuecomment-2061694802.Other Projects Using Bolt
Below is a list of public, open source projects that use Bolt:
If you are using Bolt in a project please send a pull request to add it to the list.