• Stars
    star
    224
  • Rank 177,792 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An append-only B-tree running on a Hypercore

Hyperbee 🐝

See API docs at docs.holepunch.to

An append-only B-tree running on a Hypercore. Allows sorted iteration and more.

npm install hyperbee

Usage

const Hyperbee = require('hyperbee')
const Hypercore = require('hypercore')
const RAM = require('random-access-memory')

const core = new Hypercore(RAM)
const db = new Hyperbee(core, { keyEncoding: 'utf-8', valueEncoding: 'binary' })

// If you own the core
await db.put('key1', 'value1')
await db.put('key2', 'value2')
await db.del('some-key')

// If you want to insert/delete batched values
const batch = db.batch()

await batch.put('key', 'value')
await batch.del('some-key')
await batch.flush() // Execute the batch

// Query the core
const entry = await db.get('key') // => null or { key, value }

// Read all entries
for await (const entry of db.createReadStream()) {
  // ..
}

// Read a range
for await (const entry of db.createReadStream({ gte: 'a', lt: 'd' })) {
  // Anything >=a and <d
}

// Get the last written entry
for await (const entry of db.createHistoryStream({ reverse: true, limit: 1 })) {
  // ..
}

It works with sparse cores, only a small subset of the full core is downloaded to satisfy your queries.

API

const db = new Hyperbee(core, [options])

Make a new Hyperbee instance. core should be a Hypercore.

options include:

{
  keyEncoding: 'binary', // "binary" (default), "utf-8", "ascii", "json", or an abstract-encoding
  valueEncoding: 'binary' // Same options as keyEncoding like "json", etc
}

Note that currently read/diff streams sort based on the encoded value of the keys.

await db.ready()

Waits until internal state is loaded.

Use it once before reading synchronous properties like db.version, unless you called any of the other APIs.

await db.close()

Fully close this bee, including its core.

db.core

The underlying Hypercore backing this bee.

db.version

Number that indicates how many modifications were made, useful as a version identifier.

db.id

String containing the id (z-base-32 of the public key) identifying this bee.

db.key

Buffer containing the public key identifying this bee.

db.discoveryKey

Buffer containing a key derived from db.key.

This discovery key does not allow you to verify the data, it's only to announce or look for peers that are sharing the same bee, without leaking the bee key.

db.writable

Boolean indicating if we can put or delete data in this bee.

db.readable

Boolean indicating if we can read from this bee. After closing the bee this will be false.

await db.put(key, [value], [options])

Insert a new key. Value can be optional.

If you're inserting a series of data atomically or want more performance then check the db.batch API.

options includes:

{
  cas (prev, next) { return true }
}
Compare And Swap (cas)

cas option is a function comparator to control whether the put succeeds.

By returning true it will insert the value, otherwise it won't.

It receives two args: prev is the current node entry, and next is the potential new node.

await db.put('number', '123', { cas })
console.log(await db.get('number')) // => { seq: 1, key: 'number', value: '123' }

await db.put('number', '123', { cas })
console.log(await db.get('number')) // => { seq: 1, key: 'number', value: '123' }
// Without cas this would have been { seq: 2, ... }, and the next { seq: 3 }

await db.put('number', '456', { cas })
console.log(await db.get('number')) // => { seq: 2, key: 'number', value: '456' }

function cas (prev, next) {
  // You can use same-data or same-object lib, depending on the value complexity
  return prev.value !== next.value
}

const { seq, key, value } = await db.get(key)

Get a key's value. Returns null if key doesn't exists.

seq is the Hypercore index at which this key was inserted.

await db.del(key, [options])

Delete a key.

options include:

{
  cas (prev, next) { return true }
}
Compare And Swap (cas)

cas option is a function comparator to control whether the del succeeds.

By returning true it will delete the value, otherwise it won't.

It only receives one arg: prev which is the current node entry.

// This won't get deleted
await db.del('number', { cas })
console.log(await db.get('number')) // => { seq: 1, key: 'number', value: 'value' }

// Change the value so the next time we try to delete it then "cas" will return true
await db.put('number', 'can-be-deleted')

await db.del('number', { cas })
console.log(await db.get('number')) // => null

function cas (prev) {
  return prev.value === 'can-be-deleted'
}

const stream = db.replicate(isInitiatorOrStream)

See more about how replicate works at core.replicate.

const batch = db.batch()

Make a new atomic batch that is either fully processed or not processed at all.

If you have several inserts and deletions then a batch can be much faster.

await batch.put(key, [value], [options])

Insert a key into a batch.

options are the same as db.put method.

const { seq, key, value } = await batch.get(key)

Get a key, value out of a batch.

await batch.del(key, [options])

Delete a key into the batch.

options are the same as db.del method.

await batch.flush()

Commit the batch to the database, and releases any locks it has acquired.

await batch.close()

Destroy a batch, and releases any locks it has acquired on the db.

Call this if you want to abort a batch without flushing it.

const stream = db.createReadStream([range], [options])

Make a read stream. Sort order is based on the binary value of the keys.

All entries in the stream are similar to the ones returned from db.get.

range should specify the range you want to read and looks like this:

{
  gt: 'only return keys > than this',
  gte: 'only return keys >= than this',
  lt: 'only return keys < than this',
  lte: 'only return keys <= than this'
}

options include:

{
  reverse: false // Set to true to get them in reverse order,
  limit: -1 // Set to the max number of entries you want
}

const { seq, key, value } = await db.peek([range], [options])

Similar to doing a read stream and returning the first value, but a bit faster than that.

const stream = db.createHistoryStream([options])

Create a stream of all entries ever inserted or deleted from the db.

Each entry has an additional type property indicating if it was a put or del operation.

options include:

{
  live: false, // If true the stream will wait for new data and never end
  reverse: false, // If true get from the newest to the oldest
  gte: seq, // Start with this seq (inclusive)
  gt: seq, // Start after this index
  lte: seq, // Stop after this index
  lt: seq, // Stop before this index
  limit: -1 // Set to the max number of entries you want
}

If any of the gte, gt, lte, lt arguments are < 0 then they'll implicitly be added with the version before starting so doing { gte: -1 } makes a stream starting at the last index.

const stream = db.createDiffStream(otherVersion, [options])

Efficiently create a stream of the shallow changes between two versions of the db.

options are the same as db.createReadStream, except for reverse.

Each entry is sorted by key and looks like this:

{
  left: Object, // The entry in the `db`
  right: Object // The entry in `otherVersion`
}

If an entry exists in db but not in the other version, then left is set and right will be null, and vice versa.

If the entries are causally equal (i.e. the have the same seq), they are not returned, only the diff.

const entryWatcher = await db.getAndWatch(key, [options])

Returns a watcher which listens to changes on the given key.

entryWatcher.node contains the current entry in the same format as the result of bee.get(key), and will be updated as it changes.

By default, the node will have the bee's key- and value encoding, but you can overwrite it by setting the keyEncoding and valueEncoding options.

You can listen to entryWatcher.on('update') to be notified when the value of node has changed.

Call await watcher.close() to stop the watcher.

const watcher = db.watch([range])

Listens to changes that are on the optional range.

range options are the same as db.createReadStream except for reverse.

By default, the yielded snapshots will have the bee's key- and value encoding, but you can overwrite them by setting the keyEncoding and valueEncoding options.

Usage example:

for await (const [current, previous] of watcher) {
  console.log(current.version)
  console.log(previous.version)
}

Returns a new value after a change, current and previous are snapshots that are auto-closed before next value.

Don't close those snapshots yourself because they're used internally, let them be auto-closed.

Watchers on subs and checkouts are not supported. Instead, use the range option to limit scope.

await watcher.ready()

Waits until the watcher is loaded and detecting changes.

await watcher.close()

Stops the watcher. You could also stop it by using break in the loop.

const snapshot = db.checkout(version)

Get a read-only snapshot of a previous version.

const snapshot = db.snapshot()

Shorthand for getting a checkout for the current version.

const sub = db.sub('sub-prefix', options = {})

Create a sub-database where all entries will be prefixed by a given value.

This makes it easy to create namespaces within a single Hyperbee.

options include:

{
  sep: Buffer.alloc(1), // A namespace separator
  valueEncoding, // Optional sub valueEncoding (defaults to the parents)
  keyEncoding // Optional sub keyEncoding (defaults to the parents)
}

For example:

const root = new Hyperbee(core)
const sub = root.sub('a')

// In root, this will have the key ('a' + separator + 'b')
await sub.put('b', 'hello')

// Returns => { key: 'b', value: 'hello')
await sub.get('b')

const header = await db.getHeader([options])

Returns the header contained in the first block. Throws if undecodable.

options are the same as the core.get method.

const isHyperbee = await Hyperbee.isHyperbee(core, [options])

Returns true if the core contains a Hyperbee, false otherwise.

This requests the first block on the core, so it can throw depending on the options.

options are the same as the core.get method.

More Repositories

1

hypercore

Hypercore is a secure, distributed append-only log.
JavaScript
2,403
star
2

hyperdrive

Hyperdrive is a secure, real time distributed file system
JavaScript
1,794
star
3

hyperswarm

A distributed networking stack for connecting peers.
JavaScript
926
star
4

sodium-native

Low level bindings for libsodium
JavaScript
302
star
5

hyperdht

The DHT powering Hyperswarm
JavaScript
251
star
6

autobase

Autobase lets you write concise multiwriter data structures with Hypercore
JavaScript
84
star
7

corestore

A simple corestore that wraps a random-access-storage module
JavaScript
60
star
8

libudx

udx is reliable, multiplexed, and congestion-controlled streams over udp
C
40
star
9

hyperdrive-next

Hyperdrive is a secure, real-time distributed file system
JavaScript
37
star
10

hypercore-crypto

The crypto primitives used in hypercore, extracted into a separate module
JavaScript
36
star
11

hyperswarm-dht-relay

Relaying the Hyperswarm DHT over other transport protocols to bring decentralized networking to everyone
JavaScript
36
star
12

b4a

Bridging the gap between buffers and typed arrays
JavaScript
33
star
13

hyperblobs

A blob store for Hypercore
JavaScript
31
star
14

hypershell

Spawn shells anywhere. Fully peer-to-peer, authenticated, and end to end encrypted
JavaScript
31
star
15

hyperswarm-secret-stream

Secret stream backed by Noise and libsodium's secretstream
JavaScript
27
star
16

fs-native-extensions

Native file system extensions for advanced file operations
C
26
star
17

tiny-fs-native

Native fs for Javascript
JavaScript
24
star
18

keypear

🔑🍐 Keychain that derives deterministic Ed25519 keypairs and attestations
JavaScript
23
star
19

pear-expo-hello-world

C++
17
star
20

hyperswarm-seeders

A seeders only swarm
JavaScript
17
star
21

simple-seeder

Dead simple seeder with zero bugs
JavaScript
15
star
22

examples

Examples of basic flows for modules in the Holepunch ecosystem
JavaScript
15
star
23

noise-handshake

Simple noise handshake, supporting generic handshake patterns
JavaScript
13
star
24

localdrive

Hyperdrive but it is files
JavaScript
13
star
25

mirror-drive

Mirror two drives
JavaScript
12
star
26

tiny-http-native

Tiny HTTP library made purely on libuv and napi
JavaScript
12
star
27

libquickbit

The fastest bit in the West; a library for working with bit fields, accelerated using SIMD on supported hardware
C
11
star
28

drives

CLI to download, seed, and mirror a Hyperdrive or Localdrive
JavaScript
11
star
29

tiny-timers-native

Native timers for Javascript
JavaScript
9
star
30

udx-native

udx is reliable, multiplexed, and congestion-controlled streams over udp
JavaScript
9
star
31

libpearsync

Simple message passing between a libuv thread and something else
C
9
star
32

hyperswarm-doctor

Debugging tool for the swarm
JavaScript
7
star
33

netpaste

Copy and paste over the DHT
JavaScript
7
star
34

quickbit-universal

Universal wrapper for https://github.com/holepunchto/libquickbit with a JavaScript fallback
JavaScript
6
star
35

libcrc

Cross-platform implementation of CRC32 with hardware acceleration
C
6
star
36

hyperswarm-testnet

Small module to help you spin up a local Hyperswarm testnet
JavaScript
6
star
37

wasm-tools

A collection of useful tools for working with WASM/WAT in JavaScript
JavaScript
5
star
38

planb-summer-school

the workshop stuff
JavaScript
5
star
39

tt-native

https://github.com/holepunchto/libtt JavaScript bindings for Node.js
JavaScript
5
star
40

hypercore-id-encoding

Convert Hypercore keys to/from z-base32 or hex
JavaScript
4
star
41

serve-drive

HTTP drive server for entries delivery. Auto detects types like video, images, etc
JavaScript
4
star
42

autobase-test-helpers

Helpers when writing tests for an Autobased application
JavaScript
4
star
43

pear-radio-backend

Pear radio backend
JavaScript
4
star
44

nanodebug

A tiny, zero overhead debugging utility
JavaScript
4
star
45

crc-universal

Universal wrapper for https://github.com/holepunchto/libcrc with a JavaScript fallback
JavaScript
3
star
46

tiny-buffer-map

A very simple Map for Buffers and Uint8Arrays
JavaScript
3
star
47

quickbit-native

https://github.com/holepunchto/libquickbit JavaScript bindings for Node.js
JavaScript
3
star
48

tiny-paths

path for platforms without path
JavaScript
3
star
49

same-object

Determine if two objects are deeply equal
JavaScript
3
star
50

bare-expo

Example of embedding Bare in an Expo application using https://github.com/holepunchto/react-native-bare-kit
TypeScript
3
star
51

simdle-universal

Universal wrapper for https://github.com/holepunchto/libsimdle with a JavaScript fallback
JavaScript
2
star
52

libtt

Virtual console extensions built on libuv
C
2
star
53

cmake-ios

iOS utilities for CMake
CMake
2
star
54

cmake-binary

cmake binaries for windows, linux and macos
JavaScript
2
star
55

prebuild-containers

Containers for prebuilding native Node.js modules
Dockerfile
2
star
56

libsimdle

Simple and portable SIMD instructions for 128 bit vectors, inspired by the WASM SIMD specification
C
2
star
57

bits-to-bytes

Functions for doing bit manipulation of typed arrays
JavaScript
2
star
58

bare-addon

Template repository for creating Bare native addons
C
2
star
59

compact-encoding-bitfield

Compact codec for bitfields
JavaScript
2
star
60

seedbee

Bee for seeds
JavaScript
2
star
61

crc-native

https://github.com/holepunchto/libcrc JavaScript bindings for Node.js
Python
2
star
62

bare-utils

Node.js-compatible utility functions for Bare
JavaScript
2
star
63

bare-distributable-hello-world

Showing how to make a single distributable of a JS app
C
2
star
64

bare-debug-log

Simple debug log for JavaScript
JavaScript
2
star
65

pw-to-ek

Derive a secure encryption key from a password using the sodium's scrypt implementation.
JavaScript
2
star
66

cmake-drive

Drive utilities for CMake
1
star
67

cmake-bare-bundle

Bare bundling utilities for CMake
CMake
1
star
68

simdle-native

https://github.com/holepunchto/libsimdle JavaScript bindings for Node.js
C
1
star
69

native-pipe

Native named pipes
C
1
star
70

hp-rpc-cli

JavaScript
1
star
71

pear-inspect

JavaScript
1
star
72

drive-resolve

Asynchronous require resolution in Hyperdrive
JavaScript
1
star
73

warmup-encoding

Encode/decode sets of random blocks for warmup
JavaScript
1
star
74

framed-stream

Read/write stream messages prefixed 8, 16, 24 or 32 bit length
JavaScript
1
star
75

http-forward-host

Simple stream proxy that sniffs the HTTP host or x-forwarded-for header and allows you to to forward the stream based on that
JavaScript
1
star
76

hypertrace-prometheus

Add support for Prometheus/Grafana to hypertrace
JavaScript
1
star
77

bare-dns

Domain name resolution for JavaScript
C
1
star
78

fifofile

Userland FIFO file
JavaScript
1
star
79

bare-format

String formatting for JavaScript
JavaScript
1
star
80

secure-prompt

Securely prompt stdio using secure buffers
JavaScript
1
star
81

bare-headers

Development headers for Bare
JavaScript
1
star
82

bare-net

TCP and IPC servers and clients for JavaScript
JavaScript
1
star