ndb 0.1.1 → 0.2.0
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 +37 -34
- data/lib/ndb/client.rb +70 -16
- data/lib/ndb/errors.rb +16 -3
- 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: e9280ccf6f45b1db75f091211f486ab686813f6ce2e3c12ad3271617c675cf39
|
|
4
|
+
data.tar.gz: 53018c885e19cc7e010e9d14b2ceba2f036f27db767b13e9f3fee6315d507311
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: db2f8d1f62608a8d0d7a1e9293b4310ede9b1ad1946dcd4434f63a25e603d8cf3e4f6a28bad63e41f5f0a6710d58fe58662a2ec3fe57e980d391690802c88b45
|
|
7
|
+
data.tar.gz: 7f5b1bea15d1503d344f7829e129186dd754acb9b6a9a82d465afebaeaefa609693461ee44e57a3e8168dd3d61ce1b0ff9ce0e10414d2c34b13562811ac07fb2
|
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}]
|
|
82
83
|
|
|
83
|
-
ndb.
|
|
84
|
-
ndb.update("calls", "c1", set: { duration: 50 }, if_version: 2) # only if the version is still 2
|
|
84
|
+
ndb.get("calls", "c1") # => {"_id" => "c1", ..., "_v" => 1}, or nil
|
|
85
85
|
|
|
86
|
-
|
|
87
|
-
ndb.
|
|
88
|
-
|
|
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}}
|
|
89
89
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
- A missing document raises `Ndb::NotFound`.
|
|
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
|
|
93
92
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
retry
|
|
100
|
-
end
|
|
93
|
+
ndb.update("calls", { status: "failed" }, { "$set" => { status: "retry" } }, many: true) # => {"matched" => 3, "modified" => 3}
|
|
94
|
+
ndb.update("counters", { name: "hits" }, { "$inc" => { n: 1 } }, upsert: true)
|
|
95
|
+
|
|
96
|
+
ndb.delete("calls", "c2") # by _id => {"deleted" => 1}
|
|
97
|
+
ndb.delete("calls", { status: "failed" }, many: true)
|
|
101
98
|
```
|
|
102
99
|
|
|
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.
|
|
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.
|
|
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.
|
|
103
|
+
- The contract errors are `Ndb::UnknownOperator`, `NoUpdate`, `ConflictingUpdate`, `InvalidField`, `UnindexedMany` and `EmptyFilter`, all under `Ndb::InvalidUpdate`.
|
|
104
|
+
- A duplicate `_id` raises `Ndb::UniqueViolation` (code `duplicate_id`). A broken unique field raises it too (code `unique_violation`).
|
|
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", "s1", set
|
|
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) # => {"
|
|
114
|
-
ndb.expire("sessions", "s1", at: Time.now + 7200
|
|
116
|
+
ndb.expire("sessions", "s1", in: 1800) # => {"_id", "v", "expires_at"}
|
|
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)
|
|
@@ -275,7 +278,7 @@ All errors inherit from `Ndb::Error`, which has `code` (the daemon code) and `st
|
|
|
275
278
|
| `NotReady` | `not_ready` |
|
|
276
279
|
| `NotFound` | `not_found` |
|
|
277
280
|
| `UnknownCollection` | `unknown_collection` |
|
|
278
|
-
| `
|
|
281
|
+
| `InvalidUpdate` and its subclasses | `unknown_operator`, `no_update`, `conflicting_update`, `invalid_field`, `unindexed_many`, `empty_filter` |
|
|
279
282
|
| `UniqueViolation` | `unique_violation`, `duplicate_id` |
|
|
280
283
|
| `CatalogConflict` | `catalog_conflict` |
|
|
281
284
|
| `CatalogInvalid` | `catalog_invalid` |
|
|
@@ -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,44 +58,64 @@ module Ndb
|
|
|
50
58
|
json(post(coll, "insert", body)).fetch("results")
|
|
51
59
|
end
|
|
52
60
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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
|
|
64
|
+
# concurrent updates never interleave.
|
|
65
|
+
#
|
|
66
|
+
# client.update("stock", { sku: "a", qty: { "$gte" => 1 } }, { "$inc" => { qty: -1 } })
|
|
67
|
+
# # => {"matched" => 1, "modified" => 1, "doc" => {...with "_v"}}
|
|
68
|
+
#
|
|
69
|
+
# Operators: $set, $setOnInsert, $unset, $inc, $push, $pull, $min, $max (dot paths work).
|
|
70
|
+
# Nothing matched is not an error: {"matched" => 0, "modified" => 0}. A
|
|
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
|
|
74
|
+
# of the filter when nothing matches. expire_in (seconds, or "30m") sets
|
|
75
|
+
# the expires_field.
|
|
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
|
+
|
|
83
|
+
query = write_query(many: many, upsert: upsert, expire_in: expire_in)
|
|
57
84
|
|
|
58
|
-
json(post(coll, "update",
|
|
85
|
+
json(post(coll, "update#{query}", merge_update(id_or_filter, ops)))
|
|
59
86
|
end
|
|
60
87
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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)
|
|
64
93
|
|
|
65
|
-
json(post(coll, "delete",
|
|
94
|
+
json(post(coll, "delete#{write_query(many: many)}", id_or_filter))
|
|
66
95
|
end
|
|
67
96
|
|
|
68
97
|
# Makes a document expire, like EXPIRE in Redis: in: seconds or "30m", or
|
|
69
|
-
# at: a Time or an RFC 3339 String. Returns {"
|
|
98
|
+
# at: a Time or an RFC 3339 String. Returns {"_id", "v", "expires_at"}.
|
|
70
99
|
# Raises NotFound for a missing or expired document, TtlNotEnabled when
|
|
71
100
|
# the collection has no expires_field, TtlDerived when the expiry comes
|
|
72
101
|
# from ttl + time.
|
|
73
|
-
def expire(coll, id,
|
|
74
|
-
body = {
|
|
102
|
+
def expire(coll, id, **time)
|
|
103
|
+
body = { _id: id }
|
|
75
104
|
body[:in] = time[:in] if time[:in]
|
|
76
105
|
body[:at] = time[:at].respond_to?(:utc) ? time[:at].utc.iso8601(9) : time[:at] if time[:at]
|
|
77
|
-
body[:if_version] = if_version if if_version
|
|
78
106
|
|
|
79
107
|
json(post(coll, "expire", body))
|
|
80
108
|
end
|
|
81
109
|
|
|
82
110
|
# Removes the expiry of a document, like PERSIST in Redis.
|
|
83
111
|
def persist(coll, id)
|
|
84
|
-
json(post(coll, "persist",
|
|
112
|
+
json(post(coll, "persist", _id: id))
|
|
85
113
|
end
|
|
86
114
|
|
|
87
115
|
# The seconds left of a document (an Integer, rounded up), -1 when it
|
|
88
116
|
# never expires, nil when it is missing or expired.
|
|
89
117
|
def ttl(coll, id)
|
|
90
|
-
json(request("GET", "#{
|
|
118
|
+
json(request("GET", "#{id_path(coll, id)}/ttl", nil)).fetch("ttl")
|
|
91
119
|
rescue NotFound
|
|
92
120
|
nil
|
|
93
121
|
end
|
|
@@ -117,7 +145,7 @@ module Ndb
|
|
|
117
145
|
json(post(coll, "ack", consumer: consumer, pos: pos))
|
|
118
146
|
end
|
|
119
147
|
|
|
120
|
-
def ensure_collection(coll, definition)
|
|
148
|
+
def ensure_collection(coll, definition = {})
|
|
121
149
|
json(request("PUT", path(coll), definition))
|
|
122
150
|
end
|
|
123
151
|
|
|
@@ -143,6 +171,28 @@ module Ndb
|
|
|
143
171
|
value.to_s.strip.empty? ? nil : value
|
|
144
172
|
end
|
|
145
173
|
|
|
174
|
+
def write_query(many: false, upsert: false, expire_in: nil)
|
|
175
|
+
params = {}
|
|
176
|
+
|
|
177
|
+
params["many"] = "true" if many
|
|
178
|
+
params["upsert"] = "true" if upsert
|
|
179
|
+
params["expire_in"] = expire_in.to_s if expire_in
|
|
180
|
+
|
|
181
|
+
params.empty? ? "" : "?#{URI.encode_www_form(params)}"
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# The filter and the operators in one body. An operator key without "$"
|
|
185
|
+
# would be read as a filter key by the daemon, so it is refused here.
|
|
186
|
+
def merge_update(filter, ops)
|
|
187
|
+
ops.each_key do |key|
|
|
188
|
+
next if key.to_s.start_with?("$")
|
|
189
|
+
|
|
190
|
+
raise ArgumentError, "update operator #{key.to_s.inspect} must start with $ (for example \"$set\")"
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
filter.to_h.transform_keys(&:to_s).merge(ops.to_h.transform_keys(&:to_s))
|
|
194
|
+
end
|
|
195
|
+
|
|
146
196
|
def post(coll, verb, body)
|
|
147
197
|
request("POST", "#{path(coll)}/#{verb}", body)
|
|
148
198
|
end
|
|
@@ -151,6 +201,10 @@ module Ndb
|
|
|
151
201
|
"/v1/c/#{URI.encode_www_form_component(coll).gsub('+', '%20')}"
|
|
152
202
|
end
|
|
153
203
|
|
|
204
|
+
def id_path(coll, id)
|
|
205
|
+
"#{path(coll)}/#{URI.encode_www_form_component(id).gsub('+', '%20')}"
|
|
206
|
+
end
|
|
207
|
+
|
|
154
208
|
def request(method, target, body, headers: {})
|
|
155
209
|
payload = encode(body)
|
|
156
210
|
headers = authorize(headers)
|
data/lib/ndb/errors.rb
CHANGED
|
@@ -25,7 +25,6 @@ module Ndb
|
|
|
25
25
|
class Unauthorized < Error; end
|
|
26
26
|
class NotFound < Error; end
|
|
27
27
|
class UnknownCollection < Error; end
|
|
28
|
-
class VersionConflict < Error; end
|
|
29
28
|
class UniqueViolation < Error; end
|
|
30
29
|
class CatalogConflict < Error; end
|
|
31
30
|
class CatalogInvalid < Error; end
|
|
@@ -33,6 +32,15 @@ module Ndb
|
|
|
33
32
|
class InvalidQuery < Error; end
|
|
34
33
|
class InvalidCursor < Error; end
|
|
35
34
|
|
|
35
|
+
# The update or delete body breaks the contract (see Client#update).
|
|
36
|
+
class InvalidUpdate < Error; end
|
|
37
|
+
class UnknownOperator < InvalidUpdate; end
|
|
38
|
+
class NoUpdate < InvalidUpdate; end
|
|
39
|
+
class ConflictingUpdate < InvalidUpdate; end
|
|
40
|
+
class InvalidField < InvalidUpdate; end
|
|
41
|
+
class UnindexedMany < InvalidUpdate; end
|
|
42
|
+
class EmptyFilter < InvalidUpdate; end
|
|
43
|
+
|
|
36
44
|
# The collection has no expires_field, or its expiry comes from ttl + time.
|
|
37
45
|
class TtlNotEnabled < Error; end
|
|
38
46
|
class TtlDerived < Error; end
|
|
@@ -50,7 +58,6 @@ module Ndb
|
|
|
50
58
|
"not_ready" => NotReady,
|
|
51
59
|
"not_found" => NotFound,
|
|
52
60
|
"unknown_collection" => UnknownCollection,
|
|
53
|
-
"version_conflict" => VersionConflict,
|
|
54
61
|
"unique_violation" => UniqueViolation,
|
|
55
62
|
"duplicate_id" => UniqueViolation,
|
|
56
63
|
"catalog_conflict" => CatalogConflict,
|
|
@@ -64,7 +71,13 @@ module Ndb
|
|
|
64
71
|
"watch_lagged" => WatchLagged,
|
|
65
72
|
"history_truncated" => HistoryTruncated,
|
|
66
73
|
"ttl_not_enabled" => TtlNotEnabled,
|
|
67
|
-
"ttl_derived" => TtlDerived
|
|
74
|
+
"ttl_derived" => TtlDerived,
|
|
75
|
+
"unknown_operator" => UnknownOperator,
|
|
76
|
+
"no_update" => NoUpdate,
|
|
77
|
+
"conflicting_update" => ConflictingUpdate,
|
|
78
|
+
"invalid_field" => InvalidField,
|
|
79
|
+
"unindexed_many" => UnindexedMany,
|
|
80
|
+
"empty_filter" => EmptyFilter
|
|
68
81
|
}.freeze
|
|
69
82
|
|
|
70
83
|
def self.error_for(code, message, status)
|
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.
|
|
4
|
+
version: 0.2.0
|
|
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:
|