Skip to content
This repository was archived by the owner on Dec 2, 2024. It is now read-only.

Commit f207ae6

Browse files
authored
Drop support of key & value types other than string and Buffer (#179)
1 parent 69645a4 commit f207ae6

18 files changed

+329
-873
lines changed

README.md

Lines changed: 9 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# level-js
22

3-
> An [`abstract-leveldown`][abstract-leveldown] compliant store on top of [IndexedDB][indexeddb], which is in turn implemented on top of [LevelDB][leveldb] which brings this whole shebang full circle.
3+
> An [`abstract-leveldown`][abstract-leveldown] compliant store on top of [IndexedDB][indexeddb].
44
55
[![level badge][level-badge]][awesome]
66
[![npm](https://img.shields.io/npm/v/level-js.svg?label=&logo=npm)](https://www.npmjs.com/package/level-js)
@@ -35,13 +35,11 @@ Here are the goals of `level-js`:
3535

3636
- Store large amounts of data in modern browsers
3737
- Pass the full [`abstract-leveldown`][abstract-leveldown] test suite
38-
- Support [`Buffer`][buffer] keys and values
39-
- Support all key types of IndexedDB Second Edition
40-
- Support all value types of the [structured clone algorithm][structured-clone-algorithm] except for `null` and `undefined`
38+
- Support string and [`Buffer`][buffer] keys and values
4139
- Be as fast as possible
42-
- Sync with [multilevel](https://github.com/juliangruber/multilevel) over ASCII or binary transports.
40+
- ~~Sync with [multilevel](https://github.com/juliangruber/multilevel) over ASCII or binary transports.~~
4341

44-
Being `abstract-leveldown` compliant means you can use many of the [Level modules][awesome] on top of this library. For some demos of it working, see [**@brycebaril**](https://github.com/brycebaril)'s presentation [Path of the NodeBases Jedi](http://brycebaril.github.io/nodebase_jedi/#/vanilla).
42+
Being `abstract-leveldown` compliant means you can use many of the [Level modules][awesome] on top of this library.
4543

4644
## Example
4745

@@ -80,120 +78,17 @@ const value = await db.get('hello')
8078

8179
## Type Support
8280

83-
Unlike [`leveldown`][leveldown], `level-js` does not stringify keys or values. This means that in addition to strings and Buffers you can store almost any JavaScript type without the need for [`encoding-down`][encoding-down].
81+
Keys and values can be a string or [`Buffer`][buffer]. Any other type will be irreversibly stringified. The only exceptions are `null` and `undefined`. Keys and values of that type are rejected.
8482

85-
### Values
83+
In order to sort string and Buffer keys the same way, for compatibility with `leveldown` and the larger ecosystem, `level-js` internally converts keys and values to binary before passing them to IndexedDB. If binary keys are not supported by the environment (like IE11) `level-js` falls back to `String(key)`.
8684

87-
All value types of the [structured clone algorithm][structured-clone-algorithm] are supported except for `null` and `undefined`. Depending on the environment, this includes:
85+
If you desire non-destructive encoding (e.g. to store and retrieve numbers as-is), wrap `level-js` with [`encoding-down`][encoding-down]. Alternatively install [`level`][level] which conveniently bundles [`levelup`][levelup], `level-js` and `encoding-down`. Such an approach is also recommended if you want to achieve universal (isomorphic) behavior. For example, you could have [`leveldown`][leveldown] in a backend and `level-js` in the frontend. The `level` package does exactly that.
8886

89-
- Number, including `NaN`, `Infinity` and `-Infinity`
90-
- String, Boolean, Date, RegExp, Array, Object
91-
- ArrayBuffer or a view thereof (typed arrays);
92-
- Map, Set, Blob, File, FileList, ImageData (limited support).
93-
94-
In addition `level-js` stores [`Buffer`][buffer] values without transformation. This works in all target environments because `Buffer` is a subclass of `Uint8Array`, meaning such values can be passed to `IndexedDB` as-is.
95-
96-
When getting or iterating binary values, regardless of whether they were stored as a `Buffer`, `ArrayBuffer` or a view thereof, values will return as a `Buffer`. This behavior can be disabled, in which case `ArrayBuffer` returns as `ArrayBuffer`, typed arrays return as typed arrays and `Buffer` returns as `Uint8Array`:
87+
When getting or iterating keys and values, regardless of the type with which they were stored, keys and values will return as a Buffer unless the `asBuffer`, `keyAsBuffer` or `valueAsBuffer` options are set, in which case strings are returned. Setting these options is not needed when `level-js` is wrapped with `encoding-down`, which determines the optimal return type by the chosen encoding.
9788

9889
```js
9990
db.get('key', { asBuffer: false })
100-
db.iterator({ valueAsBuffer: false })
101-
```
102-
103-
If the environment does not support a type, it will throw an error which `level-js` catches and passes to the callbacks of `put` or `batch`. For example, IE does not support typed array values. At the time of writing, Chrome is the only browser that supports all types listed above.
104-
105-
### Keys
106-
107-
All key types of IndexedDB Second Edition are supported. Depending on the environment, this includes:
108-
109-
- Number, including `Infinity` and `-Infinity`, but not `NaN`
110-
- Date, except invalid (`NaN`)
111-
- String
112-
- ArrayBuffer or a view thereof (typed arrays);
113-
- Array, except cyclical, empty and sparse arrays. Elements must be valid types themselves.
114-
115-
In addition you can use [`Buffer`][buffer] keys, giving `level-js` the same power as implementations like `leveldown` and `memdown`. When iterating binary keys, regardless of whether they were stored as `Buffer`, `ArrayBuffer` or a view thereof, keys will return as a `Buffer`. This behavior can be disabled, in which case binary keys will always return as `ArrayBuffer`:
116-
117-
```js
118-
db.iterator({ keyAsBuffer: false })
119-
```
120-
121-
Note that this behavior is slightly different from values due to the way that IndexedDB works. IndexedDB stores binary _values_ using the structured clone algorithm, which preserves views, but it stores binary _keys_ as an array of octets, so that it is able to compare and sort differently typed keys.
122-
123-
If the environment does not support a type, it will throw an error which `level-js` catches and passes to the callbacks of `get`, `put`, `del`, `batch` or an iterator. Exceptions are:
124-
125-
- `null` and `undefined`: rejected early by `abstract-leveldown`
126-
- Binary and array keys: if not supported by the environment, `level-js` falls back to `String(key)`.
127-
128-
### Normalization
129-
130-
If you desire normalization for keys and values (e.g. to stringify numbers), wrap `level-js` with [`encoding-down`][encoding-down]. Alternatively install [`level`][level] which conveniently bundles [`levelup`][levelup], `level-js` and `encoding-down`. Such an approach is also recommended if you want to achieve universal (isomorphic) behavior or to smooth over type differences between browsers. For example, you could have [`leveldown`][leveldown] in a backend and `level-js` in the frontend. The `level` package does exactly that.
131-
132-
Another reason you might want to use `encoding-down` is that the structured clone algorithm, while rich in types, can be slower than `JSON.stringify`.
133-
134-
### Sort Order
135-
136-
Unless `level-js` is wrapped with [`encoding-down`][encoding-down], IndexedDB will sort your keys in the following order:
137-
138-
1. number (numeric)
139-
2. date (numeric, by epoch offset)
140-
3. binary (bitwise)
141-
4. string (lexicographic)
142-
5. array (componentwise).
143-
144-
You can take advantage of this fact with `levelup` streams. For example, if your keys are dates, you can select everything greater than a specific date (let's be happy and ignore timezones for a moment):
145-
146-
```js
147-
const db = levelup(leveljs('time-db'))
148-
149-
db.createReadStream({ gt: new Date('2019-01-01') })
150-
.pipe(..)
151-
```
152-
153-
Or if your keys are arrays, you can do things like:
154-
155-
```js
156-
const db = levelup(leveljs('books-db'))
157-
158-
await db.put(['Roald Dahl', 'Charlie and the Chocolate Factory'], {})
159-
await db.put(['Roald Dahl', 'Fantastic Mr Fox'], {})
160-
161-
// Select all books by Roald Dahl
162-
db.createReadStream({ gt: ['Roald Dahl'], lt: ['Roald Dahl', '\xff'] })
163-
.pipe(..)
164-
```
165-
166-
To achieve this on other `abstract-leveldown` implementations, wrap them with [`encoding-down`][encoding-down] and [`charwise`][charwise] (or similar).
167-
168-
#### Known Browser Issues
169-
170-
IE11 and Edge yield incorrect results for `{ gte: '' }` if the database contains any key types other than strings.
171-
172-
### Buffer vs ArrayBuffer
173-
174-
For interoperability it is recommended to use `Buffer` as your binary type. While we recognize that Node.js core modules are moving towards supporting `ArrayBuffer` and views thereof, `Buffer` remains the primary binary type in the Level ecosystem.
175-
176-
That said: if you want to `put()` an `ArrayBuffer` you can! Just know that it will come back as a `Buffer` by default. If you want to `get()` or iterate stored `ArrayBuffer` data as an `ArrayBuffer`, you have a few options. Without `encoding-down`:
177-
178-
```js
179-
const db = levelup(leveljs('mydb'))
180-
181-
// Yields an ArrayBuffer, Buffer and ArrayBuffer
182-
const value1 = await db.get('key', { asBuffer: false })
183-
const value2 = await db.get('key')
184-
const value3 = value2.buffer
185-
```
186-
187-
With `encoding-down` (or `level`) you can use the `id` encoding to selectively bypass encodings:
188-
189-
```js
190-
const encode = require('encoding-down')
191-
const db = levelup(encode(leveljs('mydb'), { valueEncoding: 'binary' }))
192-
193-
// Yields an ArrayBuffer, Buffer and ArrayBuffer
194-
const value1 = await db.get('key', { valueEncoding: 'id' })
195-
const value2 = await db.get('key')
196-
const value3 = value2.buffer
91+
db.iterator({ keyAsBuffer: false, valueAsBuffer: false })
19792
```
19893

19994
## Install
@@ -268,22 +163,16 @@ To sustain [`Level`](https://github.com/Level) and its activities, become a back
268163

269164
[indexeddb]: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
270165

271-
[leveldb]: https://github.com/google/leveldb
272-
273166
[buffer]: https://nodejs.org/api/buffer.html
274167

275168
[awesome]: https://github.com/Level/awesome
276169

277170
[abstract-leveldown]: https://github.com/Level/abstract-leveldown
278171

279-
[charwise]: https://github.com/dominictarr/charwise
280-
281172
[levelup]: https://github.com/Level/levelup
282173

283174
[leveldown]: https://github.com/Level/leveldown
284175

285176
[level]: https://github.com/Level/level
286177

287178
[encoding-down]: https://github.com/Level/encoding-down
288-
289-
[structured-clone-algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm

UPGRADING.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,41 @@
22

33
This document describes breaking changes and how to upgrade. For a complete list of changes including minor and patch releases, please refer to the [changelog][changelog].
44

5+
## 5.0.0 (unreleased)
6+
7+
Support of keys & values other than strings and Buffers has been dropped. Internally `level-js` now stores keys & values as binary which solves a number of compatibility issues ([Level/memdown#186](https://github.com/Level/memdown/issues/186)). If you pass in a key or value that isn't a string or Buffer, it will be irreversibly stringified.
8+
9+
Existing IndexedDB databases created with `level-js@4` can be read only if they used binary keys and string or binary values. Other types will come out stringified, and string keys will sort incorrectly. Use the included `upgrade()` utility to convert stored data to binary (in so far the environment supports it):
10+
11+
```js
12+
var leveljs = require('level-js')
13+
var db = leveljs('my-db')
14+
15+
db.open(function (err) {
16+
if (err) throw err
17+
18+
db.upgrade(function (err) {
19+
if (err) throw err
20+
})
21+
})
22+
```
23+
24+
Or with (the upcoming release of) `level`:
25+
26+
```js
27+
var level = require('level')
28+
var reachdown = require('reachdown')
29+
var db = level('my-db')
30+
31+
db.open(function (err) {
32+
if (err) throw err
33+
34+
reachdown(db, 'level-js').upgrade(function (err) {
35+
if (err) throw err
36+
})
37+
})
38+
```
39+
540
## 4.0.0
641

742
This is an upgrade to `abstract-leveldown@6` which solves long-standing issues around serialization and type support.

index.js

Lines changed: 61 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ module.exports = Level
77
var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
88
var inherits = require('inherits')
99
var Iterator = require('./iterator')
10-
var mixedToBuffer = require('./util/mixed-to-buffer')
10+
var serialize = require('./util/serialize')
11+
var deserialize = require('./util/deserialize')
1112
var setImmediate = require('./util/immediate')
1213
var support = require('./util/support')
1314

@@ -25,13 +26,17 @@ function Level (location, opts) {
2526
this.location = location
2627
this.prefix = opts.prefix || DEFAULT_PREFIX
2728
this.version = parseInt(opts.version || 1, 10)
29+
30+
// Experimental, do not externally rely on this object yet.
31+
// See Level/community#42.
32+
this.supports = {
33+
bufferKeys: support.bufferKeys(indexedDB)
34+
}
2835
}
2936

3037
inherits(Level, AbstractLevelDOWN)
3138

32-
// Detect binary and array key support (IndexedDB Second Edition)
33-
Level.binaryKeys = support.binaryKeys(indexedDB)
34-
Level.arrayKeys = support.arrayKeys(indexedDB)
39+
Level.prototype.type = 'level-js'
3540

3641
Level.prototype._open = function (options, callback) {
3742
var req = indexedDB.open(this.prefix + this.location, this.version)
@@ -93,11 +98,7 @@ Level.prototype._get = function (key, options, callback) {
9398
return callback(new Error('NotFound'))
9499
}
95100

96-
if (options.asBuffer) {
97-
value = mixedToBuffer(value)
98-
}
99-
100-
callback(null, value)
101+
callback(null, deserialize(value, options.asBuffer))
101102
})
102103
}
103104

@@ -131,27 +132,12 @@ Level.prototype._put = function (key, value, options, callback) {
131132
this.await(req, callback)
132133
}
133134

134-
// Valid key types in IndexedDB Second Edition:
135-
//
136-
// - Number, except NaN. Includes Infinity and -Infinity
137-
// - Date, except invalid (NaN)
138-
// - String
139-
// - ArrayBuffer or a view thereof (typed arrays). In level-js we also support
140-
// Buffer (which is an Uint8Array) (and the primary binary type of Level).
141-
// - Array, except cyclical and empty (e.g. Array(10)). Elements must be valid
142-
// types themselves.
143135
Level.prototype._serializeKey = function (key) {
144-
if (Buffer.isBuffer(key)) {
145-
return Level.binaryKeys ? key : key.toString()
146-
} else if (Array.isArray(key)) {
147-
return Level.arrayKeys ? key.map(this._serializeKey, this) : String(key)
148-
} else {
149-
return key
150-
}
136+
return serialize(key, this.supports.bufferKeys)
151137
}
152138

153139
Level.prototype._serializeValue = function (value) {
154-
return value
140+
return serialize(value, true)
155141
}
156142

157143
Level.prototype._iterator = function (options) {
@@ -200,6 +186,55 @@ Level.prototype._close = function (callback) {
200186
setImmediate(callback)
201187
}
202188

189+
// NOTE: remove in a next major release
190+
Level.prototype.upgrade = function (callback) {
191+
if (this.status !== 'open') {
192+
return setImmediate(function () {
193+
callback(new Error('cannot upgrade() before open()'))
194+
})
195+
}
196+
197+
var it = this.iterator()
198+
var batchOptions = {}
199+
var self = this
200+
201+
it._deserializeKey = it._deserializeValue = identity
202+
next()
203+
204+
function next (err) {
205+
if (err) return finish(err)
206+
it.next(each)
207+
}
208+
209+
function each (err, key, value) {
210+
if (err || key === undefined) {
211+
return finish(err)
212+
}
213+
214+
var newKey = self._serializeKey(deserialize(key, true))
215+
var newValue = self._serializeValue(deserialize(value, true))
216+
217+
// To bypass serialization on the old key, use _batch() instead of batch().
218+
// NOTE: if we disable snapshotting (#86) this could lead to a loop of
219+
// inserting and then iterating those same entries, because the new keys
220+
// possibly sort after the old keys.
221+
self._batch([
222+
{ type: 'del', key: key },
223+
{ type: 'put', key: newKey, value: newValue }
224+
], batchOptions, next)
225+
}
226+
227+
function finish (err) {
228+
it.end(function (err2) {
229+
callback(err || err2)
230+
})
231+
}
232+
233+
function identity (data) {
234+
return data
235+
}
236+
}
237+
203238
Level.destroy = function (location, prefix, callback) {
204239
if (typeof prefix === 'function') {
205240
callback = prefix

iterator.js

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
var inherits = require('inherits')
66
var AbstractIterator = require('abstract-leveldown').AbstractIterator
77
var ltgt = require('ltgt')
8-
var mixedToBuffer = require('./util/mixed-to-buffer')
8+
var deserialize = require('./util/deserialize')
99
var setImmediate = require('./util/immediate')
1010
var noop = function () {}
1111

@@ -23,6 +23,8 @@ function Iterator (db, location, options) {
2323
this._error = null
2424
this._transaction = null
2525

26+
this._keys = options.keys
27+
this._values = options.values
2628
this._keyAsBuffer = options.keyAsBuffer
2729
this._valueAsBuffer = options.valueAsBuffer
2830

@@ -126,8 +128,17 @@ Iterator.prototype._next = function (callback) {
126128
var key = this._cache.shift()
127129
var value = this._cache.shift()
128130

129-
if (this._keyAsBuffer) key = mixedToBuffer(key)
130-
if (this._valueAsBuffer) value = mixedToBuffer(value)
131+
if (this._keys && key !== undefined) {
132+
key = this._deserializeKey(key, this._keyAsBuffer)
133+
} else {
134+
key = undefined
135+
}
136+
137+
if (this._values && value !== undefined) {
138+
value = this._deserializeValue(value, this._valueAsBuffer)
139+
} else {
140+
value = undefined
141+
}
131142

132143
setImmediate(function () {
133144
callback(null, key, value)
@@ -139,6 +150,10 @@ Iterator.prototype._next = function (callback) {
139150
}
140151
}
141152

153+
// Exposed for the v4 to v5 upgrade utility
154+
Iterator.prototype._deserializeKey = deserialize
155+
Iterator.prototype._deserializeValue = deserialize
156+
142157
Iterator.prototype._end = function (callback) {
143158
if (this._aborted || this._completed) {
144159
var err = this._error

0 commit comments

Comments
 (0)