store-digest-http 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a72d6b02d91d9dd43d504f4649349c824c772f2f9dca6d66956030b576b7554c
4
+ data.tar.gz: 5bd41ae90ef5eddb436cb96e0bd066ad4c53e5a4315c6b77a7314970a5daf0f4
5
+ SHA512:
6
+ metadata.gz: 566ea9753c1ac630771303491d6aac7f22226fb40bc9ed2c04d6a8812c3c46c82dfeedbbc32b2a0453f870fb4073c378cb150b2a864939d18d617f345bfe7cc2
7
+ data.tar.gz: 6fb63fb6e96c8752130ce21e9b5a747d6e0afc4a5af55b04386e6284285de0fceaad7470419640cff33f3e658279bdb722259b4be82e152a94c8bb13f7dd9598
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ # gem files lol
13
+ *.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.5.5
6
+ before_install: gem install bundler -v 2.1.2
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in store-digest-http.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "rspec", "~> 3.0"
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.
@@ -0,0 +1,36 @@
1
+ # Store::Digest::HTTP
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/store/digest/http`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'store-digest-http'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install store-digest-http
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/store-digest-http.
36
+
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "store/digest/http"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env ruby
2
+ # -*- mode: enh-ruby -*-
3
+
4
+ require 'store/digest'
5
+ require 'store/digest/http'
6
+ require 'commander'
7
+ require 'rack'
8
+
9
+
10
+ HOST = '0.0.0.0'
11
+ PORT = 10101
12
+ MAPSIZE = 2**30
13
+
14
+ Commander.configure do
15
+ program :name, File.basename($0)
16
+ program :version, Store::Digest::HTTP::VERSION
17
+ program :description, 'Command-line starter for Store::Digest::HTTP'
18
+
19
+ command :serve do |c|
20
+ c.option '-d', '--dir DIR', 'The root directory of the store'
21
+ c.option '-m', '--mapsize BYTES', 'The memory map size of the store'
22
+ c.option '-h', '--host NAME', "Specify host"
23
+ c.option '-p', '--port NUMBER', "Specify TCP port (default #{PORT})"
24
+ c.option '-z', '--detach', 'Detach and daemonize the process'
25
+ c.option '-F', '--fastcgi', 'Run as FastCGI rather than standalone'
26
+
27
+ c.action do |args, opts|
28
+ opts.default :host => HOST, :port => PORT, :mapsize => MAPSIZE
29
+
30
+ raise Commander::Runner::CommandError.new 'No root directory' unless
31
+ opts.dir
32
+
33
+ store = Store::Digest.new dir: opts.dir, mapsize: opts.mapsize
34
+
35
+ Rack::Server.start({
36
+ app: Store::Digest::HTTP.new(store),
37
+ server: opts.fastcgi ? 'fastcgi' : 'webrick',
38
+ environment: 'none',
39
+ daemonize: opts.detach,
40
+ Host: opts.host,
41
+ Port: opts.port,
42
+ })
43
+ end
44
+ end
45
+
46
+ default_command :serve
47
+
48
+ run!
49
+ end
@@ -0,0 +1,381 @@
1
+ require 'store/digest/http/version'
2
+ require 'uri/ni'
3
+ require 'xml/mixup'
4
+ require 'rack'
5
+ require 'rack/request'
6
+ require 'rack/response'
7
+
8
+ class Store::Digest::HTTP
9
+ private
10
+
11
+ DIGESTS = {
12
+ md5: 16,
13
+ "sha-1": 20,
14
+ "sha-256": 32,
15
+ "sha-384": 48,
16
+ "sha-512": 64,
17
+ }.freeze
18
+
19
+
20
+ COERCIONS = {
21
+ string: -> str { str.to_s },
22
+ symbol: -> sym { sym.to_s.to_sym },
23
+ integer: -> int { int.to_i },
24
+ time: -> time do
25
+ return time if time.is_a? Time
26
+ return time.to_time if time.is_a? DateTime
27
+ time = time.to_s + 'T00:00:00Z' if /^\d{4}-\d\d-\d\d$/.match? time.to_s
28
+ Time.iso8601 time.to_s rescue nil
29
+ end
30
+ }.freeze
31
+
32
+ COERCE_MAP = {
33
+ size: [:size, COERCIONS[:integer]],
34
+ created: [:ctime, COERCIONS[:time]],
35
+ modified: [:mtime, COERCIONS[:time]],
36
+ "meta-modified": [:ptime, COERCIONS[:time]],
37
+ deleted: [:dtime, COERCIONS[:time]],
38
+ boundary: [:boundary, COERCIONS[:integer]],
39
+ }
40
+
41
+ def uri_query uri
42
+ out = {}
43
+ if uri.query
44
+ URI.decode_www_form(uri.query).each do |k, v|
45
+ k = k.to_sym
46
+ out[k] ||= []
47
+ out[k] << v
48
+ end
49
+ end
50
+ out
51
+ end
52
+
53
+ def coerce_query query
54
+ out = {}
55
+
56
+ # let's force this into an assoc and treat it like it may have the
57
+ # keys repeated (as in URI.decode_www_form)
58
+ query.to_a.each do |q|
59
+ raise ArgumentError, "#{q.inspect} must be an array" unless q.is_a? Array
60
+
61
+ # when flattened, the first element is the key and subsequent
62
+ # elements are values
63
+ k, *v = q.flatten
64
+ k = k.to_sym
65
+ if COERCE_MAP.key? k
66
+ # rewrite outside keys to inside keys
67
+ k, coerce = COERCE_MAP[k]
68
+ v.map! { |x| coerce.call x if x and !x.to_s.empty? }
69
+ end
70
+ # this will collate and append any values
71
+ out.key?(k) ? out[k] += v : out[k] = v
72
+ end
73
+
74
+ out
75
+ end
76
+
77
+ # this will do for now
78
+ def serialize_query hash
79
+ hash.to_a.map do |pair|
80
+ k, *v = pair.flatten
81
+ v.map { |x| [k.to_s, x.to_s].join ?= }
82
+ end.flatten.join(?&).gsub(/\+/, '%2B')
83
+ end
84
+
85
+ BASE = /^\/+\.well-known\/+[dn]i\/+/.freeze
86
+ POST_RAW = '0c17e171-8cb1-4c60-9c58-f218075ae9a9'.freeze
87
+ POST_FORM = '12d851b7-5f71-405c-bb44-bd97b318093a'.freeze
88
+ DISPATCH = {
89
+ object: {}, meta: {}, partial: {},
90
+ collection: {}, stats: {}, raw: {}, form: {},
91
+ }
92
+
93
+ DISPATCH[:object][:GET] = -> uri, query, hdrs, body = nil do
94
+ # note this can be anything
95
+ ni = URI('ni:///%s;%s' % query.values_at(:algorithm, :digest))
96
+ obj = store.get ni
97
+
98
+ resp = Rack::Response[404, [], []]
99
+
100
+ return resp unless obj
101
+
102
+ # overwrite ni uri
103
+ ni = obj[store.primary] # overwrite ni uri with canonical
104
+ ct = obj.content # make sure we have content
105
+ lm = obj.mtime || obj.ctime # get last-modified
106
+
107
+ # this is deleted
108
+ if dt = obj.dtime or !ct
109
+ dt ||= lm
110
+ resp.status = 410
111
+ resp.set_header 'Last-Modified', dt.getgm.rfc822
112
+ return resp
113
+ end
114
+
115
+ # set up the final response
116
+ resp.status = 304
117
+ resp.set_header 'Last-Modified', lm.getgm.rfc822
118
+ resp.set_header 'ETag', '"%s"' % ni.to_s
119
+ cl = "/.well-known/ni/#{ni.algorithm}/#{ni.b64digest}"
120
+ resp.set_header 'Content-Location', cl if cl != uri.request_uri
121
+
122
+ cc = %w[HTTP_CACHE_CONTROL HTTP_PRAGMA].map do |h|
123
+ (hdrs[h] || '').split(/s*,+\s*/)
124
+ end.flatten.map(&:downcase).uniq
125
+
126
+ unless cc.include? 'no-cache'
127
+ # check etag
128
+ if inm = hdrs['HTTP_IF_NONE_MATCH']
129
+ inm = inm.split(/\s*,+\s*/).map { |i| i.tr_s ?", '' }
130
+ return resp unless (obj.digests.values.map(&:to_s) & inm).empty?
131
+ end
132
+
133
+ # check if-modified-since
134
+ if ims = hdrs['HTTP_IF_MODIFIED_SINCE']
135
+ ims.gsub!(/^([^,]*(?:,[^,]*)?)(?:\s*,.*)?$/, "\\1")
136
+ if ims = Time.httpdate(ims).getgm rescue nil
137
+ return resp if ims > lm
138
+ end
139
+ end
140
+ end
141
+
142
+ # set headers
143
+ type = obj.type.dup # note the type comes out frozen
144
+ type << ";charset=#{obj.charset}" if obj.charset
145
+ resp.set_header 'Content-Type', type
146
+ resp.set_header 'Content-Encoding', obj.encoding if obj.encoding
147
+ resp.set_header 'Content-Length', obj.size.to_s
148
+
149
+ # return 200
150
+ resp.status = 200
151
+ resp.body = ct
152
+
153
+ resp
154
+ end
155
+
156
+ DISPATCH[:stats][:GET] = -> uri, query, hdrs, body = nil do
157
+ stats = store.stats
158
+
159
+ pri = store.primary
160
+
161
+ sections = stats.label_struct.map do |slug, values|
162
+ label, values = values
163
+ { [
164
+ { [label] => :h2 },
165
+ { values.map { |val, count|
166
+ q = serialize_query({ slug => val})
167
+ href = "#{pri}/?#{q}"
168
+
169
+ { { [ { [val] => :code }, ': ',
170
+ { [count] => :var }] => :a, href: href } => :li } } => :ul },
171
+ ] => :section }
172
+ end
173
+
174
+ doc = XML::Mixup.xhtml_stub(
175
+ title: 'Content-Addressable Storage Stats',
176
+ content: [
177
+ { [
178
+ { ['Statistics'] => :h2 },
179
+ { [
180
+ { ['Created:'] => :dt },
181
+ { [stats.ctime] => :dd },
182
+ { ['Last modified:'] => :dt },
183
+ { [stats.mtime] => :dd },
184
+ { ['Total objects:'] => :dt },
185
+ { [stats.objects] => :dd },
186
+ { ['Deleted records:'] => :dt },
187
+ { [stats.deleted] => :dd },
188
+ { ['Repository size:'] => :dt },
189
+ { [stats.human_size] => :dd } ] => :dl },
190
+ ] => :section } ] + sections,
191
+ ).document
192
+
193
+ [200, [['Content-Type', 'application/xhtml+xml;charset=utf-8']], doc.to_xml]
194
+ end
195
+
196
+ THEAD = { [
197
+ 'Digest', 'Size', 'Media Type', 'Language', 'Character Set', 'Encoding',
198
+ 'Added to Store', 'Modified', 'Metadata Changed', 'Deleted?'].map do |x|
199
+ { [x] => :th }
200
+ end => :thead }.freeze
201
+
202
+ LINKS = {
203
+ first: ['First', ?[],
204
+ prev: ['Previous', ?-],
205
+ next: ['Next', ?=],
206
+ last: ['Last', ?]],
207
+ }
208
+
209
+ DISPATCH[:collection][:GET] = -> uri, query, hdrs, body = nil do
210
+ # parse query components
211
+ query = coerce_query query
212
+
213
+ # if there is no boundary parameter we redirect so there is
214
+ unless query[:boundary]
215
+ q = uri.query || ''
216
+ q << ?& unless q.empty?
217
+ q << serialize_query({ boundary: [1, 100] })
218
+ uri.query = q
219
+ return [307, [['Location', uri.to_s]], []]
220
+ end
221
+
222
+ # now we sanitize the boundary
223
+ bound = query.delete :boundary
224
+ bound[0] = 1 unless bound[0] and bound[0] >= 1
225
+ bound[1] = 100 unless bound[1] and bound[1] >= bound[0]
226
+ offset = bound[0] - 1
227
+ limit = bound[1] - offset
228
+
229
+ # okay everything else in here should be legit
230
+ tr = store.list(**query)
231
+ len = tr.length
232
+ tr = tr.slice(offset, limit).map do |obj|
233
+ td = [{ [{ [obj[store.primary].hexdigest] => :a,
234
+ href: obj[store.primary].b64digest }] => :td }] +
235
+ %i[type size language charset encoding
236
+ ctime mtime ptime dtime].map do |p|
237
+ v = obj.send(p)
238
+ v = v.is_a?(Time) ? v.getgm.iso8601 : v.to_s
239
+ { [v] => :td }
240
+ end
241
+ { td => :tr }
242
+ end
243
+
244
+ links = {
245
+ # first is 1 .. limit, only active if offset > 0
246
+ first: offset > 0 ? [1, limit] : nil,
247
+ # prev is also only active if offset > 0 but will subtract by limit
248
+ prev: offset > 0 ? [
249
+ (x = (offset - limit >= 0 ? offset - limit : 0)) + 1, x + limit] : nil,
250
+ # next is only active if len > offset + page
251
+ next: (offset + limit) < len ?
252
+ [offset + limit + 1, 2 * limit + offset] : nil,
253
+ # last is also only active if len > offset + page and
254
+ last: (offset + limit) < len ?
255
+ [(x = (len.to_f / limit).floor * limit) + 1, x + limit] : nil,
256
+ }.map do |rel, bound|
257
+ link = if bound
258
+ lab, ak = LINKS[rel]
259
+ # href = uri.dup
260
+ q = uri_query uri
261
+ q = serialize_query(q.merge({ boundary: bound }))
262
+ # href.query = q
263
+ { [lab] => :a, rel: rel,
264
+ accesskey: ak, href: "?#{q}" }
265
+ else
266
+ LINKS[rel].first
267
+ end
268
+ { [link] => :li }
269
+ end
270
+
271
+
272
+ doc = XML::Mixup.xhtml_stub(
273
+ title: "Listing stored objects",
274
+ content: { [ { [ { links => :ul } ] => :caption },
275
+ THEAD, { tr => :tbody } ] => :table }
276
+ ).document
277
+
278
+ [200, [['Content-Type', 'application/xhtml+xml']], doc.to_xml]
279
+ end
280
+
281
+ public
282
+
283
+ attr_reader :store, :post_raw, :post_form
284
+
285
+ def initialize store, base: nil, post_raw: nil, post_form: nil, param_map: nil
286
+ @store = store
287
+ @base = base || BASE
288
+ @post_raw = post_raw || POST_RAW
289
+ @post_form = post_form || POST_FORM
290
+ end
291
+
292
+ def call env
293
+ # warn env.inspect
294
+ # do surgery to request scheme
295
+ env['HTTPS'] = 'on' if
296
+ env['REQUEST_SCHEME'] and env['REQUEST_SCHEME'].downcase == 'https'
297
+
298
+ req = Rack::Request.new env
299
+ uri = URI(req.base_url) + env['REQUEST_URI']
300
+ path = uri.path.gsub(/^\/+\.well-known\/+ni\/+/, '').split(/\/+/, -1)
301
+ query = uri_query uri # XXX req.GET is worthless
302
+ body = req.body
303
+
304
+ # dispatch type
305
+ disp = nil
306
+ if path.empty?
307
+ disp = :stats
308
+ elsif store.algorithms.include?(algo = path.first.to_sym)
309
+ if slug = path[1]
310
+ if slug.empty?
311
+ disp = :collection
312
+ elsif !/^[0-9A-Za-z_-]+$/.match?(slug)
313
+ return [404, [], []]
314
+ else
315
+ # determine if we have a whole digest or just part of one
316
+ algo = query[:algorithm] = path.first.to_sym
317
+
318
+ query[:digest] = slug
319
+
320
+ if /^[0-9A-Za-z_-]+$/.match?(slug) and
321
+ slug.length == (DIGESTS[algo] * 4/3.0).ceil
322
+ disp = :object
323
+ elsif /^[0-9A-Fa-f]+$/.match?(slug) and
324
+ slug.length == DIGESTS[algo] * 2
325
+ query[:radix] = 16
326
+
327
+ disp = :object
328
+ else
329
+ disp = :partial
330
+ end
331
+ end
332
+ else
333
+ # redirect 307
334
+ newuri = req.base_url + "/.well-known/ni/#{algo}/"
335
+ return [307, [['Location', newuri.to_s]], []]
336
+ end
337
+ elsif path.first == post_raw
338
+ disp = :raw
339
+ elsif path.first == post_form
340
+ # 415 unsupported media type
341
+ # XXX EXPLAIN THIS
342
+ return [415, [], []] unless
343
+ req.get_header('Content-Type') == 'multipart/form-data'
344
+
345
+ # 409 conflict
346
+ # XXX EXPLAIN THIS
347
+ return Rack::Response[409, [], []] unless
348
+ req.POST.values.any? { |f|
349
+ f.is_a? Rack::Multipart::UploadedFile }
350
+
351
+ # XXX here is where we would set the date from the
352
+ # multipart header but rack doesn't have a way of doing this
353
+
354
+ disp = :raw
355
+ else
356
+ # 404 again
357
+ return [404, [], []]
358
+ end
359
+
360
+ if methods = DISPATCH[disp]
361
+ m = (req.request_method == 'HEAD' ? 'GET' : req.request_method).to_sym
362
+ if func = methods[m]
363
+ begin
364
+ resp = instance_exec uri.dup, query, req.env.dup, body, &func
365
+ resp = Rack::Response[*resp] if resp.is_a? Array
366
+ rescue Exception => e
367
+ warn "wah #{e}"
368
+ return [500, [], []]
369
+ end
370
+
371
+ resp.body = [] if req.request_method == 'HEAD'
372
+
373
+ return resp.to_a
374
+ else
375
+ return [405, [], []]
376
+ end
377
+ else
378
+ return [404, [], []]
379
+ end
380
+ end
381
+ end
@@ -0,0 +1,7 @@
1
+ module Store
2
+ class Digest
3
+ class HTTP
4
+ VERSION = "0.1.0"
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,44 @@
1
+ # -*- mode: enh-ruby -*-
2
+ require_relative 'lib/store/digest/http/version'
3
+
4
+ Gem::Specification.new do |spec|
5
+ spec.name = "store-digest-http"
6
+ spec.version = Store::Digest::HTTP::VERSION
7
+ spec.authors = ["Dorian Taylor"]
8
+ spec.email = ["code@doriantaylor.com"]
9
+
10
+ spec.summary = %q{HTTP front-end to Store::Digest}
11
+ spec.homepage = "https://github.com/doriantaylor/rb-store-digest-http"
12
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
13
+
14
+ spec.metadata["homepage_uri"] = spec.homepage
15
+
16
+ # Specify which files should be added to the gem when it is
17
+ # released. The `git ls-files -z` loads the files in the RubyGem
18
+ # that have been added into git.
19
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
20
+ `git ls-files -z`.split("\x0").reject do |f|
21
+ f.match(%r{^(test|spec|features)/})
22
+ end
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+
28
+ # ruby
29
+ spec.required_ruby_version = '~> 2.0'
30
+
31
+ # dev/test dependencies
32
+ spec.add_development_dependency 'bundler', '~> 2.1'
33
+ spec.add_development_dependency 'rake', '~> 13.0'
34
+ spec.add_development_dependency 'rspec', '~> 3.9'
35
+
36
+ # stuff we use
37
+ spec.add_runtime_dependency 'rack', '~> 2.2'
38
+ spec.add_runtime_dependency 'commander', '~> 4.5'
39
+
40
+ # stuff i wrote
41
+ spec.add_runtime_dependency 'store-digest', '>= 0.1.0'
42
+ spec.add_runtime_dependency 'uri-ni', '>= 0.1.4'
43
+ spec.add_runtime_dependency 'xml-mixup', '>= 0.1.13'
44
+ end
metadata ADDED
@@ -0,0 +1,169 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: store-digest-http
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dorian Taylor
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-07-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.1'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '13.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '13.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.9'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.9'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rack
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.2'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.2'
69
+ - !ruby/object:Gem::Dependency
70
+ name: commander
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '4.5'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '4.5'
83
+ - !ruby/object:Gem::Dependency
84
+ name: store-digest
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: 0.1.0
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: 0.1.0
97
+ - !ruby/object:Gem::Dependency
98
+ name: uri-ni
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: 0.1.4
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: 0.1.4
111
+ - !ruby/object:Gem::Dependency
112
+ name: xml-mixup
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: 0.1.13
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: 0.1.13
125
+ description:
126
+ email:
127
+ - code@doriantaylor.com
128
+ executables:
129
+ - store-digest
130
+ extensions: []
131
+ extra_rdoc_files: []
132
+ files:
133
+ - ".gitignore"
134
+ - ".rspec"
135
+ - ".travis.yml"
136
+ - Gemfile
137
+ - LICENSE
138
+ - README.md
139
+ - Rakefile
140
+ - bin/console
141
+ - bin/setup
142
+ - exe/store-digest
143
+ - lib/store/digest/http.rb
144
+ - lib/store/digest/http/version.rb
145
+ - store-digest-http.gemspec
146
+ homepage: https://github.com/doriantaylor/rb-store-digest-http
147
+ licenses: []
148
+ metadata:
149
+ homepage_uri: https://github.com/doriantaylor/rb-store-digest-http
150
+ post_install_message:
151
+ rdoc_options: []
152
+ require_paths:
153
+ - lib
154
+ required_ruby_version: !ruby/object:Gem::Requirement
155
+ requirements:
156
+ - - "~>"
157
+ - !ruby/object:Gem::Version
158
+ version: '2.0'
159
+ required_rubygems_version: !ruby/object:Gem::Requirement
160
+ requirements:
161
+ - - ">="
162
+ - !ruby/object:Gem::Version
163
+ version: '0'
164
+ requirements: []
165
+ rubygems_version: 3.1.2
166
+ signing_key:
167
+ specification_version: 4
168
+ summary: HTTP front-end to Store::Digest
169
+ test_files: []