~singpolyma/dhall-ruby

ref: d2b7142409a9b71fc264fa584ef06eabc4b8ada2 dhall-ruby/lib/dhall/resolve.rb -rw-r--r-- 8.4 KiB
d2b71424Stephen Paul Weber Run all dhall-lang tests for normalization 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# frozen_string_literal: true

require "pathname"
require "promise.rb"
require "set"

require "dhall/ast"
require "dhall/binary"
require "dhall/util"

module Dhall
	class ImportFailedException < StandardError; end
	class ImportBannedException < ImportFailedException; end
	class ImportLoopException < ImportBannedException; end

	module Resolvers
		ReadPathSources = lambda do |sources|
			sources.map do |source|
				Promise.resolve(nil).then { source.pathname.binread }
			end
		end

		PreflightCORS = lambda do |source, parent_origin|
			uri = source.uri
			if parent_origin != "localhost" && parent_origin != source.origin
				req = Net::HTTP::Options.new(uri)
				req["Origin"] = parent_origin
				req["Access-Control-Request-Method"] = "GET"
				req["Access-Control-Request-Headers"] =
					source.headers.map { |h| h.fetch("header").to_s }.join(",")
				r = Net::HTTP.start(
					uri.hostname,
					uri.port,
					use_ssl: uri.scheme == "https"
				) { |http| http.request(req) }

				raise ImportFailedException, source if r.code != "200"
				unless r["Access-Control-Allow-Origin"] == parent_origin ||
				       r["Access-Control-Allow-Origin"] == "*"
					raise ImportBannedException, source
				end
			end
		end

		ReadHttpSources = lambda do |sources, parent_origin|
			sources.map do |source|
				Promise.resolve(nil).then do
					PreflightCORS.call(source, parent_origin)
					uri = source.uri
					req = Net::HTTP::Get.new(uri)
					source.headers.each do |header|
						req[header.fetch("header").to_s] = header.fetch("value").to_s
					end
					r = Net::HTTP.start(
						uri.hostname,
						uri.port,
						use_ssl: uri.scheme == "https"
					) { |http| http.request(req) }

					raise ImportFailedException, source if r.code != "200"
					r.body
				end
			end
		end

		RejectSources = lambda do |sources|
			sources.map do |source|
				Promise.new.reject(ImportBannedException.new(source))
			end
		end

		class ReadPathAndIPFSSources
			def initialize(
				path_reader: ReadPathSources,
				http_reader: ReadHttpSources,
				https_reader: http_reader,
				public_gateway: "cloudflare-ipfs.com"
			)
				@path_reader = path_reader
				@http_reader = http_reader
				@https_reader = https_reader
				@public_gateway = public_gateway
			end

			def arity
				1
			end

			def call(sources)
				@path_reader.call(sources).map.with_index do |promise, idx|
					source = sources[idx]
					if source.is_a?(Import::AbsolutePath) &&
					   ["ipfs", "ipns"].include?(source.path.first)
						gateway_fallback(source, promise)
					else
						promise
					end
				end
			end

			def to_proc
				method(:call).to_proc
			end

			protected

			def gateway_fallback(source, promise)
				promise.catch {
					@http_reader.call([
						source.to_uri(Import::Http, "localhost:8000")
					], "localhost").first
				}.catch do
					@https_reader.call([
						source.to_uri(Import::Https, @public_gateway)
					], "localhost").first
				end
			end
		end

		class ResolutionSet
			def initialize(reader)
				@reader = reader
				@parents = []
				@set = Hash.new { |h, k| h[k] = [] }
			end

			def register(source)
				p = Promise.new
				if @parents.include?(source)
					p.reject(ImportLoopException.new(source))
				else
					@set[source] << p
				end
				p
			end

			def resolutions
				sources, promises = @set.to_a.transpose
				[Array(sources), Array(promises)]
			end

			def reader
				lambda do |sources|
					if @reader.arity == 2
						@reader.call(sources, @parents.last&.origin || "localhost")
					else
						@reader.call(sources)
					end
				end
			end

			def child(parent_source)
				dup.tap do |c|
					c.instance_eval do
						@parents = @parents.dup + [parent_source]
						@set = Hash.new { |h, k| h[k] = [] }
					end
				end
			end
		end

		class Standard
			def initialize(
				path_reader: ReadPathSources,
				http_reader: ReadHttpSources,
				https_reader: http_reader
			)
				@path_resolutions = ResolutionSet.new(path_reader)
				@http_resolutions = ResolutionSet.new(http_reader)
				@https_resolutions = ResolutionSet.new(https_reader)
				@cache = {}
			end

			def cache_fetch(key, &fallback)
				@cache.fetch(key) do
					Promise.resolve(nil).then(&fallback).then do |result|
						@cache[key] = result
					end
				end
			end

			def resolve_path(path_source)
				@path_resolutions.register(path_source)
			end

			def resolve_http(http_source)
				http_source.headers.resolve(
					resolver:    self,
					relative_to: Dhall::Import::RelativePath.new
				).then do |headers|
					@http_resolutions.register(
						http_source.with(headers: headers.normalize)
					)
				end
			end

			def resolve_https(https_source)
				https_source.headers.resolve(
					resolver:    self,
					relative_to: Dhall::Import::RelativePath.new
				).then do |headers|
					@https_resolutions.register(
						https_source.with(headers: headers.normalize)
					)
				end
			end

			def finish!
				[
					@path_resolutions,
					@http_resolutions,
					@https_resolutions
				].each do |rset|
					Util.match_result_promises(*rset.resolutions, &rset.reader)
				end
				freeze
			end

			def child(parent_source)
				dup.tap do |c|
					c.instance_eval do
						@path_resolutions = @path_resolutions.child(parent_source)
						@http_resolutions = @http_resolutions.child(parent_source)
						@https_resolutions = @https_resolutions.child(parent_source)
					end
				end
			end
		end

		class Default < Standard
			def initialize(
				path_reader: ReadPathSources,
				http_reader: ReadHttpSources,
				https_reader: http_reader,
				ipfs_public_gateway: "cloudflare-ipfs.com"
			)
				super(
					path_reader:  ReadPathAndIPFSSources.new(
						path_reader:    path_reader,
						http_reader:    http_reader,
						https_reader:   https_reader,
						public_gateway: ipfs_public_gateway
					),
					http_reader:  http_reader,
					https_reader: https_reader
				)
			end
		end

		class LocalOnly < Standard
			def initialize(path_reader: ReadPathSources)
				super(
					path_reader:  path_reader,
					http_reader:  RejectSources,
					https_reader: RejectSources
				)
			end
		end

		class None < Default
			def initialize
				super(
					path_reader:  RejectSources,
					http_reader:  RejectSources,
					https_reader: RejectSources
				)
			end
		end
	end

	class ExpressionResolver
		@@registry = {}

		def self.for(expr)
			@@registry.find { |k, _| k === expr }.last.new(expr)
		end

		def self.register_for(kase)
			@@registry[kase] = self
		end

		def initialize(expr)
			@expr = expr
		end

		def resolve(**kwargs)
			Util.promise_all_hash(
				@expr.to_h.each_with_object({}) { |(attr, value), h|
					h[attr] = ExpressionResolver.for(value).resolve(**kwargs)
				}
			).then { |h| @expr.with(h) }
		end

		class ImportResolver < ExpressionResolver
			register_for Import

			def resolve(resolver:, relative_to:)
				Promise.resolve(nil).then do
					resolver.cache_fetch(@expr.cache_key(relative_to)) do
						resolve_raw(resolver: resolver, relative_to: relative_to)
					end
				end
			end

			def resolve_raw(resolver:, relative_to:)
				real_path = @expr.real_path(relative_to)
				real_path.resolve(resolver).then do |result|
					@expr.parse_and_check(result).resolve(
						resolver:    resolver.child(real_path),
						relative_to: real_path
					)
				end
			end
		end

		class FallbackResolver < ExpressionResolver
			register_for Operator::ImportFallback

			def resolve(**kwargs)
				ExpressionResolver.for(@expr.lhs).resolve(**kwargs).catch do
					ExpressionResolver.for(@expr.rhs).resolve(**kwargs)
				end
			end
		end

		class ArrayResolver < ExpressionResolver
			register_for Util::ArrayOf.new(Expression)

			def resolve(**kwargs)
				Promise.all(
					@expr.map { |e| ExpressionResolver.for(e).resolve(**kwargs) }
				)
			end
		end

		class HashResolver < ExpressionResolver
			register_for Util::HashOf.new(
				ValueSemantics::Anything,
				ValueSemantics::Either.new([Expression, nil])
			)

			def resolve(**kwargs)
				Util.promise_all_hash(Hash[@expr.map do |k, v|
					[k, ExpressionResolver.for(v).resolve(**kwargs)]
				end])
			end
		end

		register_for Expression

		class IdentityResolver < ExpressionResolver
			register_for Object

			def resolve(*)
				Promise.resolve(@expr)
			end
		end
	end

	class Expression
		def resolve(
			resolver: Resolvers::Default.new,
			relative_to: Import::Path.from_string(Pathname.pwd + "file")
		)
			p = ExpressionResolver.for(self).resolve(
				resolver:    resolver,
				relative_to: relative_to
			)
			resolver.finish!
			p
		end
	end
end