ndb 0.1.2 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +29 -26
- data/lib/ndb/client.rb +39 -17
- data/lib/ndb/id.rb +38 -0
- data/lib/ndb/version.rb +1 -1
- data/lib/ndb.rb +1 -0
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 6b71072a4d09fcc5371634cecb15cc0ecac5c63bbf3eaf4691471105cc870987
|
|
4
|
+
data.tar.gz: cf6b2985e06aa2513542c9fc76f44b6358ea1dce285f23d38fea338b314ca26b
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 4a45049489637f43fecc8bd0336b3c6cfca409f1a9b8ac9bd14307f9c785d80f5ccce5b9facb16d785a7e56311c1d1c810416b05a61cbec762ed3a5c76151fc8
|
|
7
|
+
data.tar.gz: ba0f2f03a0b8987668064e41ff0e7ee5567e7fc0faadd1573592fb0a479a9c7fc0cff34fbe21d0349439f0266792bf00fcd17817067154ced4eb7eb92251881a
|
data/README.md
CHANGED
|
@@ -59,7 +59,6 @@ Ndb::Client.new(
|
|
|
59
59
|
|
|
60
60
|
```ruby
|
|
61
61
|
ndb.ensure_collection("calls",
|
|
62
|
-
id: "call_id",
|
|
63
62
|
indexes: ["status"],
|
|
64
63
|
unique: ["caller"],
|
|
65
64
|
time: "at") # also: expires_field:, ttl:
|
|
@@ -67,6 +66,8 @@ ndb.ensure_collection("calls",
|
|
|
67
66
|
ndb.collections # => [{"name" => "calls", ...}]
|
|
68
67
|
```
|
|
69
68
|
|
|
69
|
+
Every collection has the primary key `_id`. You can send your own (any non-empty string), or leave it out: the daemon makes a UUIDv7 (`Ndb.new_id` makes the same kind of id on the client). For a natural key such as an email, keep `_id` and declare that field in `unique:`.
|
|
70
|
+
|
|
70
71
|
`ensure_collection` is idempotent. A different definition for an existing collection raises `Ndb::CatalogConflict`.
|
|
71
72
|
|
|
72
73
|
## Insert, update, delete
|
|
@@ -75,45 +76,47 @@ Every document has a version. A new document has version 1, and each change adds
|
|
|
75
76
|
|
|
76
77
|
```ruby
|
|
77
78
|
results = ndb.insert("calls", [
|
|
78
|
-
{
|
|
79
|
-
{
|
|
79
|
+
{ _id: "c1", status: "answered", caller: "a", duration: 42 },
|
|
80
|
+
{ _id: "c2", status: "failed", caller: "b", duration: 5 }
|
|
80
81
|
])
|
|
81
|
-
results # => [{"
|
|
82
|
+
results # => [{"_id" => "c1", "v" => 1}, {"_id" => "c2", "v" => 1}]
|
|
83
|
+
|
|
84
|
+
ndb.get("calls", "c1") # => {"_id" => "c1", ..., "_v" => 1}, or nil
|
|
82
85
|
|
|
83
|
-
# Atomic update by filter: the
|
|
84
|
-
ndb.update("calls",
|
|
85
|
-
# => {"matched" => 1, "modified" => 1, "doc" => {"
|
|
86
|
+
# Atomic update by _id (a String) or by filter (a Hash): the target, then the write operators.
|
|
87
|
+
ndb.update("calls", "c1", { "$set" => { status: "done" }, "$unset" => { caller: true } })
|
|
88
|
+
# => {"matched" => 1, "modified" => 1, "doc" => {"_id" => "c1", ..., "_v" => 2}}
|
|
86
89
|
|
|
87
|
-
ndb.update("calls", {
|
|
88
|
-
ndb.update("stock", {
|
|
90
|
+
ndb.update("calls", { _id: "c1", _v: 2 }, { "$set" => { duration: 50 } }) # only if the version is still 2
|
|
91
|
+
ndb.update("stock", { _id: "a", qty: { "$gte" => 1 } }, { "$inc" => { qty: -1 } }) # guarded decrement
|
|
89
92
|
|
|
90
93
|
ndb.update("calls", { status: "failed" }, { "$set" => { status: "retry" } }, many: true) # => {"matched" => 3, "modified" => 3}
|
|
91
94
|
ndb.update("counters", { name: "hits" }, { "$inc" => { n: 1 } }, upsert: true)
|
|
92
95
|
|
|
93
|
-
ndb.delete("calls",
|
|
96
|
+
ndb.delete("calls", "c2") # by _id => {"deleted" => 1}
|
|
94
97
|
ndb.delete("calls", { status: "failed" }, many: true)
|
|
95
98
|
```
|
|
96
99
|
|
|
97
|
-
- Operators: `$set`, `$unset`, `$inc`, `$push` (with `{ "$each" => [...] }`), `$pull`, `$min`, `$max`. Field names can be dot paths. A key of the operators without `$` raises `ArgumentError` before anything is sent.
|
|
100
|
+
- Operators: `$set`, `$setOnInsert` (like `$set`, but only when an upsert creates the document), `$unset`, `$inc`, `$push` (with `{ "$each" => [...] }`), `$pull`, `$min`, `$max`. Field names can be dot paths. A key of the operators without `$` raises `ArgumentError` before anything is sent.
|
|
98
101
|
- Nothing matched is not an error: `matched` is 0. A stale `_v` is a filter that matches nothing, so read again and retry. `modified` is 0 when the operators leave the document as it is.
|
|
99
|
-
- `many: true` needs
|
|
102
|
+
- `many: true` needs `_id` or an indexed field in the filter (`Ndb::UnindexedMany`), and does not apply to an `_id` String. `upsert: true` creates the document from the equality fields of the filter. The answer has `doc` only for one document.
|
|
100
103
|
- The contract errors are `Ndb::UnknownOperator`, `NoUpdate`, `ConflictingUpdate`, `InvalidField`, `UnindexedMany` and `EmptyFilter`, all under `Ndb::InvalidUpdate`.
|
|
101
|
-
- A duplicate
|
|
104
|
+
- A duplicate `_id` raises `Ndb::UniqueViolation` (code `duplicate_id`). A broken unique field raises it too (code `unique_violation`).
|
|
102
105
|
|
|
103
106
|
## Expiry (TTL like Redis)
|
|
104
107
|
|
|
105
108
|
The collection needs `expires_field`.
|
|
106
109
|
|
|
107
110
|
```ruby
|
|
108
|
-
ndb.ensure_collection("sessions", {
|
|
111
|
+
ndb.ensure_collection("sessions", { expires_field: "exp" })
|
|
109
112
|
|
|
110
|
-
ndb.insert("sessions", [{
|
|
111
|
-
ndb.update("sessions",
|
|
113
|
+
ndb.insert("sessions", [{ _id: "s1" }], expire_in: 3600) # seconds, or "1h" / "30m" / "1d"
|
|
114
|
+
ndb.update("sessions", "s1", { "$set" => { user: "u" } }, expire_in: "30m")
|
|
112
115
|
|
|
113
|
-
ndb.expire("sessions", "s1", in: 1800) # => {"
|
|
116
|
+
ndb.expire("sessions", "s1", in: 1800) # => {"_id", "v", "expires_at"}
|
|
114
117
|
ndb.expire("sessions", "s1", at: Time.now + 7200)
|
|
115
118
|
ndb.ttl("sessions", "s1") # => 7199, -1 (never expires), or nil (missing or expired)
|
|
116
|
-
ndb.persist("sessions", "s1") # => {"
|
|
119
|
+
ndb.persist("sessions", "s1") # => {"_id", "v"}
|
|
117
120
|
```
|
|
118
121
|
|
|
119
122
|
- `expire_in` wins over a value of `expires_field` in the same call. `ttl` rounds up to whole seconds.
|
|
@@ -128,11 +131,11 @@ ndb.persist("sessions", "s1") # => {"id", "v"}
|
|
|
128
131
|
page = ndb.find("calls",
|
|
129
132
|
where: { status: "answered", duration: { "$gte" => 30, "$lte" => 60 } },
|
|
130
133
|
sort: { at: -1 },
|
|
131
|
-
fields: %w[
|
|
134
|
+
fields: %w[_id status],
|
|
132
135
|
limit: 50,
|
|
133
136
|
skip: 0)
|
|
134
137
|
|
|
135
|
-
page.rows # => [{"
|
|
138
|
+
page.rows # => [{"_id" => "c1", "status" => "answered"}, ...]
|
|
136
139
|
page.plan # "id", "index:status", "scan" or "snapshot"
|
|
137
140
|
page.examined # rows the daemon looked at
|
|
138
141
|
```
|
|
@@ -148,7 +151,7 @@ ndb.find("calls", where: { "$or" => [{ status: "failed" }, { duration: { "$gt" =
|
|
|
148
151
|
ndb.find("calls", where: { "agent.id" => 7 }) # dot path
|
|
149
152
|
```
|
|
150
153
|
|
|
151
|
-
- `sort: { at: -1,
|
|
154
|
+
- `sort: { at: -1, _id: 1 }`: `1` ascending, `-1` descending. The key order is the sort order. The id is always the last key.
|
|
152
155
|
- `versions: true` adds the field `_v` (the document version) to each row.
|
|
153
156
|
|
|
154
157
|
### Regular expressions
|
|
@@ -187,9 +190,9 @@ page.total # how many documents match, whatever the limit
|
|
|
187
190
|
cursor = nil
|
|
188
191
|
|
|
189
192
|
loop do
|
|
190
|
-
page = ndb.find("calls", where: { status: "answered" }, sort: {
|
|
193
|
+
page = ndb.find("calls", where: { status: "answered" }, sort: { _id: 1 }, limit: 100, after: cursor)
|
|
191
194
|
|
|
192
|
-
page.rows.each { |row| puts row["
|
|
195
|
+
page.rows.each { |row| puts row["_id"] }
|
|
193
196
|
|
|
194
197
|
cursor = page.next_cursor
|
|
195
198
|
|
|
@@ -230,7 +233,7 @@ A watch streams the changes of a collection to a named consumer: first the event
|
|
|
230
233
|
```ruby
|
|
231
234
|
begin
|
|
232
235
|
ndb.watch("calls", "relay", where: { status: "failed" }) do |event|
|
|
233
|
-
# event has "pos", "op" ("put" or "del"), "
|
|
236
|
+
# event has "pos", "op" ("put" or "del"), "_id", "v" and "doc"
|
|
234
237
|
handle(event)
|
|
235
238
|
|
|
236
239
|
ndb.ack("calls", "relay", event["pos"])
|
|
@@ -257,7 +260,7 @@ Large values live in the blob store. A document keeps only a reference.
|
|
|
257
260
|
stored = ndb.put_blob(File.open("call.wav"), "audio/wav") # an IO, streamed in chunks
|
|
258
261
|
stored # => {"$blob" => "sha256:...", "size" => 123456, "type" => "audio/wav"}
|
|
259
262
|
|
|
260
|
-
ndb.insert("calls", [{
|
|
263
|
+
ndb.insert("calls", [{ _id: "c9", recording: stored }])
|
|
261
264
|
|
|
262
265
|
ndb.get_blob(stored["$blob"]) # all the bytes
|
|
263
266
|
ndb.get_blob(stored["$blob"], from: 0, to: 1023) # bytes 0..1023 (inclusive)
|
|
@@ -291,7 +294,7 @@ Any other code is a plain `Ndb::Error`. A response that is not a daemon error ha
|
|
|
291
294
|
|
|
292
295
|
```ruby
|
|
293
296
|
begin
|
|
294
|
-
ndb.insert("calls", [{
|
|
297
|
+
ndb.insert("calls", [{ _id: "c1" }])
|
|
295
298
|
rescue Ndb::UniqueViolation => e
|
|
296
299
|
e.code # "duplicate_id"
|
|
297
300
|
e.status # 409
|
data/lib/ndb/client.rb
CHANGED
|
@@ -41,6 +41,14 @@ module Ndb
|
|
|
41
41
|
page(post(coll, "aggregate", Conditions.regexps(body)))
|
|
42
42
|
end
|
|
43
43
|
|
|
44
|
+
# The document with this _id (and its "_v"), or nil.
|
|
45
|
+
def get(coll, id)
|
|
46
|
+
json(request("GET", id_path(coll, id), nil))
|
|
47
|
+
rescue NotFound
|
|
48
|
+
nil
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Each document gets a generated UUIDv7 _id unless it carries one.
|
|
44
52
|
# expire_in (seconds, or "30m" / "1h" / "1d") sets the expires_field of
|
|
45
53
|
# every document to now + expire_in, in the same transaction.
|
|
46
54
|
def insert(coll, docs, expire_in: nil)
|
|
@@ -50,39 +58,49 @@ module Ndb
|
|
|
50
58
|
json(post(coll, "insert", body)).fetch("results")
|
|
51
59
|
end
|
|
52
60
|
|
|
53
|
-
# Atomic update
|
|
54
|
-
#
|
|
61
|
+
# Atomic update. A String is the _id of one document (POST /{_id}/update);
|
|
62
|
+
# a Hash is a filter (POST /update). The filter and the write operators go
|
|
63
|
+
# in one body; the daemon matches and writes in one step on the newest state, so
|
|
55
64
|
# concurrent updates never interleave.
|
|
56
65
|
#
|
|
57
66
|
# client.update("stock", { sku: "a", qty: { "$gte" => 1 } }, { "$inc" => { qty: -1 } })
|
|
58
67
|
# # => {"matched" => 1, "modified" => 1, "doc" => {...with "_v"}}
|
|
59
68
|
#
|
|
60
|
-
# Operators: $set, $unset, $inc, $push, $pull, $min, $max (dot paths work).
|
|
69
|
+
# Operators: $set, $setOnInsert, $unset, $inc, $push, $pull, $min, $max (dot paths work).
|
|
61
70
|
# Nothing matched is not an error: {"matched" => 0, "modified" => 0}. A
|
|
62
|
-
# version guard is a filter: {
|
|
63
|
-
# match (no "doc" in the answer) and needs
|
|
64
|
-
#
|
|
71
|
+
# version guard is a filter: { _id: "x", _v: 7 }. many: true updates every
|
|
72
|
+
# match (no "doc" in the answer) and needs _id or an indexed field in the
|
|
73
|
+
# filter; it does not apply to an _id String. upsert: true creates the document from the equality fields
|
|
65
74
|
# of the filter when nothing matches. expire_in (seconds, or "30m") sets
|
|
66
75
|
# the expires_field.
|
|
67
|
-
def update(coll,
|
|
76
|
+
def update(coll, id_or_filter, ops, many: false, upsert: false, expire_in: nil)
|
|
77
|
+
if id_or_filter.is_a?(String)
|
|
78
|
+
query = write_query(upsert: upsert, expire_in: expire_in)
|
|
79
|
+
|
|
80
|
+
return json(request("POST", "#{id_path(coll, id_or_filter)}/update#{query}", merge_update({}, ops)))
|
|
81
|
+
end
|
|
82
|
+
|
|
68
83
|
query = write_query(many: many, upsert: upsert, expire_in: expire_in)
|
|
69
84
|
|
|
70
|
-
json(post(coll, "update#{query}", merge_update(
|
|
85
|
+
json(post(coll, "update#{query}", merge_update(id_or_filter, ops)))
|
|
71
86
|
end
|
|
72
87
|
|
|
73
|
-
# Deletes the documents that the filter matches (one,
|
|
74
|
-
# many: true, which needs
|
|
75
|
-
|
|
76
|
-
|
|
88
|
+
# Deletes by _id (a String), or the documents that the filter matches (one,
|
|
89
|
+
# or every match with many: true, which needs _id or an indexed field).
|
|
90
|
+
# {"deleted" => n}
|
|
91
|
+
def delete(coll, id_or_filter, many: false)
|
|
92
|
+
return json(request("DELETE", id_path(coll, id_or_filter), nil)) if id_or_filter.is_a?(String)
|
|
93
|
+
|
|
94
|
+
json(post(coll, "delete#{write_query(many: many)}", id_or_filter))
|
|
77
95
|
end
|
|
78
96
|
|
|
79
97
|
# Makes a document expire, like EXPIRE in Redis: in: seconds or "30m", or
|
|
80
|
-
# at: a Time or an RFC 3339 String. Returns {"
|
|
98
|
+
# at: a Time or an RFC 3339 String. Returns {"_id", "v", "expires_at"}.
|
|
81
99
|
# Raises NotFound for a missing or expired document, TtlNotEnabled when
|
|
82
100
|
# the collection has no expires_field, TtlDerived when the expiry comes
|
|
83
101
|
# from ttl + time.
|
|
84
102
|
def expire(coll, id, **time)
|
|
85
|
-
body = {
|
|
103
|
+
body = { _id: id }
|
|
86
104
|
body[:in] = time[:in] if time[:in]
|
|
87
105
|
body[:at] = time[:at].respond_to?(:utc) ? time[:at].utc.iso8601(9) : time[:at] if time[:at]
|
|
88
106
|
|
|
@@ -91,13 +109,13 @@ module Ndb
|
|
|
91
109
|
|
|
92
110
|
# Removes the expiry of a document, like PERSIST in Redis.
|
|
93
111
|
def persist(coll, id)
|
|
94
|
-
json(post(coll, "persist",
|
|
112
|
+
json(post(coll, "persist", _id: id))
|
|
95
113
|
end
|
|
96
114
|
|
|
97
115
|
# The seconds left of a document (an Integer, rounded up), -1 when it
|
|
98
116
|
# never expires, nil when it is missing or expired.
|
|
99
117
|
def ttl(coll, id)
|
|
100
|
-
json(request("GET", "#{
|
|
118
|
+
json(request("GET", "#{id_path(coll, id)}/ttl", nil)).fetch("ttl")
|
|
101
119
|
rescue NotFound
|
|
102
120
|
nil
|
|
103
121
|
end
|
|
@@ -127,7 +145,7 @@ module Ndb
|
|
|
127
145
|
json(post(coll, "ack", consumer: consumer, pos: pos))
|
|
128
146
|
end
|
|
129
147
|
|
|
130
|
-
def ensure_collection(coll, definition)
|
|
148
|
+
def ensure_collection(coll, definition = {})
|
|
131
149
|
json(request("PUT", path(coll), definition))
|
|
132
150
|
end
|
|
133
151
|
|
|
@@ -183,6 +201,10 @@ module Ndb
|
|
|
183
201
|
"/v1/c/#{URI.encode_www_form_component(coll).gsub('+', '%20')}"
|
|
184
202
|
end
|
|
185
203
|
|
|
204
|
+
def id_path(coll, id)
|
|
205
|
+
"#{path(coll)}/#{URI.encode_www_form_component(id).gsub('+', '%20')}"
|
|
206
|
+
end
|
|
207
|
+
|
|
186
208
|
def request(method, target, body, headers: {})
|
|
187
209
|
payload = encode(body)
|
|
188
210
|
headers = authorize(headers)
|
data/lib/ndb/id.rb
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "securerandom"
|
|
4
|
+
|
|
5
|
+
module Ndb
|
|
6
|
+
ID_LOCK = Mutex.new
|
|
7
|
+
ID_STATE = { ms: 0, counter: 0 }
|
|
8
|
+
|
|
9
|
+
# A new UUIDv7 (RFC 9562), lowercase and hyphenated: the same kind of id that
|
|
10
|
+
# the daemon makes. Ids from one process sort in the order of their creation.
|
|
11
|
+
def self.new_id
|
|
12
|
+
ms, counter = ID_LOCK.synchronize { next_stamp((Time.now.to_f * 1000).to_i) }
|
|
13
|
+
rest = SecureRandom.random_bytes(8).bytes
|
|
14
|
+
|
|
15
|
+
rest[0] = 0x80 | (rest[0] & 0x3f)
|
|
16
|
+
|
|
17
|
+
head = [ms >> 16, ms & 0xffff, 0x7000 | counter].pack("Nnn").unpack1("H*")
|
|
18
|
+
tail = rest.pack("C*").unpack1("H*")
|
|
19
|
+
|
|
20
|
+
"#{head[0, 8]}-#{head[8, 4]}-#{head[12, 4]}-#{tail[0, 4]}-#{tail[4, 12]}"
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def self.next_stamp(now)
|
|
24
|
+
if now > ID_STATE[:ms]
|
|
25
|
+
ID_STATE[:ms] = now
|
|
26
|
+
ID_STATE[:counter] = SecureRandom.random_number(0x800)
|
|
27
|
+
elsif ID_STATE[:counter] >= 0x0fff
|
|
28
|
+
ID_STATE[:ms] += 1
|
|
29
|
+
ID_STATE[:counter] = SecureRandom.random_number(0x800)
|
|
30
|
+
else
|
|
31
|
+
ID_STATE[:counter] += 1
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
[ID_STATE[:ms], ID_STATE[:counter]]
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
private_class_method :next_stamp
|
|
38
|
+
end
|
data/lib/ndb/version.rb
CHANGED
data/lib/ndb.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: ndb
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.1
|
|
4
|
+
version: 0.2.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- thadeu
|
|
@@ -23,6 +23,7 @@ files:
|
|
|
23
23
|
- lib/ndb/conditions.rb
|
|
24
24
|
- lib/ndb/connection.rb
|
|
25
25
|
- lib/ndb/errors.rb
|
|
26
|
+
- lib/ndb/id.rb
|
|
26
27
|
- lib/ndb/version.rb
|
|
27
28
|
homepage: https://github.com/thadeu/ndb
|
|
28
29
|
licenses:
|