ished 0.1.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.
Files changed (5) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +202 -0
  3. data/lib/ished/grid.rb +144 -0
  4. data/lib/ished.rb +540 -0
  5. metadata +43 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ff919149cef62f290766619ba426082209a755ad8f1aeaa1183d3f365abdadb9
4
+ data.tar.gz: ee8441ea5695a4854c849e99195b1d065d6795f1b1c00e7d357197d2781edfaf
5
+ SHA512:
6
+ metadata.gz: 824470231465a80d034a4121939cc9965ea97b85e8331bc0c0bf9a9370b72f8a4517989609d04306a76815c2788af0389883288c5cd0a9d2c46fa832ff2cf4a8
7
+ data.tar.gz: ff522626dbcc0dac59ef0605416979e13eaf3215fec79b3ce4c6e6f95ca6dd10bbd11a26c275424f955abf8aee2755f6b67c9a8a3f8fbfbf08c986ad48f9fae7
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/lib/ished/grid.rb ADDED
@@ -0,0 +1,144 @@
1
+ # IshedDB's files from Ruby, as the mongo gem's Mongo::Grid::FSBucket (database.fs): upload_from_stream,
2
+ # open_upload_stream, download_to_stream(_by_name), open_download_stream(_by_name), find, delete, rename, drop — the
3
+ # same names and arguments. The bytes go to IshedDB in pieces (a resumable upload, as Cloud Storage's) and come back
4
+ # as a stream; a file's document is one of the collection <bucket>.files. IshedDB's own: signed_url for a browser.
5
+
6
+ require "stringio"
7
+
8
+ module Ished
9
+ class FSBucket
10
+ PIECE = 8 * 1024 * 1024 # one request (a multiple of IshedDB's 256 KB segments)
11
+
12
+ attr_reader :bucket_name
13
+
14
+ # A file being written, as the gem's upload stream: write, then close (or the block's end); its file_id.
15
+ class UploadStream
16
+ attr_reader :file_id
17
+
18
+ def initialize(bucket, filename, options)
19
+ @bucket = bucket
20
+ @filename = filename
21
+ @options = options
22
+ @buffer = StringIO.new("".b)
23
+ @closed = false
24
+ end
25
+
26
+ def write(data)
27
+ raise Error.new("invalid-argument", "this upload stream is closed") if @closed
28
+
29
+ @buffer.write(data.b)
30
+ self
31
+ end
32
+
33
+ def close
34
+ return @file_id if @closed
35
+
36
+ @buffer.rewind
37
+ @file_id = @bucket.send(:upload, @filename, @buffer, @options)
38
+ @closed = true
39
+ @file_id
40
+ end
41
+
42
+ def closed? = @closed
43
+ end
44
+
45
+ def initialize(database, call, raw, path, bucket_name: "fs")
46
+ raise Error.new("invalid-argument", 'bucket_name: 1 to 94 letters, digits, "_", "-" or "."') unless bucket_name.to_s.match?(/\A[A-Za-z0-9_-][A-Za-z0-9_.-]{0,93}\z/)
47
+
48
+ @database = database
49
+ @call = call
50
+ @raw = raw
51
+ @bucket_name = bucket_name.to_s
52
+ @path = "#{path}/buckets/#{Ished.segment(@bucket_name)}"
53
+ end
54
+
55
+ # ---- writing ----------------------------------------------------------------------------------------------------
56
+
57
+ # As the gem's upload_from_stream(filename, io, metadata:, file_id:): the file's id.
58
+ def upload_from_stream(filename, io, options = {}) = upload(filename, io.is_a?(String) ? StringIO.new(io.b) : io, options)
59
+
60
+ # As the gem's open_upload_stream(filename) { |stream| stream.write(...) }: the stream (closed after the block).
61
+ def open_upload_stream(filename, options = {})
62
+ stream = UploadStream.new(self, filename, options)
63
+ return stream unless block_given?
64
+
65
+ yield stream
66
+ stream.close
67
+ stream
68
+ end
69
+
70
+ # ---- reading ----------------------------------------------------------------------------------------------------
71
+
72
+ # As the gem's download_to_stream(id, io): the bytes written to io as they come.
73
+ def download_to_stream(file_id, io)
74
+ document(file_id)
75
+ @raw.call(:get, "#{@path}/files/#{Ished.segment(file_id.to_s)}:download", nil, {}, auth: true) { |chunk| io.write(chunk) }
76
+ io
77
+ end
78
+
79
+ # As the gem's open_download_stream(id) { |stream| stream.read }: a stream of the file's bytes.
80
+ def open_download_stream(file_id)
81
+ io = download_to_stream(file_id, StringIO.new("".b))
82
+ io.rewind
83
+ block_given? ? yield(io) : io
84
+ end
85
+
86
+ # As the gem: revision 0 the first one sent, -1 the last one (default).
87
+ def download_to_stream_by_name(filename, io, revision: -1) = download_to_stream(by_name(filename, revision), io)
88
+
89
+ def open_download_stream_by_name(filename, revision: -1, &block) = open_download_stream(by_name(filename, revision), &block)
90
+
91
+ # ---- the files' documents -----------------------------------------------------------------------------------------
92
+
93
+ # As the gem's find(selector): a view of the files' documents (the collection <bucket>.files).
94
+ def find(selector = {}, options = {}) = @database.collection("#{@bucket_name}.files").find(selector, options)
95
+
96
+ def find_one(selector = {}) = find(selector).limit(1).first
97
+
98
+ # As the gem's delete(id): the file's document and its bytes.
99
+ def delete(file_id) = @call.call(:post, "#{@path}/files/#{Ished.segment(file_id.to_s)}:delete", {}) && nil
100
+
101
+ def rename(file_id, new_filename) = @call.call(:post, "#{@path}/files/#{Ished.segment(file_id.to_s)}:rename", { "filename" => new_filename }) && nil
102
+
103
+ # As the gem's drop: every file of the bucket, and its <bucket>.files collection.
104
+ def drop = @call.call(:post, "#{@path}:drop", {}) && nil
105
+
106
+ # IshedDB's own: a signed address for a browser (no key in it), as Cloud Storage's signed URLs: url, expiresAt.
107
+ def signed_url(file_id, expires_in: 3600, disposition: "attachment") = @call.call(:post, "#{@path}/files/#{Ished.segment(file_id.to_s)}:signUrl", { "expiresIn" => expires_in, "disposition" => disposition })
108
+
109
+ private
110
+
111
+ def document(file_id)
112
+ find_one({ _id: file_id }) || raise(Error.new("not-found", "no file #{file_id} in the bucket #{@bucket_name}", 404))
113
+ end
114
+
115
+ def by_name(filename, revision)
116
+ view = find({ filename: filename }).sort(uploadDate: revision >= 0 ? 1 : -1).skip(revision >= 0 ? revision : -revision - 1).limit(1)
117
+ (view.first || raise(Error.new("not-found", "no revision #{revision} of the file #{filename} in the bucket #{@bucket_name}", 404)))["_id"]
118
+ end
119
+
120
+ # Sends io in pieces of 8 MB; the length told with the last one.
121
+ def upload(filename, io, options)
122
+ body = { "filename" => filename, "length" => nil }
123
+ body["id"] = options[:file_id].to_s if options[:file_id]
124
+ body["metadata"] = Ished.to_wire(options[:metadata]) if options[:metadata]
125
+ body["contentType"] = options[:content_type] if options[:content_type]
126
+ piece = io.read(PIECE) || "".b
127
+ body["length"] = 0 if piece.empty?
128
+ started = @call.call(:post, "#{@path}/uploads", body)
129
+ return started["id"] if started.key?("file")
130
+
131
+ at = 0
132
+ loop do
133
+ following = io.read(PIECE)
134
+ last = following.nil? || following.empty?
135
+ total = last ? (at + piece.bytesize).to_s : "*"
136
+ @raw.call(:put, started["uploadUrl"], piece, { "Content-Range" => "bytes #{at}-#{at + piece.bytesize - 1}/#{total}", "Content-Type" => "application/octet-stream" }, auth: false)
137
+ at += piece.bytesize
138
+ return started["id"] if last
139
+
140
+ piece = following
141
+ end
142
+ end
143
+ end
144
+ end
data/lib/ished.rb ADDED
@@ -0,0 +1,540 @@
1
+ # IshedDB for Ruby, written as the mongo gem is: client.use("clinique")[:patients].find(ville: "Dakar").sort(age: -1).to_a
2
+ # Only Ruby's standard library. The key never travels but over HTTPS (or to this machine). Values: Time <-> dates,
3
+ # Integer beyond 2**53 <-> big integers, binary Strings (ASCII-8BIT) <-> bytes.
4
+ require "json"
5
+ require "net/http"
6
+ require "time"
7
+ require "uri"
8
+
9
+ module Ished
10
+ MAX_DOCUMENTS = 100_000
11
+ SAFE_INT = (2**53) - 1
12
+
13
+ class Error < StandardError
14
+ attr_reader :code, :status
15
+ def initialize(code, message, status = nil)
16
+ super("#{code}: #{message}")
17
+ @code = code
18
+ @status = status
19
+ end
20
+ end
21
+
22
+ InsertOneResult = Struct.new(:inserted_id)
23
+ InsertManyResult = Struct.new(:inserted_ids)
24
+ UpdateResult = Struct.new(:matched_count, :modified_count, :upserted_id)
25
+ DeleteResult = Struct.new(:deleted_count)
26
+ BulkWriteResult = Struct.new(:inserted_count, :matched_count, :modified_count, :deleted_count, :upserted_count, :upserted_ids)
27
+
28
+ def self.to_wire(value)
29
+ case value
30
+ when Time, DateTime then { "~date" => value.to_time.utc.iso8601(3) }
31
+ when Integer then value.abs <= SAFE_INT ? value : { "~int" => value.to_s }
32
+ when String then value.encoding == Encoding::BINARY ? { "~bytes" => [value].pack("m0") } : value
33
+ when Symbol then value.to_s
34
+ when Hash then value.to_h { |k, v| [k.to_s, to_wire(v)] }
35
+ when Array then value.map { |v| to_wire(v) }
36
+ when Float, true, false, nil then value
37
+ else raise Error.new("invalid-argument", "a value of class #{value.class} cannot be kept")
38
+ end
39
+ end
40
+
41
+ def self.from_wire(value)
42
+ case value
43
+ when Array then value.map { |v| from_wire(v) }
44
+ when Hash
45
+ if value.size == 1
46
+ k, v = value.first
47
+ return Time.iso8601(v) if k == "~date"
48
+ return Integer(v) if k == "~int"
49
+ return v.unpack1("m0") if k == "~bytes"
50
+ end
51
+ value.to_h { |k, v| [k, from_wire(v)] }
52
+ else value
53
+ end
54
+ end
55
+
56
+ # As the mongo gem's view: .sort, .limit, .skip, .projection, then .to_a, .each or .first. Read 1000 at a time.
57
+ class View
58
+ include Enumerable
59
+
60
+ def initialize(call, path, filter, options = {})
61
+ @call = call
62
+ @path = path
63
+ @filter = filter || {}
64
+ @options = options
65
+ end
66
+
67
+ def sort(spec) = with(sort: spec)
68
+ def limit(n) = with(limit: n)
69
+ def skip(n) = with(skip: n)
70
+ def projection(spec) = with(projection: spec)
71
+
72
+ def each(&block)
73
+ to_a.each(&block)
74
+ end
75
+
76
+ def first
77
+ limit(1).to_a.first
78
+ end
79
+
80
+ # As the mongo gem's view.explain(verbosity: …): the find's plan (:query_planner, :execution_stats or
81
+ # :all_plans_execution, the default), in MongoDB's shape.
82
+ def explain(verbosity: nil)
83
+ find = { "find" => URI.decode_www_form_component(@path.split("/").last), "filter" => Ished.to_wire(@filter) }
84
+ find["sort"] = Ished.to_wire(@options[:sort]) if @options[:sort]
85
+ find["projection"] = Ished.to_wire(@options[:projection]) if @options[:projection]
86
+ find["skip"] = @options[:skip] if @options[:skip].to_i.positive?
87
+ find["limit"] = @options[:limit] if @options[:limit].to_i.positive?
88
+ body = { "explain" => find }
89
+ body["verbosity"] = verbosity.to_s.gsub(/_(\w)/) { Regexp.last_match(1).upcase } if verbosity
90
+ @call.call(:post, "#{@path}:explain", body)
91
+ end
92
+
93
+ def to_a
94
+ limit = @options[:limit].to_i
95
+ out = []
96
+ token = nil
97
+ loop do
98
+ want = limit.positive? ? [1000, limit - out.size].min : 1000
99
+ body = { "filter" => Ished.to_wire(@filter), "limit" => want }
100
+ # The next page starts after the last one read (its token), never at an offset that moves with writes.
101
+ if token then body["pageToken"] = token else body["skip"] = @options[:skip].to_i end
102
+ body["sort"] = Ished.to_wire(@options[:sort]) if @options[:sort]
103
+ body["projection"] = Ished.to_wire(@options[:projection]) if @options[:projection]
104
+ page = @call.call(:post, "#{@path}:find", body)
105
+ out.concat(page["documents"].map { |d| Ished.from_wire(d) })
106
+ token = page["nextPageToken"]
107
+ return out if token.nil? || (limit.positive? && out.size >= limit)
108
+ raise Error.new("resource-exhausted", "more than #{MAX_DOCUMENTS} documents: narrow the filter") if out.size >= MAX_DOCUMENTS
109
+ end
110
+ end
111
+
112
+ private
113
+
114
+ def with(change) = View.new(@call, @path, @filter, @options.merge(change))
115
+ end
116
+
117
+ class Collection
118
+ def initialize(call, path, options = {})
119
+ @call = call
120
+ @path = path
121
+ @options = options
122
+ end
123
+
124
+ # As the mongo gem's collection.create: an empty collection, or a view when made with view_on: and pipeline:
125
+ # (client[:name, view_on: "source", pipeline: […]].create).
126
+ # Its validator too, as the gem's: client[:name, validator: { "$jsonSchema" => … }, validation_level: "moderate",
127
+ # validation_action: "warn"].create.
128
+ def create
129
+ body = {}
130
+ body["viewOn"] = @options[:view_on].to_s if @options[:view_on]
131
+ body["pipeline"] = Ished.to_wire(@options[:pipeline]) if @options[:pipeline]
132
+ body["validator"] = Ished.to_wire(@options[:validator]) if @options[:validator]
133
+ body["validationLevel"] = @options[:validation_level].to_s if @options[:validation_level]
134
+ body["validationAction"] = @options[:validation_action].to_s if @options[:validation_action]
135
+ @call.call(:post, "#{@path}:create", body)
136
+ self
137
+ end
138
+
139
+ # As the gem's collection.drop: the collection and its documents, or the view.
140
+ def drop = @call.call(:post, "#{@path}:drop", {})["ok"] == 1
141
+
142
+ def find(filter = {}, options = {}) = View.new(@call, @path, filter, options)
143
+
144
+ def count_documents(filter = {})
145
+ @call.call(:post, "#{@path}:countDocuments", { "filter" => Ished.to_wire(filter) })["count"]
146
+ end
147
+
148
+ # As the mongo gem's aggregate: the pipeline run by the server; every result, read 1000 at a time.
149
+ def aggregate(pipeline, _options = {})
150
+ out = []
151
+ skip = 0
152
+ loop do
153
+ page = @call.call(:post, "#{@path}:aggregate", { "pipeline" => Ished.to_wire(pipeline), "limit" => 1000, "skip" => skip })
154
+ out.concat(page["documents"].map { |d| Ished.from_wire(d) })
155
+ return out unless page["more"]
156
+ raise Error.new("resource-exhausted", "more than #{MAX_DOCUMENTS} documents: add $limit") if out.size >= MAX_DOCUMENTS
157
+ skip += 1000
158
+ end
159
+ end
160
+
161
+ # As the mongo gem's bulk_write: [{ insert_one: doc }, { update_one: { filter:, update:, upsert: } }, { update_many: … },
162
+ # { replace_one: { filter:, replacement: } }, { delete_one: { filter: } }, { delete_many: … }]; ordered: false goes on.
163
+ def bulk_write(requests, options = {})
164
+ ops = requests.map do |request|
165
+ name, args = request.first
166
+ camel = name.to_s.gsub(/_(\w)/) { Regexp.last_match(1).upcase }
167
+ { camel => (camel == "insertOne" ? { "document" => args } : args.transform_keys(&:to_s)) }
168
+ end
169
+ r = @call.call(:post, "#{@path}:bulkWrite", { "operations" => Ished.to_wire(ops), "ordered" => options.fetch(:ordered, true) })
170
+ BulkWriteResult.new(r["insertedCount"], r["matchedCount"], r["modifiedCount"], r["deletedCount"], r["upsertedCount"], r["upsertedIds"].transform_keys(&:to_i))
171
+ end
172
+
173
+ # The collection's number of documents, from the statistics (at once on a big collection).
174
+ def estimated_document_count
175
+ @call.call(:post, "#{@path}:estimatedDocumentCount", {})["count"]
176
+ end
177
+
178
+ # The different values of a field among the documents found (a list's items one by one).
179
+ def distinct(field_name, filter = {})
180
+ @call.call(:post, "#{@path}:distinct", { "key" => field_name.to_s, "filter" => Ished.to_wire(filter) })["values"].map { |v| Ished.from_wire(v) }
181
+ end
182
+
183
+ def insert_one(document)
184
+ InsertOneResult.new(@call.call(:post, "#{@path}:insertOne", { "document" => Ished.to_wire(document) })["insertedId"])
185
+ end
186
+
187
+ def insert_many(documents)
188
+ ids = []
189
+ documents.each_slice(1000) do |slice|
190
+ r = @call.call(:post, "#{@path}:insertMany", { "documents" => slice.map { |d| Ished.to_wire(d) } })
191
+ ids.concat((0...r["insertedIds"].size).map { |i| r["insertedIds"][i.to_s] })
192
+ end
193
+ InsertManyResult.new(ids)
194
+ end
195
+
196
+ def update_one(filter, update, upsert: false) = change("updateOne", filter, "update", update, upsert)
197
+ def update_many(filter, update) = change("updateMany", filter, "update", update, nil)
198
+ def replace_one(filter, replacement, upsert: false) = change("replaceOne", filter, "replacement", replacement, upsert)
199
+
200
+ def delete_one(filter = {})
201
+ DeleteResult.new(@call.call(:post, "#{@path}:deleteOne", { "filter" => Ished.to_wire(filter) })["deletedCount"])
202
+ end
203
+
204
+ def delete_many(filter = {})
205
+ DeleteResult.new(@call.call(:post, "#{@path}:deleteMany", { "filter" => Ished.to_wire(filter) })["deletedCount"])
206
+ end
207
+
208
+ private
209
+
210
+ def change(method, filter, key, value, upsert)
211
+ body = { "filter" => Ished.to_wire(filter), key => Ished.to_wire(value) }
212
+ body["upsert"] = upsert unless upsert.nil?
213
+ r = @call.call(:post, "#{@path}:#{method}", body)
214
+ UpdateResult.new(r["matchedCount"], r["modifiedCount"], r["upsertedId"])
215
+ end
216
+ end
217
+
218
+ # As the driver's session: client.start_session { |s| s.with_transaction { coll.update_one(f, u, session: s) } }.
219
+ # The transaction is held by the server (60 seconds at most, 20 without a request); a conflict with another
220
+ # transaction answers "aborted", and with_transaction runs the block again.
221
+ class Session
222
+ def initialize(call, v1)
223
+ @call = call
224
+ @v1 = v1
225
+ @id = nil
226
+ end
227
+
228
+ def in_transaction? = !@id.nil?
229
+
230
+ def start_transaction(_options = {})
231
+ raise Error.new("failed-precondition", "a transaction is already started in this session") if @id
232
+
233
+ @id = @call.call(:post, "#{@v1}:beginTransaction", {})["transaction"]
234
+ nil
235
+ end
236
+
237
+ def bind(call)
238
+ header = { "X-Ished-Transaction" => @id }
239
+ ->(method, path, body) { call.call(method, path, body, header) }
240
+ end
241
+
242
+ def commit_transaction
243
+ raise Error.new("failed-precondition", "no transaction started in this session") unless @id
244
+
245
+ tx = @id
246
+ @id = nil
247
+ @call.call(:post, "#{@v1}:commit", { transaction: tx })
248
+ nil
249
+ end
250
+
251
+ def abort_transaction
252
+ return unless @id
253
+
254
+ tx = @id
255
+ @id = nil
256
+ @call.call(:post, "#{@v1}:rollback", { transaction: tx })
257
+ nil
258
+ rescue Error => e
259
+ raise unless e.code == "not-found" # already ended by the server (an error, or too long): nothing kept
260
+ end
261
+
262
+ def with_transaction(_options = {}, max_attempts: 5)
263
+ attempt = 0
264
+ begin
265
+ attempt += 1
266
+ start_transaction
267
+ out = yield self
268
+ commit_transaction
269
+ out
270
+ rescue Exception => e # rubocop:disable Lint/RescueException -- given back as it came
271
+ begin
272
+ abort_transaction
273
+ rescue Error
274
+ nil
275
+ end
276
+ retry if e.is_a?(Error) && e.code == "aborted" && attempt < max_attempts
277
+ raise
278
+ end
279
+ end
280
+
281
+ def end_session = abort_transaction
282
+ end
283
+
284
+ # session: as the driver's: the method (and the view it gives, read later) runs in the session's transaction.
285
+ module InSession
286
+ %i[find count_documents aggregate bulk_write estimated_document_count distinct insert_one insert_many
287
+ update_one update_many replace_one delete_one delete_many].each do |name|
288
+ define_method(name) do |*args, **kw, &block|
289
+ session = kw.delete(:session) if kw[:session].is_a?(Session)
290
+ last = args.last
291
+ if session.nil? && last.is_a?(Hash) && last[:session].is_a?(Session)
292
+ session = last[:session]
293
+ args = [*args[0...-1], last.except(:session)]
294
+ end
295
+ return super(*args, **kw, &block) unless session&.in_transaction?
296
+
297
+ Collection.new(session.bind(@call), @path).public_send(name, *args, **kw, &block)
298
+ end
299
+ end
300
+ end
301
+ Collection.prepend(InSession)
302
+
303
+ # As the driver's change stream: stream = coll.watch(pipeline, full_document: "updateLookup"); stream.each { |change| … }
304
+ # (blocks, waiting for changes), try_next, resume_token, close. Opened at once: the changes made from then on are
305
+ # seen. Each request waits up to max_await_time_ms (10 s by default, 20 s at most) on the server. A collection
306
+ # dropped or renamed ends its stream ("invalidate").
307
+ class ChangeStream
308
+ include Enumerable
309
+
310
+ def initialize(call, path, pipeline, options)
311
+ @call = call
312
+ @path = path
313
+ @body = { pipeline: Ished.to_wire(pipeline || []) }
314
+ @body[:fullDocument] = options[:full_document] if options[:full_document]
315
+ @body[:fullDocumentBeforeChange] = options[:full_document_before_change] if options[:full_document_before_change]
316
+ @body[:batchSize] = options[:batch_size] if options[:batch_size]
317
+ @wait = options[:max_await_time_ms] || 10_000
318
+ @position = options[:resume_after] || options[:start_after]
319
+ @at = options[:start_at_operation_time]
320
+ @token = @position
321
+ @buffer = []
322
+ @closed = false
323
+ fetch(0) if @position.nil? && @at.nil?
324
+ end
325
+
326
+ # The token to resume after the last change given (resume_after:).
327
+ def resume_token = @token
328
+ def closed? = @closed
329
+
330
+ # Each change as it comes, waiting for it, until the stream is closed.
331
+ def each
332
+ return to_enum(:each) unless block_given?
333
+
334
+ loop do
335
+ fetch(@wait) while @buffer.empty? && !@closed
336
+ break if @buffer.empty?
337
+
338
+ yield take
339
+ end
340
+ end
341
+
342
+ # The next change if one comes within a second (or max_await_time_ms, if shorter), else nil.
343
+ def try_next
344
+ fetch([@wait, 1000].min) if @buffer.empty? && !@closed
345
+ @buffer.empty? ? nil : take
346
+ end
347
+
348
+ def close
349
+ @closed = true
350
+ @buffer = []
351
+ nil
352
+ end
353
+
354
+ private
355
+
356
+ def fetch(wait)
357
+ body = @body.merge(maxAwaitTimeMS: wait)
358
+ if @position then body[:resumeAfter] = @position
359
+ elsif @at then body[:startAtOperationTime] = Ished.to_wire(@at)
360
+ end
361
+ r = @call.call(:post, @path, body)
362
+ @at = nil
363
+ @position = r["resumeToken"]
364
+ @buffer.concat(r["changes"].map { |c| Ished.from_wire(c) })
365
+ @token = r["resumeToken"] if @buffer.empty?
366
+ end
367
+
368
+ def take
369
+ change = @buffer.shift
370
+ @token = @buffer.empty? ? @position : change["_id"]
371
+ @closed = true if change["operationType"] == "invalidate"
372
+ change
373
+ end
374
+ end
375
+
376
+ # As the driver's index view: collection.indexes.create_one({ a: 1, b: -1 }, unique: true); create_many, each
377
+ # (Enumerable), drop_one, drop_all. A text index: create_one({ titre: "text" }, default_language: "french").
378
+ class IndexView
379
+ include Enumerable
380
+
381
+ OPTIONS = { unique: :unique, name: :name, partial_filter_expression: :partialFilterExpression, weights: :weights,
382
+ default_language: :default_language, expire_after: :expireAfterSeconds,
383
+ wildcard_projection: :wildcardProjection }.freeze
384
+
385
+ def initialize(call, path)
386
+ @call = call
387
+ @path = path
388
+ end
389
+
390
+ def create_one(keys, options = {}) = @call.call(:post, "#{@path}:createIndex", Ished.to_wire(spec(keys, options)))["name"]
391
+
392
+ def create_many(models)
393
+ specs = models.map { |m| spec(m[:key], m.reject { |k, _| k == :key }) }
394
+ @call.call(:post, "#{@path}:createIndexes", Ished.to_wire({ indexes: specs }))["names"]
395
+ end
396
+
397
+ def each(&block) = @call.call(:post, "#{@path}:listIndexes", {})["indexes"].map { |i| Ished.from_wire(i) }.each(&block)
398
+
399
+ def drop_one(name) = @call.call(:post, "#{@path}:dropIndex", { index: name }) && nil
400
+ def drop_all = @call.call(:post, "#{@path}:dropIndexes", {}) && nil
401
+
402
+ private
403
+
404
+ def spec(keys, options)
405
+ out = { key: keys.map { |k, v| [k.to_s, v] } }
406
+ options.each do |k, v|
407
+ name = OPTIONS[k.to_sym] or raise Error.new("invalid-argument", "index option #{k} is not offered")
408
+ out[name] = v
409
+ end
410
+ out
411
+ end
412
+ end
413
+
414
+ class Collection
415
+ # As the driver's collection.indexes: create_one, create_many, each, drop_one, drop_all.
416
+ def indexes = IndexView.new(@call, @path)
417
+
418
+ # As the driver's collection.watch: the collection's changes as they happen.
419
+ def watch(pipeline = [], options = {}) = ChangeStream.new(@call, "#{@path}:watch", pipeline, options)
420
+ end
421
+
422
+ class Database
423
+ def initialize(call, path, raw = nil)
424
+ @call = call
425
+ @path = path
426
+ @raw = raw
427
+ end
428
+
429
+ # As the gem's database.fs(bucket_name:): the files of a bucket, as GridFS (ished/grid.rb).
430
+ def fs(bucket_name: "fs") = FSBucket.new(self, @call, @raw, @path, bucket_name: bucket_name)
431
+
432
+ # As the driver's database.watch: the changes of every collection of the base.
433
+ def watch(pipeline = [], options = {}) = ChangeStream.new(@call, "#{@path}:watch", pipeline, options)
434
+
435
+ def collection(name, options = {}) = Collection.new(@call, "#{@path}/collections/#{URI.encode_www_form_component(name.to_s).gsub('+', '%20')}", options)
436
+ alias [] collection
437
+
438
+ def collection_names = @call.call(:get, "#{@path}/collections", nil).map { |c| c["name"] }
439
+
440
+ # As the gem's database.list_collections: name, type ("collection" or "view"), options, info.
441
+ def list_collections
442
+ @call.call(:get, "#{@path}/collections", nil).map do |c|
443
+ view = c["type"] == "view"
444
+ { "name" => c["name"], "type" => c["type"], "options" => view ? { "viewOn" => c["viewOn"], "pipeline" => c["pipeline"] } : {}, "info" => { "readOnly" => view } }
445
+ end
446
+ end
447
+
448
+ # As the gem's database.command: create, collMod (a view's viewOn and pipeline), drop, explain. Answers the
449
+ # reply's document.
450
+ def command(document) = Ished.from_wire(@call.call(:post, "#{@path}:runCommand", Ished.to_wire(document)))
451
+ end
452
+
453
+ class Client
454
+ def initialize(call, v1, raw = nil)
455
+ @call = call
456
+ @v1 = v1
457
+ @raw = raw
458
+ end
459
+
460
+ def use(name) = Database.new(@call, "#{@v1}/bases/#{URI.encode_www_form_component(name.to_s).gsub('+', '%20')}", @raw)
461
+ alias database use
462
+ alias db use
463
+
464
+ # As the driver's client.watch: the changes of the whole cluster.
465
+ def watch(pipeline = [], options = {}) = ChangeStream.new(@call, "#{@v1}:watch", pipeline, options)
466
+
467
+ # As the driver's client.list_databases: each base's name, sizeOnDisk and empty (a key limited to some: those).
468
+ def list_databases = @call.call(:get, "#{@v1}/bases", nil)["databases"]
469
+
470
+ # As the driver's client.database_names.
471
+ def database_names = list_databases.map { |d| d["name"] }
472
+ alias list_database_names database_names
473
+
474
+ def start_session
475
+ session = Session.new(@call, @v1)
476
+ return session unless block_given?
477
+
478
+ begin
479
+ yield session
480
+ ensure
481
+ session.end_session
482
+ end
483
+ end
484
+ end
485
+
486
+ # A client for one project (its key), in one of its clusters (by default the first, "Cluster0").
487
+ def self.connect(url, key, cluster: nil, timeout: 30)
488
+ uri = URI(url)
489
+ local = %w[127.0.0.1 localhost ::1].include?(uri.host)
490
+ raise Error.new("invalid-argument", "IshedDB is reached over HTTPS (plain HTTP only to this machine)") unless uri.scheme == "https" || (uri.scheme == "http" && local)
491
+ raise Error.new("invalid-argument", "a key ished_sk_… is needed") unless key.is_a?(String) && key.start_with?("ished_sk_")
492
+ raise Error.new("invalid-argument", 'cluster: 1 to 64 letters, digits or "-"') if cluster && cluster !~ /\A[A-Za-z0-9][A-Za-z0-9-]{0,63}\z/
493
+ root = url.chomp("/")
494
+ v1 = cluster ? "/v1/clusters/#{cluster}" : "/v1"
495
+ call = lambda do |method, path, body, extra = {}|
496
+ target = URI(root + path)
497
+ request = method == :get ? Net::HTTP::Get.new(target) : Net::HTTP::Post.new(target)
498
+ request["Authorization"] = "Bearer #{key}"
499
+ extra.each { |name, value| request[name] = value }
500
+ if body
501
+ request["Content-Type"] = "application/json"
502
+ request.body = JSON.generate(body)
503
+ end
504
+ response = Net::HTTP.start(target.host, target.port, use_ssl: target.scheme == "https", open_timeout: timeout, read_timeout: timeout) { |h| h.request(request) }
505
+ text = response.body.to_s.force_encoding("UTF-8")
506
+ unless response.is_a?(Net::HTTPSuccess)
507
+ err = (JSON.parse(text)["error"] rescue nil) || {}
508
+ raise Error.new(err["code"] || "internal", err["message"] || "HTTP #{response.code}", response.code.to_i)
509
+ end
510
+ text.empty? ? nil : JSON.parse(text)
511
+ end
512
+ # The files' bytes (ished/grid.rb): an upload session's own address (no key sent to it), or a download with the
513
+ # key, its bytes given to the block as they come.
514
+ raw = lambda do |method, where, data, extra, auth: true, &block|
515
+ target = URI(where.start_with?("http://", "https://") ? where : root + where)
516
+ raise Error.new("invalid-argument", "a file's address is reached over HTTPS only") unless target.scheme == "https" || (target.scheme == "http" && %w[127.0.0.1 localhost ::1].include?(target.host))
517
+
518
+ request = method == :put ? Net::HTTP::Put.new(target) : Net::HTTP::Get.new(target)
519
+ request["Authorization"] = "Bearer #{key}" if auth
520
+ extra.each { |name, value| request[name] = value }
521
+ request.body = data if data
522
+ Net::HTTP.start(target.host, target.port, use_ssl: target.scheme == "https", open_timeout: timeout, read_timeout: timeout) do |h|
523
+ h.request(request) do |response|
524
+ unless response.is_a?(Net::HTTPSuccess)
525
+ text = response.read_body.to_s.force_encoding("UTF-8")
526
+ err = (JSON.parse(text)["error"] rescue nil) || {}
527
+ raise Error.new(err["code"] || "internal", err["message"] || "HTTP #{response.code}", response.code.to_i)
528
+ end
529
+ block ? response.read_body { |chunk| block.call(chunk) } : response.read_body
530
+ end
531
+ end
532
+ end
533
+ Client.new(call, v1, raw)
534
+ end
535
+
536
+ # A path's segment, as the addresses want it.
537
+ def self.segment(text) = URI.encode_www_form_component(text.to_s).gsub("+", "%20")
538
+ end
539
+
540
+ require_relative "ished/grid"
metadata ADDED
@@ -0,0 +1,43 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ished
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Bridge
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ executables: []
13
+ extensions: []
14
+ extra_rdoc_files: []
15
+ files:
16
+ - LICENSE
17
+ - lib/ished.rb
18
+ - lib/ished/grid.rb
19
+ homepage: https://isheddb.com
20
+ licenses:
21
+ - Apache-2.0
22
+ metadata:
23
+ source_code_uri: https://github.com/treecode9-arch/ished-drivers
24
+ rubygems_mfa_required: 'true'
25
+ rdoc_options: []
26
+ require_paths:
27
+ - lib
28
+ required_ruby_version: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '3.1'
33
+ required_rubygems_version: !ruby/object:Gem::Requirement
34
+ requirements:
35
+ - - ">="
36
+ - !ruby/object:Gem::Version
37
+ version: '0'
38
+ requirements: []
39
+ rubygems_version: 4.0.11
40
+ specification_version: 4
41
+ summary: IshedDB, written as MongoDB’s official driver of each language (Ruby, as
42
+ the mongo gem)
43
+ test_files: []