delta-qa-vision 0.0.1.beta2

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.
@@ -0,0 +1,668 @@
1
+ require "base64"
2
+ require "digest"
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "securerandom"
7
+ require "uri"
8
+ require_relative "errors"
9
+
10
+ module DeltaQa
11
+ module Vision
12
+ # The relay: the steps every Vision SDK plays, in the same order — those of src/core/ of the JavaScript SDK.
13
+ #
14
+ # The page is taken by the capture script of Delta-QA, which the gem carries as its build compiled it;
15
+ # the relay evaluates its functions, sends the commands of Chromium's protocol they need, reads outside the page
16
+ # what the page cannot read, and talks to the gate. It writes no rule of a page.
17
+ module Relay
18
+ API = "DeltaQaCapture".freeze
19
+ SCRIPT_PATH = File.join(__dir__, "delta-qa-capture.js")
20
+
21
+ PageFunction = Struct.new(:params, :body)
22
+ Size = Struct.new(:width, :height) do
23
+ def to_s
24
+ "#{width}x#{height}"
25
+ end
26
+ end
27
+ PageDocument = Struct.new(:url, :depth, :handle)
28
+ PageSnapshot = Struct.new(:url, :title, :html, :engine_styles, :unreadable_canvases)
29
+ ReadResource = Struct.new(:url, :status, :content_type, :data, :sha256)
30
+ Answered = Struct.new(:url, :final_url, :status, :content_type_header, :data)
31
+ TakenPage = Struct.new(:snapshot, :resources, :unreachable, :zones)
32
+ SentCheck = Struct.new(:size, :step, :unreadable_canvases, :unreachable_resources)
33
+ LaunchResult = Struct.new(:size, :launch_id, :result, :is_new, :comparison_url)
34
+
35
+ module_function
36
+
37
+ # The capture script, read from the gem at the first call.
38
+ def capture_script
39
+ @capture_script ||= begin
40
+ unless File.exist?(SCRIPT_PATH)
41
+ raise "The capture script is not in the gem: run scripts/copy_capture.rb"
42
+ end
43
+ read = File.read(SCRIPT_PATH, encoding: "UTF-8")
44
+ raise "delta-qa-capture.js is not the capture script: it declares no DeltaQaCapture" unless read.include?(API)
45
+ read
46
+ end
47
+ end
48
+
49
+ def capture(name)
50
+ PageFunction.new(["args"], "#{capture_script}\nreturn #{API}.#{name}.apply(null, args);")
51
+ end
52
+
53
+ def capture_on(name)
54
+ PageFunction.new(%w[element args], "#{capture_script}\nreturn #{API}.#{name}.apply(null, [element].concat(args));")
55
+ end
56
+
57
+ def lost_drawings_declaration
58
+ "function (...contexts) {\n#{capture_script}\nreturn #{API}.lostDrawings(contexts);\n}"
59
+ end
60
+
61
+ # --- The page ---------------------------------------------------------------------------------------------
62
+
63
+ def top_of(documents)
64
+ raise "The adapter listed no top document first: the page has none to take" if documents.empty? || documents[0].depth != 0
65
+ documents[0]
66
+ end
67
+
68
+ HELD_CONTEXTS = "delta-qa-vision-held-contexts"
69
+
70
+ def take_snapshot(driver)
71
+ session = driver.open_cdp
72
+ begin
73
+ take(driver, session, held_contexts(session))
74
+ ensure
75
+ begin
76
+ # The contexts listed stay held by the page's protocol until their group is released: closing the session
77
+ # releases nothing where the adapter shares the page's own session.
78
+ session.send("Runtime.releaseObjectGroup", { "objectGroup" => HELD_CONTEXTS })
79
+ ensure
80
+ session.close
81
+ end
82
+ end
83
+ end
84
+
85
+ # Takes the page, the notes erased from every document on every path — those of a pass that failed halfway included.
86
+ def take(driver, session, contexts)
87
+ snapshot = begin
88
+ refused = in_every_document(driver, "note").flat_map { |result| result || [] }
89
+ documents = driver.documents
90
+ top = top_of(documents)
91
+ unreadable = refused + lost_drawings(session, contexts)
92
+ read = []
93
+ marked = []
94
+ begin
95
+ read_frames(driver, documents, read, marked)
96
+ url = driver.url
97
+ title = driver.title
98
+ html = driver.evaluate(top, capture("serialize"), [read])
99
+ ensure
100
+ unmark(driver, marked)
101
+ end
102
+ engine_styles = driver.evaluate(top, capture("engineStyles"), [])
103
+ PageSnapshot.new(url, title, html, engine_styles, unreadable)
104
+ rescue Exception => e # rubocop:disable Lint/RescueException -- erased on every path, then raised again
105
+ erase_notes_after(driver, e)
106
+ raise
107
+ end
108
+ in_every_document(driver, "eraseNotes")
109
+ snapshot
110
+ end
111
+
112
+ # Erases the notes once the take failed: the failure of the take stays the one raised, the erase's is warned.
113
+ def erase_notes_after(driver, failure)
114
+ in_every_document(driver, "eraseNotes")
115
+ rescue StandardError => e # warned beside the failure raised, never dropped
116
+ warn("Delta-QA Vision: erasing the notes of the page also failed, after #{failure.class}: #{e.class}: #{e.message}")
117
+ end
118
+
119
+ # Takes the mark off every frame marked, then lets its tag go, even when one refuses: the first failure is raised.
120
+ def unmark(driver, marked)
121
+ failure = nil
122
+ marked.each do |element|
123
+ begin
124
+ driver.evaluate_on(element, capture_on("unmarkFrame"), [])
125
+ rescue StandardError => e # the tag left the page with its document: it carries no mark the page shows
126
+ raise unless driver.page_changing?(e)
127
+ ensure
128
+ let_go(driver, element)
129
+ end
130
+ rescue StandardError => e # every frame is unmarked before the first failure is raised
131
+ failure ||= e
132
+ end
133
+ raise failure unless failure.nil?
134
+ end
135
+
136
+ # Lets a frame tag held go; a handle that died with its document has nothing left to let go.
137
+ def let_go(driver, element)
138
+ driver.release(element)
139
+ rescue StandardError => e # a handle of a document the page replaced is gone with it
140
+ raise unless driver.page_changing?(e)
141
+ end
142
+
143
+ def held_contexts(session)
144
+ canvas = session.send("Runtime.evaluate", { "expression" => "document.querySelector('canvas') !== null", "returnByValue" => true })["result"]
145
+ return [] unless canvas["value"] == true
146
+ %w[WebGLRenderingContext WebGL2RenderingContext].filter_map do |kind|
147
+ prototype = session.send("Runtime.evaluate", { "expression" => "globalThis.#{kind}?.prototype", "objectGroup" => HELD_CONTEXTS })["result"]["objectId"]
148
+ session.send("Runtime.queryObjects", { "prototypeObjectId" => prototype, "objectGroup" => HELD_CONTEXTS })["objects"]["objectId"] unless prototype.nil?
149
+ end
150
+ end
151
+
152
+ def lost_drawings(session, lists)
153
+ return [] if lists.empty?
154
+ named = session.send("Runtime.callFunctionOn", { "objectId" => lists[0], "functionDeclaration" => lost_drawings_declaration,
155
+ "arguments" => lists.map { |one| { "objectId" => one } }, "returnByValue" => true })
156
+ raise "The page refused to name its lost WebGL drawings: #{named["exceptionDetails"]}" unless named["exceptionDetails"].nil?
157
+ named["result"]["value"] || []
158
+ end
159
+
160
+ def in_every_document(driver, name)
161
+ documents = driver.documents
162
+ results = [driver.evaluate(top_of(documents), capture(name), name == "note" ? [true] : [])]
163
+ documents.drop(1).each do |document|
164
+ results << driver.evaluate(document, capture(name), [])
165
+ rescue StandardError => e # a frame the page is changing (navigating, removed) is left out of the check
166
+ raise unless driver.page_changing?(e)
167
+ end
168
+ results
169
+ end
170
+
171
+ # Reads every frame, the deepest first, and marks its live tag, held in marked until unmark lets it go; the tag of a
172
+ # frame not marked is let go at once.
173
+ def read_frames(driver, documents, read, marked)
174
+ documents.select { |d| d.depth.positive? }.sort_by { |d| -d.depth }.each do |frame|
175
+ element = nil
176
+ kept = false
177
+ begin
178
+ element = driver.host_of(frame)
179
+ html = driver.evaluate(frame, capture("serialize"), [[]])
180
+ next if html == ""
181
+ mark = SecureRandom.uuid
182
+ # An ATTRIBUTE navigates nothing — a srcdoc on the live frame would destroy its widget.
183
+ driver.evaluate_on(element, capture_on("markFrame"), [mark])
184
+ marked << element
185
+ kept = true
186
+ read << { "mark" => mark, "html" => html, "url" => frame.url }
187
+ rescue StandardError => e # a frame the page is changing (navigating, removed) is left out of the check
188
+ raise unless driver.page_changing?(e)
189
+ ensure
190
+ let_go(driver, element) unless element.nil? || kept
191
+ end
192
+ end
193
+ end
194
+
195
+ # --- The environment ----------------------------------------------------------------------------------------
196
+
197
+ def environment_of(driver)
198
+ driver.evaluate(top_of(driver.documents), capture("environment"), [])
199
+ end
200
+
201
+ def require_chromium(driver)
202
+ chromium, name = driver.browser
203
+ raise UnsupportedBrowserError, name unless chromium
204
+ end
205
+
206
+ def read_environment(driver)
207
+ require_chromium(driver)
208
+ read = environment_of(driver)
209
+ raise UnsupportedDensityError, read["devicePixelRatio"] unless read["devicePixelRatio"] == 1
210
+ unless read["width"].positive? && read["height"].positive? && read["language"] && !read["language"].empty? && read["timezone"] &&
211
+ !read["timezone"].empty?
212
+ raise "The browser of the test gives no environment to open a launch in: #{read}"
213
+ end
214
+ { "browser" => "CHROMIUM", "width" => read["width"].to_i, "height" => read["height"].to_i, "language" => read["language"],
215
+ "timezone" => read["timezone"], "colorScheme" => read["dark"] ? "DARK" : "LIGHT" }
216
+ end
217
+
218
+ def require_page(driver)
219
+ require_chromium(driver)
220
+ density = environment_of(driver)["devicePixelRatio"]
221
+ raise UnsupportedDensityError, density unless density == 1
222
+ end
223
+
224
+ # --- The zones ----------------------------------------------------------------------------------------------
225
+
226
+ MAX_ZONES = 100
227
+
228
+ def designate_zones(driver, ignore, check, size)
229
+ zones = { "ignore" => designate(driver, "ignore", ignore, size), "check" => designate(driver, "check", check, size) }
230
+ .reject { |_, found| found.empty? }
231
+ zones.empty? ? nil : zones
232
+ end
233
+
234
+ def designate(driver, kind, designated, size)
235
+ zones = designated.flat_map do |zone|
236
+ described, sets = driver.zone_selector_sets(zone, kind, capture("selectorSets"))
237
+ raise ZoneNotFoundError.new(kind, described, size&.to_s) if sets.empty?
238
+ sets.map do |selector_set|
239
+ raise TypeError, "The zone to #{kind} #{described} designates an element of a frame: a zone is an element of the page itself" if selector_set.nil?
240
+ { "selectorSet" => selector_set }
241
+ end
242
+ end
243
+ raise ArgumentError, "The zones to #{kind} designate #{zones.size} elements, more than the #{MAX_ZONES} Delta-QA admits in a check" if zones.size > MAX_ZONES
244
+ zones
245
+ end
246
+
247
+ # --- The resources ------------------------------------------------------------------------------------------
248
+
249
+ UNTYPED_BYTES = "application/octet-stream".freeze
250
+ ANIMATED_IMAGE_MESSAGE_TYPE = "image/svg+xml".freeze
251
+ MAX_RESOURCE_BYTES = 31_457_280
252
+ MAX_RESOURCES = 10_000
253
+ COPIED = %w[Image Font].freeze
254
+ NO_COPY = ["Content unavailable", "No resource with given URL found"].freeze
255
+ REDIRECTIONS = [301, 302, 303, 307, 308].freeze
256
+ MAX_REDIRECTIONS = 20
257
+ OUTSIDE_TIMEOUT_S = 30
258
+ UNREACHABLE = Object.new.freeze
259
+ # The types the browser used, by page, as read at its checks: a later check finds the type of a copy the browser no longer lists.
260
+ # Weak by its keys only: the table of a page lives as long as its driver.
261
+ TYPES_SEEN = ObjectSpace::WeakKeyMap.new
262
+
263
+ # The SHA-256 of bytes, lowercase hexadecimal — the form the gate compares.
264
+ def sha256_hex(data)
265
+ Digest::SHA256.hexdigest(data)
266
+ end
267
+
268
+ # The browser's own copies of the page's images and fonts, read by Chromium's protocol.
269
+ class BrowserView
270
+ attr_reader :session, :types
271
+
272
+ def initialize(driver)
273
+ @driver = driver
274
+ @session = driver.open_cdp
275
+ @types = (TYPES_SEEN[driver] ||= {})
276
+ @held = {}
277
+ @received = false
278
+ @enabled = false
279
+ begin
280
+ walk(@session.send("Page.getResourceTree", {})["frameTree"])
281
+ rescue StandardError # the session is closed, then the failure raised
282
+ @session.close
283
+ raise
284
+ end
285
+ end
286
+
287
+ def close
288
+ @session.close
289
+ end
290
+
291
+ def copy_of(url)
292
+ where = @held[url]
293
+ return nil if where.nil?
294
+ unless @received
295
+ Relay.documents_received(@driver, url)
296
+ @received = true
297
+ end
298
+ begin
299
+ unless @enabled
300
+ # Never disabled after: where the session is the driver's own (ChromeDriver, Ferrum), disabling the Page domain would break the driver.
301
+ @session.send("Page.enable", {})
302
+ @enabled = true
303
+ end
304
+ content = @session.send("Page.getResourceContent", where)
305
+ rescue StandardError => e # the protocol's refusal is read: no copy, or a named failure
306
+ return nil if NO_COPY.any? { |marker| e.message.include?(marker) }
307
+ raise ResourceUnreadableError.new(url, "the browser's copy could not be read — #{e.message}")
308
+ end
309
+ raise ResourceUnreadableError.new(url, "the browser gave its copy as text, not as the bytes it received") unless content["base64Encoded"]
310
+ Base64.strict_decode64(content["content"])
311
+ end
312
+
313
+ private
314
+
315
+ def walk(tree)
316
+ frame_id = tree["frame"]["id"]
317
+ (tree["resources"] || []).each do |resource|
318
+ address = resource["url"].split("#", 2)[0]
319
+ kind = Relay.base_type(resource["mimeType"] || "")
320
+ @types[address] = kind unless kind.empty?
321
+ if COPIED.include?(resource["type"]) && !resource["failed"] && !resource["canceled"] && !@held.key?(address)
322
+ @held[address] = { "frameId" => frame_id, "url" => resource["url"] }
323
+ end
324
+ end
325
+ (tree["childFrames"] || []).each { |child| walk(child) }
326
+ end
327
+ end
328
+
329
+ def documents_received(driver, url)
330
+ driver.documents.each do |document|
331
+ driver.document_received(document)
332
+ rescue DocumentStillReceivingError => e
333
+ raise ResourceUnreadableError.new(url, "the browser gives its copy once every document of the page is received, and the frame " \
334
+ "#{e.document_url} was still receiving its document at the page load timeout — #{e.message}")
335
+ rescue StandardError => e # a document leaving the page is not waited for
336
+ raise unless driver.page_changing?(e)
337
+ end
338
+ end
339
+
340
+ def read_resources(driver, engine_styles)
341
+ read = {}
342
+ tried = {}
343
+ unreachable = []
344
+ browser = BrowserView.new(driver)
345
+ top = begin
346
+ read_documents(driver, engine_styles, browser, read, tried, unreachable)
347
+ ensure
348
+ browser.close
349
+ end
350
+ [frozen(driver, top, read.values), unreachable]
351
+ end
352
+
353
+ # Reads what every document cites into read, and gives the top document.
354
+ def read_documents(driver, engine_styles, browser, read, tried, unreachable)
355
+ documents = driver.documents
356
+ top = top_of(documents)
357
+ user_agent = environment_of(driver)["userAgent"]
358
+ documents.each do |document|
359
+ cited = driver.evaluate(document, capture("cited"), [document.depth.zero? ? engine_styles : ""])
360
+ following = cited["urls"]
361
+ until following.empty?
362
+ fresh = following.uniq.reject { |url| tried.key?(url) }
363
+ fresh.each { |url| tried[url] = true }
364
+ answered, missed = read_all(driver, document, cited, fresh, browser, user_agent)
365
+ unreachable.concat(missed)
366
+ sheets = []
367
+ answered.each do |answer|
368
+ content_type = typed(answer, browser.types)
369
+ if content_type == "text/css"
370
+ sheets << { "base64" => Base64.strict_encode64(answer.data), "contentType" => answer.content_type_header, "url" => answer.final_url }
371
+ end
372
+ read[answer.url] = [answer, content_type]
373
+ end
374
+ following = sheets.empty? ? [] : driver.evaluate(top, capture("sheetsCited"), [sheets]).flatten(1)
375
+ end
376
+ rescue StandardError => e # a document the page is changing is left, as the snapshot leaves it
377
+ raise unless driver.page_changing?(e)
378
+ end
379
+ top
380
+ end
381
+
382
+ def frozen(driver, top, read)
383
+ head = driver.evaluate(top, capture("headBytes"), [])
384
+ may = read.empty? ? [] : driver.evaluate(top, capture("mayBeAnimated"), [read.map { |answer, _| Base64.strict_encode64(answer.data.byteslice(0, head)) }])
385
+ candidates = may.each_index.select { |index| may[index] == true }
386
+ stills = candidates.empty? ? [] : driver.evaluate(top, capture("stills"), [candidates.map { |index| Base64.strict_encode64(read[index][0].data) }])
387
+ still_of = candidates.zip(stills).select { |_, svg| svg.is_a?(String) }.to_h
388
+ read.each_with_index.map do |(answer, content_type), index|
389
+ svg = still_of[index]
390
+ data = svg.nil? ? answer.data : svg.b
391
+ ReadResource.new(answer.url, answer.status, svg.nil? ? content_type : ANIMATED_IMAGE_MESSAGE_TYPE, data, sha256_hex(data))
392
+ end
393
+ end
394
+
395
+ def typed(answer, types)
396
+ from_site = base_type(answer.content_type_header)
397
+ return from_site unless from_site.empty?
398
+ types[answer.url] || types[answer.final_url]
399
+ end
400
+
401
+ def base_type(header)
402
+ header.split(";", 2)[0].to_s.strip.downcase
403
+ end
404
+
405
+ def origin_of(url)
406
+ parsed = URI.parse(url)
407
+ default = parsed.port.nil? || parsed.port == parsed.default_port
408
+ "#{parsed.scheme}://#{parsed.host}#{default ? "" : ":#{parsed.port}"}"
409
+ end
410
+
411
+ def read_all(driver, document, cited, urls, browser, user_agent)
412
+ read = []
413
+ read_again = []
414
+ urls.each do |url|
415
+ data = browser.copy_of(url)
416
+ if data.nil?
417
+ read_again << url
418
+ else
419
+ add(read, kept(url, url, 200, "", data))
420
+ end
421
+ end
422
+ own, by_request = read_again.partition { |url| origin_of(url) == cited["origin"] }
423
+ (own.empty? ? [] : driver.evaluate(document, capture("readInPage"), [own])).each do |answer|
424
+ raise ResourceUnreadableError.new(answer["url"], "the page's fetch failed — #{answer["failure"]}") if answer.key?("failure")
425
+ if answer.key?("refused") || answer.key?("redirected")
426
+ # Refused by the page (its Content Security Policy, or the network), or redirected: read outside the page.
427
+ by_request << answer["url"]
428
+ next
429
+ end
430
+ add(read, kept(answer["url"], answer["url"], answer["status"].to_i, answer["contentType"], Base64.strict_decode64(answer["base64"])))
431
+ end
432
+ unreachable = []
433
+ by_request.each do |url|
434
+ answer = read_outside(browser.session, user_agent, url, cited["url"])
435
+ if answer.equal?(UNREACHABLE)
436
+ unreachable << url
437
+ else
438
+ add(read, answer)
439
+ end
440
+ end
441
+ [read, unreachable]
442
+ end
443
+
444
+ # Reads an address outside the page as the browser would ask for it: its cookies, its user agent, the Referer of its policy.
445
+ def read_outside(session, user_agent, url, referrer)
446
+ address = url
447
+ raise ResourceUnreadableError.new(url, "only an http(s) address is read outside the page") unless http?(address)
448
+ (MAX_REDIRECTIONS + 1).times do
449
+ uri = URI.parse(address)
450
+ request = Net::HTTP::Get.new(uri.request_uri, { "User-Agent" => user_agent })
451
+ cookie = cookie_header(session, address)
452
+ request["Cookie"] = cookie unless cookie.empty?
453
+ referer = referer_of(referrer, address)
454
+ request["Referer"] = referer unless referer.nil?
455
+ begin
456
+ response, body = get(uri, request, url)
457
+ rescue SocketError, SystemCallError, OpenSSL::SSL::SSLError
458
+ return UNREACHABLE
459
+ rescue Late, Timeout::Error
460
+ raise ResourceUnreadableError.new(url, "the SDK's request failed — no whole answer within #{OUTSIDE_TIMEOUT_S * 1000} ms")
461
+ rescue IOError => e
462
+ raise ResourceUnreadableError.new(url, "the SDK's request failed — #{e.message}")
463
+ end
464
+ status = response.code.to_i
465
+ location = response["location"]
466
+ if REDIRECTIONS.include?(status) && !location.nil?
467
+ address = URI.join(address, location).to_s
468
+ raise ResourceUnreadableError.new(url, "redirected outside http(s), to #{address}") unless http?(address)
469
+ next
470
+ end
471
+ return kept(url, address, status, response["content-type"] || "", body)
472
+ end
473
+ raise ResourceUnreadableError.new(url, "more than #{MAX_REDIRECTIONS} redirections, the last to #{address}")
474
+ end
475
+
476
+ # The whole answer of an address did not come within the deadline of its read.
477
+ class Late < StandardError; end
478
+
479
+ # One GET, never redirected: its response and its body. The body is read in chunks, cut beyond the size Delta-QA
480
+ # admits; the whole exchange, from the connection to the last byte, is bounded by one deadline.
481
+ def get(uri, request, url)
482
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + OUTSIDE_TIMEOUT_S
483
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: OUTSIDE_TIMEOUT_S,
484
+ read_timeout: OUTSIDE_TIMEOUT_S) do |http|
485
+ http.read_timeout = remaining(deadline)
486
+ http.request(request) do |response|
487
+ declared = response.content_length
488
+ raise ResourceTooLargeError.new(url, declared, MAX_RESOURCE_BYTES) if !declared.nil? && declared > MAX_RESOURCE_BYTES
489
+ body = "".b
490
+ response.read_body do |chunk|
491
+ body << chunk.b
492
+ raise ResourceTooLargeError.new(url, body.bytesize, MAX_RESOURCE_BYTES) if body.bytesize > MAX_RESOURCE_BYTES
493
+ # Each read waits only the time left.
494
+ http.read_timeout = remaining(deadline)
495
+ end
496
+ return [response, body]
497
+ end
498
+ end
499
+ end
500
+
501
+ def remaining(deadline)
502
+ left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
503
+ raise Late unless left.positive?
504
+ left
505
+ end
506
+
507
+ def http?(address)
508
+ %w[http https].include?(URI.parse(address).scheme)
509
+ end
510
+
511
+ # The Cookie header the browser would send: its cookies for the address, the longest path first (RFC 6265 § 5.4), then by name.
512
+ def cookie_header(session, address)
513
+ cookies = session.send("Network.getCookies", { "urls" => [address] })["cookies"]
514
+ cookies.sort_by { |c| [-(c["path"] || "").length, c["name"] || ""] }
515
+ .map { |c| c["name"] == "" ? c["value"] : "#{c["name"]}=#{c["value"]}" }.join("; ")
516
+ end
517
+
518
+ # The Referer of the browser's default policy (strict-origin-when-cross-origin).
519
+ def referer_of(document_url, target)
520
+ source = URI.parse(document_url)
521
+ return nil unless %w[http https].include?(source.scheme)
522
+ return nil if source.scheme == "https" && URI.parse(target).scheme == "http"
523
+ return document_url.split("#", 2)[0] if origin_of(document_url) == origin_of(target)
524
+ "#{origin_of(document_url)}/"
525
+ end
526
+
527
+ def kept(url, final_url, status, content_type_header, data)
528
+ return nil if status < 200 || status >= 300 || data.empty?
529
+ Answered.new(url, final_url, status, content_type_header, data)
530
+ end
531
+
532
+ def add(read, answer)
533
+ read << answer unless answer.nil?
534
+ end
535
+
536
+ def send_missing(gate, resources)
537
+ return 0 if resources.empty?
538
+ raise ArgumentError, "The page cites #{resources.size} resources, more than the #{MAX_RESOURCES} a check admits" if resources.size > MAX_RESOURCES
539
+ by_hash = {}
540
+ resources.each do |resource|
541
+ raise ResourceTooLargeError.new(resource.url, resource.data.bytesize, MAX_RESOURCE_BYTES) if resource.data.bytesize > MAX_RESOURCE_BYTES
542
+ by_hash[resource.sha256] ||= resource
543
+ end
544
+ missing = gate.declare_resources(by_hash.keys)
545
+ missing.each do |digest|
546
+ resource = by_hash.fetch(digest)
547
+ gate.send_resource(digest, resource.content_type || UNTYPED_BYTES, resource.data, resource.url)
548
+ end
549
+ missing.size
550
+ end
551
+
552
+ def cited_entry(resource)
553
+ entry = { "url" => resource.url, "method" => "GET", "requestBodyHash" => "", "status" => resource.status }
554
+ entry["contentType"] = resource.content_type unless resource.content_type.nil?
555
+ entry["sha256"] = resource.sha256
556
+ entry
557
+ end
558
+
559
+ # --- The launches -------------------------------------------------------------------------------------------
560
+
561
+ RESULT_TIMEOUT_S = 15 * 60
562
+ POLL_INTERVAL_S = 2
563
+
564
+ def take_page(driver, ignore, check, size)
565
+ require_page(driver)
566
+ zones = designate_zones(driver, ignore, check, size)
567
+ snapshot = take_snapshot(driver)
568
+ resources, unreachable = read_resources(driver, snapshot.engine_styles)
569
+ TakenPage.new(snapshot, resources, unreachable, zones)
570
+ end
571
+
572
+ def commit_url(result, commit)
573
+ suffix = "/comparisons/#{result.launch_id}"
574
+ unless result.comparison_url.end_with?(suffix)
575
+ raise "Delta-QA gave launch #{result.launch_id} the comparison address #{result.comparison_url}, not <app>#{suffix}: " \
576
+ "the SDK cannot compose the link of commit #{commit}"
577
+ end
578
+ "#{result.comparison_url.delete_suffix(suffix)}/ci/commit/#{URI.encode_www_form_component(commit).gsub("+", "%20")}"
579
+ end
580
+
581
+ def require_sizes(sizes)
582
+ raise ArgumentError, "sizes is empty: declare at least one size, or leave sizes out to take the page at its own size" if sizes.empty?
583
+ seen = {}
584
+ sizes.each do |size|
585
+ raise ArgumentError, "A size is two whole numbers of CSS points above 0, got #{size}" unless size.width.positive? && size.height.positive?
586
+ raise ArgumentError, "The size #{size} is declared twice: each size is one launch" if seen.key?(size)
587
+ seen[size] = true
588
+ end
589
+ end
590
+
591
+ # The launches of a Vision test: one per size, the page at its own size when none is declared.
592
+ class Launches
593
+ def self.open(gate, driver, request, sizes)
594
+ Relay.require_sizes(sizes) unless sizes.nil?
595
+ environment = Relay.read_environment(driver)
596
+ sent = request.dup
597
+ sent.delete("baseBranch") if sent["baseBranch"].nil? || sent["baseBranch"] == sent["branch"]
598
+ launches = (sizes || [Size.new(environment["width"], environment["height"])]).map do |size|
599
+ opening = sent.merge("environment" => environment.merge("width" => size.width, "height" => size.height))
600
+ [size, gate.open_launch(opening)["launchId"]]
601
+ end
602
+ new(gate, launches, !sizes.nil?)
603
+ end
604
+
605
+ def initialize(gate, launches, resizes)
606
+ @gate = gate
607
+ @launches = launches
608
+ @resizes = resizes
609
+ end
610
+
611
+ def check(driver, name, ignore, check)
612
+ if @resizes
613
+ before = driver.viewport
614
+ taken = []
615
+ begin
616
+ @launches.each do |size, _|
617
+ driver.resize(size)
618
+ taken << Relay.take_page(driver, ignore, check, size)
619
+ end
620
+ ensure
621
+ driver.resize(before)
622
+ end
623
+ else
624
+ taken = [Relay.take_page(driver, ignore, check, nil)]
625
+ end
626
+ unique = {}
627
+ taken.each { |page| page.resources.each { |resource| unique[resource.sha256] ||= resource } }
628
+ Relay.send_missing(@gate, unique.values)
629
+ @launches.zip(taken).map do |(size, launch_id), page|
630
+ request = { "name" => name, "url" => page.snapshot.url, "title" => page.snapshot.title, "html" => page.snapshot.html,
631
+ "engineStyles" => page.snapshot.engine_styles, "resources" => page.resources.map { |r| Relay.cited_entry(r) } }
632
+ request["zones"] = page.zones unless page.zones.nil?
633
+ added = @gate.add_check(launch_id, request)
634
+ SentCheck.new(size, added["step"].to_i, page.snapshot.unreadable_canvases, page.unreachable)
635
+ end
636
+ end
637
+
638
+ def close
639
+ @launches.each do |_, launch_id|
640
+ @gate.close_launch(launch_id)
641
+ rescue ApiError => e
642
+ raise unless e.code == "LAUNCH_CLOSED"
643
+ # Already closed by Delta-QA: its result is read the same way.
644
+ end
645
+ @launches.map do |size, launch_id|
646
+ read = wait_for_result(launch_id)
647
+ LaunchResult.new(size, launch_id, read["result"], read["isNew"] == true, read["comparisonUrl"])
648
+ end
649
+ end
650
+
651
+ private
652
+
653
+ def wait_for_result(launch_id)
654
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + RESULT_TIMEOUT_S
655
+ last = nil
656
+ loop do
657
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
658
+ raise LaunchResultTimeoutError.new(launch_id, RESULT_TIMEOUT_S, last) if remaining <= 0
659
+ read = @gate.read_launch(launch_id, remaining)
660
+ last = read["result"]
661
+ return read unless last == "RUNNING"
662
+ sleep([POLL_INTERVAL_S, [deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max].min)
663
+ end
664
+ end
665
+ end
666
+ end
667
+ end
668
+ end