fix: multi-repo local dev (file:../ deps, package exports, missing deps)

This commit is contained in:
Raven Scott
2026-05-21 20:14:15 -04:00
parent fc17ec7445
commit dfc3315572
395 changed files with 51601 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
cmake_minimum_required(VERSION 4.0)
find_package(cmake-bare REQUIRED PATHS node_modules/cmake-bare)
find_package(cmake-fetch REQUIRED PATHS node_modules/cmake-fetch)
find_package(cmake-napi REQUIRED PATHS node_modules/cmake-napi)
find_package(cmake-npm REQUIRED PATHS node_modules/cmake-npm)
project(rocksdb_native C CXX)
bare_target(target)
fetch_package("github:holepunchto/librocksdb#efb0607")
fetch_package("github:holepunchto/libjstl#387f6d0")
add_bare_module(rocksdb_native_bare)
target_sources(
${rocksdb_native_bare}
PRIVATE
binding.cc
)
target_link_libraries(
${rocksdb_native_bare}
PRIVATE
$<TARGET_OBJECTS:rocksdb>
jstl
PUBLIC
rocksdb
rocksdb_facebook
)
add_napi_module(rocksdb_native_napi)
target_sources(
${rocksdb_native_napi}
PRIVATE
binding.cc
)
target_compile_definitions(
${rocksdb_native_napi}
PRIVATE
NAPI_VERSION=9
)
target_link_libraries(
${rocksdb_native_napi}
PRIVATE
$<TARGET_OBJECTS:rocksdb>
jstl
PUBLIC
rocksdb
rocksdb_facebook
)
resolve_node_module(bare-compat-napi compat)
target_include_directories(
${rocksdb_native_napi}
PRIVATE
"${compat}/include"
)
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+32
View File
@@ -0,0 +1,32 @@
# rocksdb-native
<https://github.com/holepunchto/librocksdb> bindings for JavaScript.
```
npm i rocksdb-native
```
> [!IMPORTANT]
> On Linux `libatomic` must be installed as well.
## Usage
```js
const RocksDB = require('rocksdb-native')
const db = new RocksDB('./example.db')
const w = db.write()
w.put('hello', 'world')
await w.flush()
const r = db.read()
const p = r.get('hello')
r.flush()
console.log(await p)
```
## License
Apache-2.0
+1869
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
+223
View File
@@ -0,0 +1,223 @@
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')
class RocksDB {
constructor(path, opts = {}) {
const {
columnFamily,
state = new State(this, path, opts),
snapshot = null,
keyEncoding = null,
valueEncoding = null
} = opts
this._state = state
this._snapshot = snapshot
this._columnFamily = state.getColumnFamily(columnFamily)
this._keyEncoding = keyEncoding
this._valueEncoding = valueEncoding
this._index = -1
this._state.addSession(this)
}
get opened() {
return this._state.opened
}
get closed() {
return this.isRoot() ? this._state.closed : this._index === -1
}
get path() {
return this._state.path
}
get stats() {
return this._state.stats
}
get snapshotted() {
return this._snapshot !== null
}
get defaultColumnFamily() {
return this._columnFamily
}
session({
columnFamily = this._columnFamily,
snapshot = this._snapshot !== null,
keyEncoding = this._keyEncoding,
valueEncoding = this._valueEncoding
} = {}) {
maybeClosed(this)
return new RocksDB(null, {
state: this._state,
columnFamily,
snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
keyEncoding,
valueEncoding
})
}
columnFamily(name, opts) {
return this.session({ ...opts, columnFamily: name })
}
snapshot() {
return this.session({ snapshot: true })
}
isRoot() {
return this === this._state.db
}
ready() {
return this._state.ready()
}
async close({ force } = {}) {
if (!this._state.opened) await this._state.ready()
if (this._index !== -1) this._state.removeSession(this)
if (force) {
while (this._state.sessions.length > 0) {
await this._state.sessions[this._state.sessions.length - 1].close()
}
}
return this.isRoot() ? this._state.close() : Promise.resolve()
}
suspend() {
maybeClosed(this)
return this._state.suspend()
}
resume() {
maybeClosed(this)
return this._state.resume()
}
isIdle() {
return this._state.handles.isIdle()
}
idle() {
return this._state.handles.idle()
}
iterator(range, opts) {
maybeClosed(this)
return new Iterator(this, { ...range, ...opts })
}
async *keys(range, opts) {
for await (const { key } of this.iterator(range, {
...opts,
values: false
})) {
yield key
}
}
async peek(range, opts) {
for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
return value
}
return null
}
read(opts) {
maybeClosed(this)
return this._state.createReadBatch(this, opts)
}
write(opts) {
maybeClosed(this)
return this._state.createWriteBatch(this, opts)
}
flush(opts) {
maybeClosed(this)
return this._state.flush(this, opts)
}
async get(key, opts) {
const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
const value = batch.get(key)
batch.tryFlush()
return value
}
async put(key, value, opts) {
const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
batch.tryPut(key, value)
await batch.flush()
}
async delete(key, opts) {
const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
batch.tryDelete(key)
await batch.flush()
}
async deleteRange(start, end, opts) {
const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
batch.tryDeleteRange(start, end)
await batch.flush()
}
async compactRange(start = null, end = null, opts = {}) {
if (typeof end === 'object' && end !== null) {
opts = end
end = null
} else if (typeof start === 'object' && start !== null) {
opts = start
start = null
end = null
}
await this._state.compactRange(this, start, end, opts)
}
async approximateSize(start, end, opts = {}) {
return this._state.approximateSize(this, start, end, opts)
}
_ref() {
if (this._snapshot) this._snapshot.ref()
this._state.handles.inc()
}
_unref() {
if (this._snapshot) this._snapshot.unref()
this._state.handles.dec()
}
}
module.exports = exports = RocksDB
exports.constants = constants
exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy
function maybeClosed(db) {
if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
+438
View File
@@ -0,0 +1,438 @@
const c = require('compact-encoding')
const binding = require('../binding')
const empty = Buffer.alloc(0)
const resolved = Promise.resolve()
class RocksDBBatch {
constructor(db, opts = {}) {
const { capacity = 8, autoDestroy = false } = opts
db._ref()
this._db = db
this._destroyed = false
this._capacity = capacity
this._operations = []
this._promises = []
this._enqueuePromise = this._enqueuePromise.bind(this)
this._request = null
this._resolve = null
this._reject = null
this._handle = null
this._buffer = null
this._autoDestroy = autoDestroy
this._stats = null
this._resetStats()
if (db._state.opened === true) this.ready()
}
_reuse(db, opts = {}) {
const { autoDestroy = false } = opts
db._ref()
this._db = db
this._destroyed = false
this._autoDestroy = autoDestroy
}
_onfinished(err) {
const resolve = this._resolve
const reject = this._reject
if (this._request) this._db._state.io.dec()
this._operations = []
this._promises = []
this._request = null
this._resolve = null
this._reject = null
this._resetStats()
if (this._autoDestroy === true) this.destroy()
if (reject !== null && err) reject(err)
else if (resolve !== null) resolve()
}
_resize() {
if (this._operations.length <= this._capacity) return false
while (this._operations.length > this._capacity) {
this._capacity *= 2
}
return true
}
async ready() {
if (this._handle !== null) return
if (this._db._state.opened === false) await this._db._state.ready()
this._init()
}
destroy() {
if (this._request) throw new Error('Request in progress')
if (this._destroyed) return
this._destroyed = true
if (this._promises.length) this._abort()
this._db._unref()
this._onfree()
}
_onfree() {
this._resetStats()
this._db._state.freeBatch(this, false)
this._db = null
}
_abort() {
for (let i = 0; i < this._promises.length; i++) {
const promise = this._promises[i]
if (promise !== null) promise.reject(new Error('Batch is destroyed'))
}
this._onfinished(new Error('Batch is destroyed'))
}
_resetStats() {}
async flush() {
if (this._request) throw new Error('Request in progress')
if (this._destroyed) throw new Error('Batch is destroyed')
this._request = new Promise((resolve, reject) => {
this._resolve = resolve
this._reject = reject
})
this._flush()
return this._request
}
tryFlush() {
if (this._request) throw new Error('Request in progress')
if (this._destroyed) throw new Error('Batch is destroyed')
this._request = resolved
this._flush()
}
async _flush() {
if (this._handle === null) await this.ready()
this._db._state.io.inc()
if (this._db._state.resumed !== null) {
const resumed = await this._db._state.resumed.promise
if (!resumed) {
if (this._destroyed) {
this._db._state.io.dec()
} else {
this._destroyed = true
this._abort()
this._db._unref()
}
}
}
}
_enqueuePromise(resolve, reject) {
this._promises.push({ resolve, reject })
}
_encodeKey(k) {
if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
if (typeof k === 'string') return Buffer.from(k)
return k
}
_encodeValue(v) {
if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
if (v === null) return empty
if (typeof v === 'string') return Buffer.from(v)
return v
}
_decodeValue(b) {
if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
return b
}
}
exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
constructor(db, opts = {}) {
super(db, opts)
const { asyncIO = false, fillCache = true } = opts
this._asyncIO = asyncIO
this._fillCache = fillCache
}
_init() {
this._handle = binding.readInit()
this._buffer = binding.readBuffer(this._handle, this._capacity)
}
_resize() {
if (super._resize() && this._handle !== null) {
this._buffer = binding.readBuffer(this._handle, this._capacity)
}
}
async _flush() {
await super._flush()
if (this._destroyed) return
try {
binding.read(
this._db._state._handle,
this._handle,
this._operations,
this._db._snapshot ? this._db._snapshot._handle : undefined,
this._asyncIO,
this._fillCache,
this,
this._onread
)
} catch (err) {
this._db._state.io.dec()
throw err
}
this._db._state.stats.gets += this._stats.gets
this._db._state.stats.readBatches++
}
_onread(errs, values) {
let applied = true
for (let i = 0, n = this._promises.length; i < n; i++) {
const err = errs[i]
if (err) applied = false
const promise = this._promises[i]
if (promise === null) continue
if (err) promise.reject(err)
else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
}
this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
}
_resetStats() {
this._stats = { gets: 0 }
}
get(key) {
if (this._request) throw new Error('Request already in progress')
this._stats.gets++
const promise = new Promise(this._enqueuePromise)
this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))
this._resize()
return promise
}
}
exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
_init() {
this._handle = binding.writeInit()
this._buffer = binding.writeBuffer(this._handle, this._capacity)
}
_resize() {
if (super._resize() && this._handle !== null) {
this._buffer = binding.writeBuffer(this._handle, this._capacity)
}
}
_onfree() {
this._resetStats()
this._db._state.freeBatch(this, true)
this._db = null
}
async _flush() {
await super._flush()
if (this._destroyed) return
try {
binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
} catch (err) {
this._db._state.io.dec()
throw err
}
this._db._state.stats.puts += this._stats.puts
this._db._state.stats.deletes += this._stats.deletes
this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
this._db._state.stats.writeBatches++
}
_onwrite(err) {
const applied = !err
for (let i = 0, n = this._promises.length; i < n; i++) {
const promise = this._promises[i]
if (promise === null) continue
if (err) promise.reject(err)
else promise.resolve()
}
this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
}
_resetStats() {
this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
}
put(key, value) {
if (this._request) throw new Error('Request already in progress')
this._stats.puts++
const promise = new Promise(this._enqueuePromise)
this._operations.push(
new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
)
this._resize()
return promise
}
tryPut(key, value) {
if (this._request) throw new Error('Request already in progress')
this._stats.puts++
this._operations.push(
new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
)
this._promises.push(null)
this._resize()
}
delete(key) {
if (this._request) throw new Error('Request already in progress')
this._stats.deletes++
const promise = new Promise(this._enqueuePromise)
this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))
this._resize()
return promise
}
tryDelete(key) {
if (this._request) throw new Error('Request already in progress')
this._stats.deletes++
this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))
this._promises.push(null)
this._resize()
}
deleteRange(start, end) {
if (this._request) throw new Error('Request already in progress')
this._stats.rangeDeletes++
const promise = new Promise(this._enqueuePromise)
this._operations.push(
new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
)
this._resize()
return promise
}
tryDeleteRange(start, end) {
if (this._request) throw new Error('Request already in progress')
this._stats.rangeDeletes++
this._operations.push(
new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
)
this._promises.push(null)
this._resize()
}
}
class RocksDBGet {
constructor(key, columnFamily) {
this.key = key
this.columnFamily = columnFamily._handle
}
get type() {
return binding.GET
}
}
class RocksDBPut {
constructor(key, value, columnFamily) {
this.key = key
this.value = value
this.columnFamily = columnFamily._handle
}
get type() {
return binding.PUT
}
}
class RocksDBDelete {
constructor(key, columnFamily) {
this.key = key
this.columnFamily = columnFamily._handle
}
get type() {
return binding.DELETE
}
}
class RocksDBDeleteRange {
constructor(start, end, columnFamily) {
this.start = start
this.end = end
this.columnFamily = columnFamily._handle
}
get type() {
return binding.DELETE_RANGE
}
}
+108
View File
@@ -0,0 +1,108 @@
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')
class RocksDBColumnFamily {
constructor(name, opts = {}) {
const {
// Blob options
enableBlobFiles = false,
minBlobSize = 0,
blobFileSize = 0,
enableBlobGarbageCollection = true,
// Block table options
tableBlockSize = 8192,
tableCacheIndexAndFilterBlocks = true,
tableFormatVersion = 6,
optimizeFiltersForMemory = false,
blockCache = true,
filterPolicy = new BloomFilterPolicy(10),
topLevelIndexPinningTier = constants.pinningTier.ALL,
partitionPinningTier = constants.pinningTier.ALL,
unpartitionedPinningTier = constants.pinningTier.ALL,
optimizeFiltersForHits = false,
numLevels = 7,
maxWriteBufferNumber = 2,
blobGarbageCollectionAgeCutOff = 0.25,
blobGarbageCollectionForceThreshold = 1.0
} = opts
this._name = name
this._flushing = null
this._options = {
enableBlobFiles,
minBlobSize,
blobFileSize,
enableBlobGarbageCollection,
tableBlockSize,
tableCacheIndexAndFilterBlocks,
tableFormatVersion,
optimizeFiltersForMemory,
blockCache,
filterPolicy,
topLevelIndexPinningTier,
partitionPinningTier,
unpartitionedPinningTier,
optimizeFiltersForHits,
numLevels,
maxWriteBufferNumber
}
const filterPolicyArguments = [0, 0, 0]
if (filterPolicy !== null) {
filterPolicyArguments[0] = filterPolicy.type
switch (filterPolicy.type) {
case 1: // Bloom filter policy
filterPolicyArguments[1] = filterPolicy.bitsPerKey
break
case 2: // Ribbon filter policy
filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel
break
}
}
this._handle = binding.columnFamilyInit(
name,
enableBlobFiles,
minBlobSize,
blobFileSize,
enableBlobGarbageCollection,
tableBlockSize,
tableCacheIndexAndFilterBlocks,
tableFormatVersion,
optimizeFiltersForMemory,
blockCache === false,
...filterPolicyArguments,
topLevelIndexPinningTier,
partitionPinningTier,
unpartitionedPinningTier,
optimizeFiltersForHits,
numLevels,
maxWriteBufferNumber,
blobGarbageCollectionAgeCutOff,
blobGarbageCollectionForceThreshold
)
}
cloneSettings(name) {
return new RocksDBColumnFamily(name, this._options)
}
get name() {
return this._name
}
destroy() {
if (this._handle === null) return
binding.columnFamilyDestroy(this._handle)
this._handle = null
}
}
module.exports = RocksDBColumnFamily
+23
View File
@@ -0,0 +1,23 @@
module.exports = {
pinningTier: {
NONE: 0,
FLUSHED_AND_SIMILAR: 1,
ALL: 2
},
garbageCollectionPolicy: {
DEFAULT: 0,
FORCE: 1,
DISABLE: 2
},
bottommostLevelCompaction: {
NONE: 0,
SKIP: 1,
FORCE: 2
},
walRecoveryMode: {
TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
ABSOLUTE_CONSISTENCY: 1,
POINT_IN_TIME: 2,
SKIP_ANY_CORRUPTED_RECORDS: 3
}
}
+20
View File
@@ -0,0 +1,20 @@
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
get type() {
return 1
}
constructor(bitsPerKey) {
this.bitsPerKey = bitsPerKey
}
}
exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
get type() {
return 2
}
constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
this.bloomBeforeLevel = bloomBeforeLevel
}
}
+208
View File
@@ -0,0 +1,208 @@
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')
const empty = Buffer.alloc(0)
module.exports = class RocksDBIterator extends Readable {
constructor(db, opts = {}) {
const {
gt = null,
gte = null,
lt = null,
lte = null,
reverse = false,
values = true,
limit = Infinity,
capacity = 8
} = opts
super()
db._ref()
this._db = db
this._gt = gt ? this._encodeKey(gt) : empty
this._gte = gte ? this._encodeKey(gte) : empty
this._lt = lt ? this._encodeKey(lt) : empty
this._lte = lte ? this._encodeKey(lte) : empty
this._reverse = reverse
this._values = values
this._limit = limit < 0 ? Infinity : limit
this._capacity = capacity
this._opened = false
this._pendingOpen = null
this._pendingRead = null
this._pendingDestroy = null
this._buffer = null
this._handle = null
if (this._db._state.opened === true) this.ready()
}
_onopen(err) {
const cb = this._pendingOpen
this._pendingOpen = null
this._opened = true
this._db._state.io.dec()
cb(err)
}
_onread(err, keys, values) {
const cb = this._pendingRead
this._pendingRead = null
this._db._state.io.dec()
if (err) return cb(err)
const n = keys.length
this._limit -= n
for (let i = 0; i < n; i++) {
this.push({
key: this._decodeKey(Buffer.from(keys[i])),
value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
})
}
if (n < this._capacity) this.push(null)
cb(null)
}
_onclose(err) {
const cb = this._pendingDestroy
this._pendingDestroy = null
this._db._state.io.dec()
this._db._unref()
cb(err)
}
_resize() {
if (this._handle !== null) {
this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
}
}
async ready() {
if (this._handle !== null) return
if (this._db._state.opened === false) await this._db._state.ready()
this._init()
}
_init() {
this._handle = binding.iteratorInit()
this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
}
async _open(cb) {
await this.ready()
this._db._state.io.inc()
if (this._db._state.resumed !== null) {
const resumed = await this._db._state.resumed.promise
if (!resumed) {
this._db._state.io.dec()
return cb(new Error('RocksDB session is closed'))
}
}
this._pendingOpen = cb
try {
binding.iteratorOpen(
this._db._state._handle,
this._handle,
this._db._columnFamily._handle,
this._gt,
this._gte,
this._lt,
this._lte,
this._reverse,
!this._values, // Keys only
this._db._snapshot ? this._db._snapshot._handle : undefined,
this,
this._onopen,
this._onclose,
this._onread
)
} catch (err) {
this._db._state.io.dec()
cb(err)
}
}
async _read(cb) {
this._db._state.io.inc()
if (this._db._state.resumed !== null) {
const resumed = await this._db._state.resumed.promise
if (!resumed) {
this._db._state.io.dec()
return cb(new Error('RocksDB session is closed'))
}
}
this._pendingRead = cb
try {
binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
} catch (err) {
this._db._state.io.dec()
cb(err)
}
}
async _destroy(cb) {
await this.ready()
this._db._state.io.inc()
if (this._opened === false) {
this._db._state.io.dec()
this._db._unref()
return cb(null)
}
this._pendingDestroy = cb
try {
binding.iteratorClose(this._handle)
} catch (err) {
this._db._state.io.dec()
this._db._unref()
cb(err)
}
}
_encodeKey(k) {
if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
if (typeof k === 'string') return Buffer.from(k)
return k
}
_decodeKey(b) {
if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
return b
}
_decodeValue(b) {
if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
return b
}
}
+30
View File
@@ -0,0 +1,30 @@
const binding = require('../binding')
module.exports = class RocksDBSnapshot {
constructor(state) {
this._state = state
this._handle = null
this._refs = 0
if (state.deferSnapshotInit === false) this._init()
}
_init() {
this._handle = binding.snapshotCreate(this._state._handle)
}
ref() {
this._refs++
}
unref() {
if (--this._refs > 0) return
if (this._handle === null) return
binding.snapshotDestroy(this._handle)
this._handle = null
}
}
+435
View File
@@ -0,0 +1,435 @@
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')
const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)
module.exports = class RocksDBState extends ReadyResource {
constructor(db, path, opts) {
super()
const {
columnFamily = new ColumnFamily('default', opts),
columnFamilies = [],
readOnly = false,
createIfMissing = true,
createMissingColumnFamilies = true,
maxBackgroundJobs = 6,
bytesPerSync = 1048576,
maxOpenFiles = -1,
useDirectReads = false,
avoidUnnecessaryBlockingIO = false,
skipStatsUpdateOnOpen = false,
useDirectIOForFlushAndCompaction = false,
maxFileOpeningThreads = 16,
lock = null,
walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
bestEffortsRecovery = false
} = opts
this.path = path
this.db = db
this.handles = new RefCounter()
this.io = new RefCounter()
this.sessions = []
this.columnFamilies = [columnFamily]
this.deferSnapshotInit = true
this.resumed = null
this.stats = {
gets: 0,
puts: 0,
deletes: 0,
rangeDeletes: 0,
readBatches: 0,
writeBatches: 0
}
this._suspended = false
this._suspending = false
this._updating = false
this._updatingSignal = new SignalPromise()
this._columnsFlushed = false
this._lock = lock
this._readBatches = []
this._writeBatches = []
for (const columnFamily of columnFamilies) {
this.columnFamilies.push(
typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
)
}
this._handle = binding.init(
readOnly,
createIfMissing,
createMissingColumnFamilies,
maxBackgroundJobs,
bytesPerSync,
maxOpenFiles,
useDirectReads,
avoidUnnecessaryBlockingIO,
skipStatsUpdateOnOpen,
useDirectIOForFlushAndCompaction,
maxFileOpeningThreads,
walRecoveryMode,
bestEffortsRecovery
)
}
createReadBatch(db, opts) {
if (this._readBatches.length === 0) return new ReadBatch(db, opts)
const batch = this._readBatches.pop()
batch._reuse(db, opts)
return batch
}
createWriteBatch(db, opts) {
if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
const batch = this._writeBatches.pop()
batch._reuse(db, opts)
return batch
}
freeBatch(batch, writable) {
if (batch._capacity > 16) return
const queue = writable ? this._writeBatches : this._readBatches
if (queue.length >= MAX_BATCH_REUSE) return
queue.push(batch)
}
addSession(db) {
db._index = this.sessions.push(db) - 1
if (db._snapshot) db._snapshot.ref()
}
removeSession(db) {
const head = this.sessions.pop()
if (head !== db) this.sessions[(head._index = db._index)] = head
db._index = -1
if (db._snapshot) db._snapshot.unref()
}
upsertColumnFamily(c) {
if (typeof c === 'string') {
let col = this.getColumnFamilyByName(c)
if (col) return col
col = this.columnFamilies[0].cloneSettings(c)
this.columnFamilies.push(col)
return col
}
if (this.columnFamilies.includes(c)) return c
this.columnFamilies.push(c)
return c
}
getColumnFamily(c) {
if (!c) return this.columnFamilies[0]
if (!this._columnsFlushed) return this.upsertColumnFamily(c)
if (typeof c !== 'string') return c
const col = this.getColumnFamilyByName(c)
if (col === null) throw new Error('Unknown column family')
return col
}
getColumnFamilyByName(name) {
for (const col of this.columnFamilies) {
if (col.name === name) return col
}
return null
}
async _open() {
await Promise.resolve() // Allow column families to populate if on-demand
if (this._lock) await this._lock.ready()
const req = { resolve: null, reject: null, handle: null }
const promise = new Promise((resolve, reject) => {
req.resolve = resolve
req.reject = reject
})
this._columnsFlushed = true
const lock = this._lock === null ? -1 : this._lock.transfer()
req.handle = binding.open(
this._handle,
this,
this.path,
this.columnFamilies.map((c) => c._handle),
lock,
req,
onopen
)
await promise
this.deferSnapshotInit = false
for (const session of this.sessions) {
if (session._snapshot) session._snapshot._init()
}
function onopen(err) {
if (err) req.reject(err)
else req.resolve()
}
}
async _close() {
while (this._updating) await this._updatingSignal.wait()
if (this.resumed) this.resumed.resolve(false)
while (!this.io.isIdle()) await this.io.idle()
while (!this.handles.isIdle()) await this.handles.idle()
while (this.sessions.length > 0) {
await this.sessions[this.sessions.length - 1].close()
}
for (const columnFamily of this.columnFamilies) columnFamily.destroy()
const req = { resolve: null, reject: null, handle: null }
const promise = new Promise((resolve, reject) => {
req.resolve = resolve
req.reject = reject
})
req.handle = binding.close(this._handle, req, onclose)
try {
await promise
} finally {
if (this._lock) await this._lock.close()
}
function onclose(err) {
if (err) req.reject(err)
else req.resolve()
}
}
async flush(db, opts) {
if (this.opened === false) await this.ready()
this.io.inc()
if (this.resumed !== null) {
const resumed = await this.resumed.promise
if (!resumed) {
this.io.dec()
throw new Error('RocksDB session is closed')
}
}
const req = { resolve: null, reject: null, handle: null }
const promise = new Promise((resolve, reject) => {
req.resolve = resolve
req.reject = reject
})
try {
req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)
await promise
} finally {
this.io.dec()
}
function onflush(err) {
if (err) req.reject(err)
else req.resolve()
}
}
suspend() {
this._suspending = true
return this.update()
}
resume() {
this._suspending = false
return this.update()
}
async update() {
while (this._updating) await this._updatingSignal.wait()
if (this._suspending === this._suspended || this.closing) return
this._updating = true
try {
if (this._suspending) await this._suspend()
else await this._resume()
} finally {
this._updating = false
this._updatingSignal.notify()
}
}
async _suspend() {
if (this._suspended === true) return
while (!this.io.isIdle()) await this.io.idle()
this.io.inc()
this.resumed = rrp()
const req = { resolve: null, reject: null, handle: null }
const promise = new Promise((resolve, reject) => {
req.resolve = resolve
req.reject = reject
})
try {
req.handle = binding.suspend(this._handle, req, onsuspend)
await promise
this._suspended = true
} finally {
this.io.dec()
}
function onsuspend(err) {
if (err) req.reject(err)
else req.resolve()
}
}
async _resume() {
if (this._suspended === false) return
const req = { resolve: null, reject: null, handle: null }
const promise = new Promise((resolve, reject) => {
req.resolve = resolve
req.reject = reject
})
req.handle = binding.resume(this._handle, req, onresume)
await promise
this._suspended = false
const resumed = this.resumed
this.resumed = null
resumed.resolve(true)
function onresume(err) {
if (err) req.reject(err)
else req.resolve()
}
}
async compactRange(db, start, end, opts) {
if (this.opened === false) await this.ready()
this.io.inc()
const {
exclusive = false,
blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
blobGarbageCollectionAgeCutoff = 0.25,
bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
} = opts
start = this._encodeKey(start)
end = this._encodeKey(end)
const req = { resolve: null, reject: null, handle: null, start, end }
const promise = new Promise((resolve, reject) => {
req.resolve = resolve
req.reject = reject
})
try {
req.handle = binding.compactRange(
this._handle,
db._columnFamily._handle,
start,
end,
exclusive,
blobGarbageCollectionPolicy,
blobGarbageCollectionAgeCutoff,
bottommostLevelCompaction,
req,
oncompactrange
)
await promise
} finally {
this.io.dec()
}
function oncompactrange(err) {
if (err) req.reject(err)
else req.resolve()
}
}
async approximateSize(db, start, end, opts) {
if (this.opened === false) await this.ready()
this.io.inc()
const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts
start = this._encodeKey(start)
end = this._encodeKey(end)
const req = { resolve: null, reject: null, handle: null, start, end }
const promise = new Promise((resolve, reject) => {
req.resolve = resolve
req.reject = reject
})
try {
req.handle = binding.approximateSize(
this._handle,
db._columnFamily._handle,
start,
end,
includeMemtables,
includeFiles,
filesSizeErrorMargin,
req,
onapproximatesize
)
return await promise
} finally {
this.io.dec()
}
function onapproximatesize(err, result) {
if (err) req.reject(err)
else req.resolve(result)
}
}
_encodeKey(k) {
if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
if (typeof k === 'string') return Buffer.from(k)
if (k === null) return empty
return k
}
}
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+165
View File
@@ -0,0 +1,165 @@
# compact-encoding
A series of compact encoding schemes for building small and fast parsers and serializers
```
npm install compact-encoding
```
## Usage
```js
const cenc = require('compact-encoding')
const state = cenc.state()
// use preencode to figure out how big a buffer is needed
cenc.uint.preencode(state, 42)
cenc.string.preencode(state, 'hi')
console.log(state) // { start: 0, end: 4, buffer: null }
state.buffer = Buffer.allocUnsafe(state.end)
// then use encode to actually encode it to the buffer
cenc.uint.encode(state, 42)
cenc.string.encode(state, 'hi')
// to decode it simply use decode instead
state.start = 0
cenc.uint.decode(state) // 42
cenc.string.decode(state) // 'hi'
```
## Encoder API
#### `state`
Should be an object that looks like this `{ start, end, buffer }`.
You can also get a blank state object using `cenc.state()`.
- `start` is the byte offset to start encoding/decoding at.
- `end` is the byte offset indicating the end of the buffer.
- `buffer` should be either a Node.js Buffer or Uint8Array.
#### `enc.preencode(state, val)`
Does a fast preencode dry-run that only sets state.end.
Use this to figure out how big of a buffer you need.
#### `enc.encode(state, val)`
Encodes `val` into `state.buffer` at position `state.start`.
Updates `state.start` to point after the encoded value when done.
#### `val = enc.decode(state)`
Decodes a value from `state.buffer` as position `state.start`.
Updates `state.start` to point after the decoded value when done in the buffer.
## Helpers
If you are just encoding to a buffer or decoding from one you can use the `encode` and `decode` helpers
to reduce your boilerplate
```js
const buf = cenc.encode(cenc.bool, true)
const bool = cenc.decode(cenc.bool, buf)
```
## Bundled encodings
The following encodings are bundled as they are primitives that can be used
to build others on top. Feel free to PR more that are missing.
- `cenc.raw` - Pass through encodes a buffer, i.e. a basic copy.
- `cenc.uint` - Encodes a uint using the smallest fixed size encoding with a prefix to signal which one. Useful for uints that can be a wide range of values.
- `cenc.uint8` - Encodes a fixed size uint8.
- `cenc.uint16` - Encodes a fixed size uint16. Useful for things like ports.
- `cenc.uint24` - Encodes a fixed size uint24. Useful for message framing.
- `cenc.uint32` - Encodes a fixed size uint32. Useful for very large message framing.
- `cenc.uint40` - Encodes a fixed size uint40.
- `cenc.uint48` - Encodes a fixed size uint48.
- `cenc.uint56` - Encodes a fixed size uint56.
- `cenc.uint64` - Encodes a fixed size uint64.
- `cenc.int` - Encodes an int using `cenc.uint` with ZigZag encoding.
- `cenc.int8` - Encodes a fixed size int8 using `cenc.uint8` with ZigZag encoding.
- `cenc.int16` - Encodes a fixed size int16 using `cenc.uint16` with ZigZag encoding.
- `cenc.int24` - Encodes a fixed size int24 using `cenc.uint24` with ZigZag encoding.
- `cenc.int32` - Encodes a fixed size int32 using `cenc.uint32` with ZigZag encoding.
- `cenc.int40` - Encodes a fixed size int40 using `cenc.uint40` with ZigZag encoding.
- `cenc.int48` - Encodes a fixed size int48 using `cenc.uint48` with ZigZag encoding.
- `cenc.int56` - Encodes a fixed size int56 using `cenc.uint56` with ZigZag encoding.
- `cenc.int64` - Encodes a fixed size int64 using `cenc.uint64` with ZigZag encoding.
- `cenc.biguint64` - Encodes a fixed size biguint64.
- `cenc.bigint64` - Encodes a fixed size bigint64 using `cenc.biguint64` with ZigZag encoding.
- `cenc.biguint` - Encodes a biguint with its word count uint prefixed.
- `cenc.bigint` - Encodes a bigint using `cenc.biguint` with ZigZag encoding.
- `cenc.float32` - Encodes a fixed size float32.
- `cenc.float64` - Encodes a fixed size float64.
- `cenc.buffer` - Encodes a buffer with its length uint prefixed. When decoding an empty buffer, `null` is returned.
- `cenc.raw.buffer` - Encodes a buffer without a length prefixed.
- `cenc.arraybuffer` - Encodes an arraybuffer with its length uint prefixed.
- `cenc.raw.arraybuffer` - Encodes an arraybuffer without a length prefixed.
- `cenc.uint8array` - Encodes a uint8array with its element length uint prefixed.
- `cenc.raw.uint8array` - Encodes a uint8array without a length prefixed.
- `cenc.uint16array` - Encodes a uint16array with its element length uint prefixed.
- `cenc.raw.uint16array` - Encodes a uint16array without a length prefixed.
- `cenc.uint32array` - Encodes a uint32array with its element length uint prefixed.
- `cenc.raw.uint32array` - Encodes a uint32array without a length prefixed.
- `cenc.int8array` - Encodes a int8array with its element length uint prefixed.
- `cenc.raw.int8array` - Encodes a int8array without a length prefixed.
- `cenc.int16array` - Encodes a int16array with its element length uint prefixed.
- `cenc.raw.int16array` - Encodes a int16array without a length prefixed.
- `cenc.int32array` - Encodes a int32array with its element length uint prefixed.
- `cenc.raw.int32array` - Encodes a int32array without a length prefixed.
- `cenc.biguint64array` - Encodes a biguint64array with its element length uint prefixed.
- `cenc.raw.biguint64array` - Encodes a biguint64array without a length prefixed.
- `cenc.bigint64array` - Encodes a bigint64array with its element length uint prefixed.
- `cenc.raw.bigint64array` - Encodes a bigint64array without a length prefixed.
- `cenc.float32array` - Encodes a float32array with its element length uint prefixed.
- `cenc.raw.float32array` - Encodes a float32array without a length prefixed.
- `cenc.float64array` - Encodes a float64array with its element length uint prefixed.
- `cenc.raw.float64array` - Encodes a float64array without a length prefixed.
- `cenc.bool` - Encodes a boolean as 1 or 0.
- `cenc.string`, `cenc.utf8` - Encodes a utf-8 string, similar to buffer.
- `cenc.raw.string`, `cenc.raw.utf8` - Encodes a utf-8 string without a length prefixed.
- `cenc.string.fixed(n)`, `cenc.utf8.fixed(n)` - Encodes a fixed sized utf-8 string.
- `cenc.ascii` - Encodes an ascii string.
- `cenc.raw.ascii` - Encodes an ascii string without a length prefixed.
- `cenc.ascii.fixed(n)` - Encodes a fixed size ascii string.
- `cenc.hex` - Encodes a hex string.
- `cenc.raw.hex` - Encodes a hex string without a length prefixed.
- `cenc.hex.fixed(n)` - Encodes a fixed size hex string.
- `cenc.base64` - Encodes a base64 string.
- `cenc.raw.base64` - Encodes a base64 string without a length prefixed.
- `cenc.base64.fixed(n)` - Encodes a fixed size base64 string.
- `cenc.utf16le`, `cenc.ucs2` - Encodes a utf16le string.
- `cenc.raw.utf16le`, `cenc.raw.ucs2` - Encodes a utf16le string without a length prefixed.
- `cenc.utf16le.fixed(n)`, `cenc.ucs2.fixed(n)` - Encodes a fixed size utf16le string.
- `cenc.fixed32` - Encodes a fixed 32 byte buffer.
- `cenc.fixed64` - Encodes a fixed 64 byte buffer.
- `cenc.fixed(n)` - Makes a fixed sized encoder.
- `cenc.date(d)` - Encodes a date object.
- `cenc.array(enc)` - Makes an array encoder from another encoder. Arrays are uint prefixed with their length.
- `cenc.raw.array(enc)` - Makes an array encoder from another encoder, without a length prefixed.
- `cenc.json` - Encodes a JSON value as utf-8.
- `cenc.raw.json` - Encodes a JSON value as utf-8 without a length prefixed.
- `cenc.ndjson` - Encodes a JSON value as newline delimited utf-8.
- `cenc.raw.ndjson` - Encodes a JSON value as newline delimited utf-8 without a length prefixed.
- `cenc.any` - Encodes any JSON representable value into a self described buffer. Like JSON + buffer, but using compact types. Useful for schemaless codecs.
- `cenc.port` - Encodes a port number for network addresses.
- `cenc.ipv4` - Encodes an IPv4 network address.
- `cenc.ipv4Address` Encodes an IPv4 network address and a port number.
- `cenc.ipv6` - Encodes an IPv6 network address.
- `cenc.ipv6Address` Encodes an IPv6 network address and a port number.
- `cenc.ip` - Encodes a dual IPv4/6 network address.
- `cenc.ipAddress` Encodes a dual IPv4/6 network address and a port number.
- `cenc.from(enc)` - Makes a compact encoder from a [codec](https://github.com/mafintosh/codecs) or [abstract-encoding](https://github.com/mafintosh/abstract-encoding).
- `cenc.none` - Helper for when you want to just express nothing
## License
Apache 2.0
+4
View File
@@ -0,0 +1,4 @@
const LE = (exports.LE =
new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)
exports.BE = !LE
File diff suppressed because it is too large Load Diff
+117
View File
@@ -0,0 +1,117 @@
module.exports = {
preencode,
encode,
decode
}
function preencode(state, num) {
if (num < 251) {
state.end++
} else if (num < 256) {
state.end += 2
} else if (num < 0x10000) {
state.end += 3
} else if (num < 0x1000000) {
state.end += 4
} else if (num < 0x100000000) {
state.end += 5
} else {
state.end++
const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
preencode(state, exp)
state.end += 6
}
}
function encode(state, num) {
const max = 251
const x = num - max
if (num < max) {
state.buffer[state.start++] = num
} else if (num < 256) {
state.buffer[state.start++] = max
state.buffer[state.start++] = x
} else if (num < 0x10000) {
state.buffer[state.start++] = max + 1
state.buffer[state.start++] = (x >> 8) & 0xff
state.buffer[state.start++] = x & 0xff
} else if (num < 0x1000000) {
state.buffer[state.start++] = max + 2
state.buffer[state.start++] = x >> 16
state.buffer[state.start++] = (x >> 8) & 0xff
state.buffer[state.start++] = x & 0xff
} else if (num < 0x100000000) {
state.buffer[state.start++] = max + 3
state.buffer[state.start++] = x >> 24
state.buffer[state.start++] = (x >> 16) & 0xff
state.buffer[state.start++] = (x >> 8) & 0xff
state.buffer[state.start++] = x & 0xff
} else {
// need to use Math here as bitwise ops are 32 bit
const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
state.buffer[state.start++] = 0xff
encode(state, exp)
const rem = x / Math.pow(2, exp - 11)
for (let i = 5; i >= 0; i--) {
state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
}
}
}
function decode(state) {
const max = 251
if (state.end - state.start < 1) throw new Error('Out of bounds')
const flag = state.buffer[state.start++]
if (flag < max) return flag
if (state.end - state.start < flag - max + 1) {
throw new Error('Out of bounds.')
}
if (flag < 252) {
return state.buffer[state.start++] + max
}
if (flag < 253) {
return (
(state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
)
}
if (flag < 254) {
return (
(state.buffer[state.start++] << 16) +
(state.buffer[state.start++] << 8) +
state.buffer[state.start++] +
max
)
}
// << 24 result may be interpreted as negative
if (flag < 255) {
return (
state.buffer[state.start++] * 0x1000000 +
(state.buffer[state.start++] << 16) +
(state.buffer[state.start++] << 8) +
state.buffer[state.start++] +
max
)
}
const exp = decode(state)
if (state.end - state.start < 6) throw new Error('Out of bounds')
let rem = 0
for (let i = 5; i >= 0; i--) {
rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
}
return rem * Math.pow(2, exp - 11) + max
}
+34
View File
@@ -0,0 +1,34 @@
{
"name": "compact-encoding",
"version": "3.1.0",
"description": "A series of compact encoding schemes for building small and fast parsers and serializers",
"main": "index.js",
"files": [
"endian.js",
"index.js",
"lexint.js",
"raw.js"
],
"dependencies": {
"b4a": "^1.3.0"
},
"devDependencies": {
"brittle": "^3.0.0",
"prettier": "^3.6.2",
"prettier-config-holepunch": "^1.0.0"
},
"scripts": {
"format": "prettier . --write",
"test": "prettier . --check && brittle test.js"
},
"repository": {
"type": "git",
"url": "https://github.com/holepunchto/compact-encoding.git"
},
"author": "Mathias Buus (@mafintosh)",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/compact-encoding/issues"
},
"homepage": "https://github.com/holepunchto/compact-encoding"
}
+170
View File
@@ -0,0 +1,170 @@
const b4a = require('b4a')
const { BE } = require('./endian')
exports = module.exports = {
preencode(state, b) {
state.end += b.byteLength
},
encode(state, b) {
state.buffer.set(b, state.start)
state.start += b.byteLength
},
decode(state) {
const b = state.buffer.subarray(state.start, state.end)
state.start = state.end
return b
}
}
const buffer = (exports.buffer = {
preencode(state, b) {
uint8array.preencode(state, b)
},
encode(state, b) {
uint8array.encode(state, b)
},
decode(state) {
const b = state.buffer.subarray(state.start)
state.start = state.end
return b
}
})
exports.binary = {
...buffer,
preencode(state, b) {
if (typeof b === 'string') utf8.preencode(state, b)
else buffer.preencode(state, b)
},
encode(state, b) {
if (typeof b === 'string') utf8.encode(state, b)
else buffer.encode(state, b)
}
}
exports.arraybuffer = {
preencode(state, b) {
state.end += b.byteLength
},
encode(state, b) {
const view = new Uint8Array(b)
state.buffer.set(view, state.start)
state.start += b.byteLength
},
decode(state) {
const b = new ArrayBuffer(state.end - state.start)
const view = new Uint8Array(b)
view.set(state.buffer.subarray(state.start))
state.start = state.end
return b
}
}
function typedarray(TypedArray, swap) {
const n = TypedArray.BYTES_PER_ELEMENT
return {
preencode(state, b) {
state.end += b.byteLength
},
encode(state, b) {
const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)
if (BE && swap) swap(view)
state.buffer.set(view, state.start)
state.start += b.byteLength
},
decode(state) {
let b = state.buffer.subarray(state.start)
if (b.byteOffset % n !== 0) b = new Uint8Array(b)
if (BE && swap) swap(b)
state.start = state.end
return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
}
}
}
const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)
exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)
exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)
exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)
function string(encoding) {
return {
preencode(state, s) {
state.end += b4a.byteLength(s, encoding)
},
encode(state, s) {
state.start += b4a.write(state.buffer, s, state.start, encoding)
},
decode(state) {
const s = b4a.toString(state.buffer, encoding, state.start)
state.start = state.end
return s
}
}
}
const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')
exports.array = function array(enc) {
return {
preencode(state, list) {
for (const value of list) enc.preencode(state, value)
},
encode(state, list) {
for (const value of list) enc.encode(state, value)
},
decode(state) {
const arr = []
while (state.start < state.end) arr.push(enc.decode(state))
return arr
}
}
}
exports.json = {
preencode(state, v) {
utf8.preencode(state, JSON.stringify(v))
},
encode(state, v) {
utf8.encode(state, JSON.stringify(v))
},
decode(state) {
return JSON.parse(utf8.decode(state))
}
}
exports.ndjson = {
preencode(state, v) {
utf8.preencode(state, JSON.stringify(v) + '\n')
},
encode(state, v) {
utf8.encode(state, JSON.stringify(v) + '\n')
},
decode(state) {
return JSON.parse(utf8.decode(state))
}
}
+77
View File
@@ -0,0 +1,77 @@
{
"name": "rocksdb-native",
"version": "3.15.1",
"description": "librocksdb bindings for JavaScript",
"exports": {
".": "./index.js",
"./package": "./package.json"
},
"imports": {
"crypto": {
"bare": "bare-crypto",
"default": "crypto"
},
"fs": {
"bare": "bare-fs",
"default": "fs"
},
"path": {
"bare": "bare-path",
"default": "path"
}
},
"files": [
"index.js",
"binding.cc",
"binding.js",
"CMakeLists.txt",
"lib",
"prebuilds",
"!prebuilds/android-*/**/*.node"
],
"addon": true,
"scripts": {
"format": "prettier --write . && lunte --fix",
"lint": "prettier --check . && lunte",
"test": "npm run test:bare && npm run test:node",
"test:bare": "brittle-bare --coverage test.js",
"test:node": "brittle-node --coverage test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holepunchto/rocksdb-native.git"
},
"author": "Holepunch Inc",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/rocksdb-native/issues"
},
"homepage": "https://github.com/holepunchto/rocksdb-native",
"engines": {
"bare": ">=1.16.0"
},
"dependencies": {
"compact-encoding": "^3.0.0",
"ready-resource": "^1.0.0",
"refcounter": "^1.0.0",
"require-addon": "^1.0.2",
"resolve-reject-promise": "^1.1.0",
"signal-promise": "^1.0.3",
"streamx": "^2.16.1"
},
"devDependencies": {
"bare-compat-napi": "^1.3.0",
"bare-crypto": "^1.12.0",
"bare-fs": "^4.5.0",
"bare-path": "^3.0.0",
"brittle": "^3.5.0",
"cmake-bare": "^1.1.14",
"cmake-fetch": "^1.0.1",
"cmake-napi": "^1.0.6",
"fd-lock": "^2.0.0",
"lunte": "^1.8.0",
"paparam": "^1.9.0",
"prettier": "^3.6.2",
"prettier-config-holepunch": "^2.0.0"
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.