tungsten-runtime 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7c60518f52962a9bcf62ad89dd0be554d64d52e768ff886a19946851a7193c50
4
+ data.tar.gz: 5bec47c402cb907e48047375a8b69d0d976b406a80658169c676b705719fff58
5
+ SHA512:
6
+ metadata.gz: 9ffb9d1e620fe26036fc6374c3688540645311bc7c9bbaa4a1a18609001d8ac15e1bd25592d9789c8fec49d08fcc4f764f01db50eab709cb955d31a3aa7c0372
7
+ data.tar.gz: 2600a2effe2c9e7a1595e563ff4009bdccf7f8e279b2ed7f6b4c38ec8d5dc582846487e755ab97266d032a463742f79b0714cd671a99ed16577090999cda7d81
data/LICENSE ADDED
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
data/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # tungsten-runtime 0.1.2
2
+
3
+ The runtime used by the Ruby SDKs generated by [tungsten](https://github.com/pboachie/tungsten).
4
+ It provides pre-flight validation, authentication, idempotency, confirmation,
5
+ retries, diagnostic error envelopes, previews, pagination, macros and server-sent event streams.
6
+
7
+ Requires Ruby 3.3 or newer and the base64 gem (~> 0.2). Licensed under Apache-2.0.
8
+
9
+ The implementation is unchanged from the released `v0.1.2` source. The gemspec
10
+ sets this package version to 0.1.2; the stable internal runtime/header version
11
+ remains 0.1.0.
12
+
13
+ To pin the package with the released tungsten 0.1.2 compiler:
14
+
15
+ ```yaml
16
+ targets:
17
+ ruby:
18
+ out: sdk-ruby
19
+ runtime: "= 0.1.2"
20
+ ```
21
+
22
+ Omit `runtime_path` to resolve the gem through RubyGems. The compiler's default
23
+ runtime requirement is `~> 0.1`.
@@ -0,0 +1,258 @@
1
+ # frozen_string_literal: true
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ module Tungsten
5
+ module Runtime
6
+ # Auth resolution: an operation's security is an OR of AND-sets of
7
+ # scheme names; the first alternative the configured credentials fully
8
+ # satisfy is applied. A composite profile satisfies the names in its
9
+ # `satisfies` list when every part it needs for this request is
10
+ # configured.
11
+ class ClientCore
12
+ # The headers, cookies and query parameters credentials add.
13
+ AuthPlan = Struct.new(:headers, :cookies, :query) do
14
+ def self.empty = new([], [], [])
15
+ end
16
+
17
+ # The plan, the secrets it carries, the authorization-code scheme whose
18
+ # stored token it sends, or the remediation of an AUTH_FAILED envelope.
19
+ AuthResult = Struct.new(:plan, :secrets, :oauth, :failed)
20
+
21
+ Satisfier = Struct.new(:kind, :name, :parts, :config, :mutation, :scheme, :secret, :client_id,
22
+ :client_secret, :token_url, :scopes, keyword_init: true)
23
+
24
+ private
25
+
26
+ def safe_method?(method) = %w[GET HEAD OPTIONS TRACE].include?(method)
27
+
28
+ def composite_key(part)
29
+ case part["kind"]
30
+ when "cookie" then part["name"]
31
+ when "bearer" then "bearer"
32
+ else part["equals_cookie"] || part["from_config"] || part["name"]
33
+ end
34
+ end
35
+
36
+ def check_prefix(token, prefix, what)
37
+ return nil if prefix.nil? || prefix.empty? || token.start_with?(prefix)
38
+
39
+ "The #{what} credential must start with \"#{prefix}\"; check that the right kind of token is configured."
40
+ end
41
+
42
+ def skips?(part, mutation) = part["kind"] == "header" && part["mutation_only"] && !mutation
43
+
44
+ def credential(name)
45
+ value = @auth[name]
46
+ case value
47
+ when nil then UNSET
48
+ when Hash then value.to_h { |k, v| [k.to_s, v.nil? ? nil : v.to_s] }
49
+ else value.to_s
50
+ end
51
+ end
52
+
53
+ def part_of(parts, snake, camel) = parts.key?(snake) ? parts[snake] : parts[camel]
54
+
55
+ def try_composite(name, parts, cred, method)
56
+ return [nil, nil, ["auth.#{name} (an object for the composite profile #{name})"]] unless cred.is_a?(Hash)
57
+
58
+ mutation = !safe_method?(method)
59
+ missing = []
60
+ parts.each do |p|
61
+ next if skips?(p, mutation)
62
+
63
+ key = composite_key(p)
64
+ next unless cred[key].to_s.empty?
65
+
66
+ role =
67
+ case p["kind"]
68
+ when "cookie" then "cookie #{p['name']}"
69
+ when "bearer" then "bearer token"
70
+ else "header #{p['name']}#{p['equals_cookie'] ? " (equal to cookie #{p['equals_cookie']})" : ''}"
71
+ end
72
+ missing << "auth.#{name}[#{Util.js_string(key)}] (#{role} of the composite profile #{name})"
73
+ end
74
+ return [nil, nil, missing] unless missing.empty?
75
+
76
+ ["composite:#{name}", Satisfier.new(kind: :composite, name: name, parts: parts, config: cred, mutation: mutation), nil]
77
+ end
78
+
79
+ def try_direct(scheme, cred)
80
+ name = scheme["name"]
81
+ if scheme["kind"] == "oauth2" && cred.is_a?(Hash)
82
+ if part_of(cred, "flow", "flow") == "authorizationCode"
83
+ unless scheme["authorization_code"]
84
+ return [nil, nil, ["auth.#{name} (sets flow \"authorizationCode\", but the API descriptor has no authorizationCode flow for #{name})"]]
85
+ end
86
+ if part_of(cred, "client_id", "clientId").to_s.empty?
87
+ return [nil, nil, ["auth.#{name} (a client_id for the authorizationCode flow)"]]
88
+ end
89
+
90
+ return ["scheme:#{name}", Satisfier.new(kind: :oauth_code, name: name, client_secret: part_of(cred, "client_secret", "clientSecret").to_s), nil]
91
+ end
92
+ id = part_of(cred, "client_id", "clientId")
93
+ secret = part_of(cred, "client_secret", "clientSecret")
94
+ if !id.nil? && !secret.nil? && scheme["token_url"].is_a?(String) && !scheme["token_url"].empty?
95
+ return ["scheme:#{name}", Satisfier.new(kind: :oauth, name: name, token_url: scheme["token_url"], scopes: scheme["scopes"] || [],
96
+ client_id: id, client_secret: secret), nil]
97
+ end
98
+ code = scheme["authorization_code"] ? ", or {flow: \"authorizationCode\", client_id, client_secret?, redirect_uri?}" : ""
99
+ return [nil, nil, ["auth.#{name} (an access token, or {client_id, client_secret} for the token URL#{code})"]]
100
+ end
101
+ return ["scheme:#{name}", Satisfier.new(kind: :secret, scheme: scheme, secret: cred), nil] if cred.is_a?(String) && !cred.empty?
102
+
103
+ what =
104
+ case scheme["kind"]
105
+ when "http_basic" then "\"user:password\" for HTTP Basic scheme #{name}"
106
+ when "api_key" then "API key for scheme #{name} (#{scheme['in']} #{scheme['wire']})"
107
+ else "bearer token for scheme #{name}"
108
+ end
109
+ [nil, nil, ["auth.#{name} (#{what})"]]
110
+ end
111
+
112
+ def schemes = @api["auth"] || []
113
+
114
+ def try_scheme(name, method)
115
+ missing = []
116
+ schemes.each do |s|
117
+ next unless s["kind"] == "composite" && (s["satisfies"] || []).include?(name)
118
+
119
+ cred = credential(s["name"])
120
+ if UNSET.equal?(cred)
121
+ missing << "auth.#{s['name']} (composite profile #{s['name']})"
122
+ next
123
+ end
124
+ key, sat, more = try_composite(s["name"], s["parts"] || [], cred, method)
125
+ return [key, sat, nil] if sat
126
+
127
+ missing.concat(more)
128
+ end
129
+ direct = schemes.find { |s| s["name"] == name && s["kind"] != "composite" }
130
+ if direct
131
+ key, sat, more = try_direct(direct, credential(name))
132
+ return [key, sat, nil] if sat
133
+
134
+ missing.concat(more) if missing.empty?
135
+ elsif missing.empty?
136
+ missing << "a scheme named #{name} (the API descriptor does not define it)"
137
+ end
138
+ [nil, nil, missing]
139
+ end
140
+
141
+ def configured?(name)
142
+ return true if @auth.key?(name)
143
+
144
+ schemes.any? { |s| s["kind"] == "composite" && (s["satisfies"] || []).include?(name) && @auth.key?(s["name"]) }
145
+ end
146
+
147
+ def bearer(plan, token) = plan.headers << ["Authorization", "Bearer #{token}", true]
148
+
149
+ # Apply one satisfier; a remediation when it cannot be applied.
150
+ def apply(sat, result)
151
+ plan = result.plan
152
+ case sat.kind
153
+ when :composite
154
+ sat.parts.each do |p|
155
+ next if skips?(p, sat.mutation)
156
+
157
+ value = sat.config[composite_key(p)].to_s
158
+ case p["kind"]
159
+ when "cookie"
160
+ plan.cookies << [p["name"], value]
161
+ result.secrets << value
162
+ when "bearer"
163
+ problem = check_prefix(value, p["prefix"], "#{sat.name} bearer")
164
+ return problem if problem
165
+
166
+ bearer(plan, value)
167
+ result.secrets << value
168
+ else
169
+ secret = p["from_config"].nil?
170
+ plan.headers << [p["name"], value, secret]
171
+ result.secrets << value if secret
172
+ end
173
+ end
174
+ when :secret
175
+ scheme = sat.scheme
176
+ result.secrets << sat.secret
177
+ case scheme["kind"]
178
+ when "api_key"
179
+ case scheme["in"]
180
+ when "query" then plan.query << [scheme["wire"], sat.secret]
181
+ when "cookie" then plan.cookies << [scheme["wire"], sat.secret]
182
+ else plan.headers << [scheme["wire"], sat.secret, true]
183
+ end
184
+ when "http_bearer"
185
+ problem = check_prefix(sat.secret, scheme["prefix"], scheme["name"])
186
+ return problem if problem
187
+
188
+ bearer(plan, sat.secret)
189
+ when "http_basic"
190
+ encoded = Base64.strict_encode64(sat.secret)
191
+ result.secrets << encoded
192
+ plan.headers << ["Authorization", "Basic #{encoded}", true]
193
+ else bearer(plan, sat.secret)
194
+ end
195
+ when :oauth_code
196
+ result.secrets << sat.client_secret unless sat.client_secret.empty?
197
+ token, problem = stored_token(sat.name, false)
198
+ return problem if problem
199
+
200
+ result.secrets << token
201
+ bearer(plan, token)
202
+ result.oauth ||= sat.name
203
+ when :oauth
204
+ result.secrets << sat.client_secret
205
+ token, problem = client_credentials_token(sat)
206
+ return problem if problem
207
+
208
+ result.secrets << token
209
+ bearer(plan, token)
210
+ end
211
+ nil
212
+ end
213
+
214
+ # The credentials for an operation.
215
+ def resolve_auth(op, method)
216
+ empty = AuthResult.new(AuthPlan.empty, Util::Secrets.new, nil, nil)
217
+ return empty if op.security.empty?
218
+
219
+ best = nil
220
+ best_touched = false
221
+ ordered = op.security.reject(&:empty?) + op.security.select(&:empty?)
222
+ ordered.each do |alternative|
223
+ sats = []
224
+ missing = []
225
+ alternative.each do |name|
226
+ key, sat, more = try_scheme(name, method)
227
+ if sat.nil?
228
+ missing.concat(more)
229
+ next
230
+ end
231
+ existing = sats.find { |k, _| k == key }
232
+ existing ? existing[1] = sat : sats << [key, sat]
233
+ end
234
+ if missing.empty?
235
+ out = AuthResult.new(AuthPlan.empty, Util::Secrets.new, nil, nil)
236
+ sats.each do |_, sat|
237
+ problem = apply(sat, out)
238
+ return AuthResult.new(nil, nil, nil, "#{problem} Operation #{op.id} was not sent.") if problem
239
+ end
240
+ return out
241
+ end
242
+ unique = missing.uniq
243
+ touched = alternative.any? { |n| configured?(n) }
244
+ better = best.nil? || (touched && !best_touched) || (touched == best_touched && unique.length < best.length)
245
+ if better
246
+ best = unique
247
+ best_touched = touched
248
+ end
249
+ end
250
+ alternatives = op.security.map { |alt| alt.empty? ? "no credentials" : alt.join(" AND ") }
251
+ missing_text = best ? best.join("; ") : "credentials"
252
+ AuthResult.new(nil, nil, nil,
253
+ "Operation #{op.id} needs #{alternatives.join(' OR ')}. Missing: #{missing_text}. " \
254
+ "Configure it in ClientOptions.auth and call again; the request was not sent.")
255
+ end
256
+ end
257
+ end
258
+ end
@@ -0,0 +1,248 @@
1
+ # frozen_string_literal: true
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ module Tungsten
5
+ module Runtime
6
+ # Decoding answers and classifying failures into the envelope.
7
+ module Classify
8
+ REQUEST_ID_HEADERS = %w[x-request-id request-id x-correlation-id x-amzn-requestid cf-ray].freeze
9
+ MESSAGE_FIELDS = %w[message error.message detail error_description title error].freeze
10
+
11
+ # A decoded body: `value` (parsed JSON, text, or a Binary; UNSET for an
12
+ # empty body), and what it was.
13
+ Decoded = Data.define(:value, :json, :invalid_json, :empty, :jsonl, :bad_line) do
14
+ def initialize(value:, json: false, invalid_json: false, empty: false, jsonl: false, bad_line: 0) = super
15
+ def present? = !UNSET.equal?(value)
16
+ end
17
+
18
+ # Everything one call's classification shares: the operation, its key
19
+ # and header, the attempts so far and how to check a lost mutation.
20
+ CallContext = Struct.new(:api, :op, :key, :key_header, :attempts, :check, keyword_init: true) do
21
+ def key? = !key.nil?
22
+ end
23
+
24
+ # How to find out whether an unprotected mutation took effect: the call
25
+ # to make and what to look for, in words.
26
+ OutcomeCheck = Data.define(:call, :shows)
27
+
28
+ module_function
29
+
30
+ def request_id(headers)
31
+ REQUEST_ID_HEADERS.each do |name|
32
+ v = headers[name]
33
+ return Json.take_units(v, 200) if v.is_a?(String) && !v.empty?
34
+ end
35
+ nil
36
+ end
37
+
38
+ def media_type(headers) = headers.fetch("content-type", "").split(";").first.to_s.strip.downcase
39
+
40
+ def json_media?(media) = media == "application/json" || media.end_with?("+json") || media == "text/json"
41
+
42
+ def jsonl_media?(media) = %w[application/jsonl application/x-jsonl application/ndjson application/x-ndjson].include?(media)
43
+
44
+ def match_response(responses, status)
45
+ responses.find { |r| r.status == status } ||
46
+ responses.find { |r| r.status.is_a?(String) && r.status.match?(/\A[1-5]XX\z/) && r.status[0].to_i == status / 100 } ||
47
+ responses.find { |r| r.status == "default" }
48
+ end
49
+
50
+ def decode_text(data)
51
+ text = data.b.delete_prefix("\xEF\xBB\xBF".b).force_encoding(Encoding::UTF_8)
52
+ text.valid_encoding? ? text : text.scrub("\uFFFD")
53
+ end
54
+
55
+ def decode_body(data, headers, declared)
56
+ announced = media_type(headers)
57
+ return Decoded.new(value: UNSET, empty: true) if data.empty? && !jsonl_media?(announced)
58
+
59
+ media = announced.empty? ? declared.to_s.downcase : announced
60
+ jsonl_media = announced.empty? ? media.split(";").first.to_s.strip : announced
61
+ if jsonl_media?(jsonl_media)
62
+ raw = decode_text(data)
63
+ values = []
64
+ raw.split("\n", -1).each_with_index do |line, i|
65
+ next if line.strip.empty?
66
+
67
+ v = Json.try_parse(line)
68
+ return Decoded.new(value: raw, invalid_json: true, jsonl: true, bad_line: i + 1) if UNSET.equal?(v)
69
+
70
+ values << v
71
+ end
72
+ return Decoded.new(value: values, jsonl: true)
73
+ end
74
+ if json_media?(media)
75
+ raw = decode_text(data)
76
+ v = Json.try_parse(raw)
77
+ return UNSET.equal?(v) ? Decoded.new(value: raw, invalid_json: true) : Decoded.new(value: v, json: true)
78
+ end
79
+ if media.empty? || media.start_with?("text/") || media == "application/problem+xml" || media.end_with?("+xml") ||
80
+ media == "application/xml"
81
+ raw = decode_text(data)
82
+ if media.empty? && raw.lstrip.start_with?("[", "{")
83
+ v = Json.try_parse(raw)
84
+ return Decoded.new(value: v, json: true) unless UNSET.equal?(v)
85
+ end
86
+ return Decoded.new(value: raw)
87
+ end
88
+ Decoded.new(value: Binary.new(data: data))
89
+ end
90
+
91
+ def server_message(body)
92
+ MESSAGE_FIELDS.each do |field|
93
+ v = Util.get_path_str(body, field)
94
+ next unless v.is_a?(String)
95
+
96
+ text = v.strip
97
+ return Json.take_units(text, 200) unless text.empty?
98
+ end
99
+ nil
100
+ end
101
+
102
+ def error_code(op, body)
103
+ return nil if op.error_code_field.nil? || op.error_code_field.empty?
104
+
105
+ v = Util.get_path_str(body, op.error_code_field)
106
+ case v
107
+ when String then v.empty? ? nil : Json.take_units(v, 200)
108
+ when Integer, Float then Json.number_text(v)
109
+ end
110
+ end
111
+
112
+ def refers_to_response?(node, depth = 0)
113
+ return true if depth > 32
114
+
115
+ case node
116
+ when String then node == "$response" || node.start_with?("$response.")
117
+ when Array then node.any? { |n| refers_to_response?(n, depth + 1) }
118
+ when Hash then node.each_value.any? { |n| refers_to_response?(n, depth + 1) }
119
+ else false
120
+ end
121
+ end
122
+
123
+ # After a lost answer there is no success body, so a hook whose
124
+ # arguments reference $response cannot be called.
125
+ def verify_callable?(verify) = !refers_to_response?(verify["args"])
126
+
127
+ def next_action_hint(ctx)
128
+ op = ctx.op
129
+ v = op.agent["verify"]
130
+ if v && v["operation"].to_s != "" && verify_callable?(v)
131
+ args = v["args"]
132
+ with = args.is_a?(Hash) && !args.empty? ? " with #{args.keys.join(', ')}" : ""
133
+ return "Call #{v['operation']}#{with} to check whether #{op.id} took effect before doing anything else."
134
+ end
135
+ if op.agent["idempotency"]["policy"] == "content_identity"
136
+ return "Call #{op.id} again with the identical body; the body is its own identity, so the server answers the original result instead of applying it twice."
137
+ end
138
+ return nil unless ctx.key?
139
+
140
+ "Call #{op.id} again with the same #{ctx.key_header} value and identical arguments; the server answers the original result instead of applying it twice."
141
+ end
142
+
143
+ # The change an operation makes, in words.
144
+ def change_of(op)
145
+ summary = op.summary.strip.delete_suffix(".")
146
+ summary.empty? ? "the change #{op.id} makes" : "the change #{Util.js_string(summary)}"
147
+ end
148
+
149
+ def replay_protection?(op, has_key) = op.agent["idempotency"]["policy"] == "content_identity" || has_key
150
+
151
+ # OUTCOME_UNKNOWN for a mutation whose effect cannot be known. Without
152
+ # replay protection a repeat can apply the effect twice, so the
153
+ # envelope never offers one.
154
+ def outcome_unknown(ctx, cause, next_action: nil, http_status: nil, code: nil, request_id: nil, retry_after_ms: nil)
155
+ op = ctx.op
156
+ hint = nil
157
+ rule =
158
+ if op.agent["idempotency"]["policy"] == "content_identity"
159
+ "If you retry, resend the identical bytes only; the body is its own identity."
160
+ elsif ctx.key?
161
+ "If you retry, reuse the SAME #{ctx.key_header} value; a new key can apply the effect twice."
162
+ elsif ctx.check
163
+ c = ctx.check
164
+ hint = "Call #{c.call} and check #{c.shows}; call #{op.id} again only if it did not take effect."
165
+ "This operation has no idempotency key, so repeating it can apply the effect twice. Before calling #{op.id} again, " \
166
+ "call #{c.call} and check #{c.shows}: if it does, #{op.id} took effect and must not be repeated; call it again only if it did not."
167
+ else
168
+ change = change_of(op)
169
+ hint = "Do not retry #{op.id} blindly: it may have taken effect. Check for #{change} if you can; call #{op.id} " \
170
+ "again only if it is not there, or after the task owner accepts that it may apply twice."
171
+ "This operation has no idempotency key and no registered way to verify it, so #{op.id} may have taken effect and " \
172
+ "a repeat can apply the effect twice: do not retry it blindly. Check the outcome by other means if you can " \
173
+ "(look for #{change}); if you cannot, ask whoever owns the task before calling it again."
174
+ end
175
+ retryable = replay_protection?(op, ctx.key?) ? "same_key_only" : "after_remediation"
176
+ Runtime.diag(op.id, "OUTCOME_UNKNOWN")
177
+ .remedy("#{cause} The server may or may not have applied #{op.id}. #{rule}")
178
+ .retrying(retryable).next_action(next_action || hint || next_action_hint(ctx))
179
+ .status(http_status).code(code).request_id(request_id).retry_after_ms(retry_after_ms)
180
+ .attempts(ctx.attempts).build
181
+ end
182
+
183
+ DEFINITE = %w[VALIDATION_FAILED MALFORMED_REQUEST REQUEST_TOO_LARGE AUTH_FAILED NOT_FOUND CONFLICT PRECONDITION_FAILED
184
+ RATE_LIMITED GATE_DISABLED].freeze
185
+
186
+ # A manifest entry with one of these categories (or retryable never /
187
+ # after_remediation) is a definite answer even for an ambiguous status.
188
+ def definite?(category, retryable) = %w[never after_remediation].include?(retryable) || DEFINITE.include?(category)
189
+
190
+ # The envelope of an HTTP error status.
191
+ def classify_error(ctx, status, headers, decoded, retry_after)
192
+ api = ctx.api
193
+ op = ctx.op
194
+ rid = request_id(headers)
195
+ base = ->(d) { d.status(status).request_id(rid).retry_after_ms(retry_after).attempts(ctx.attempts) }
196
+ code = decoded.json ? error_code(op, decoded.value) : nil
197
+ gate = op.gate
198
+ if gate && status == gate["disabled_status"] && code.nil?
199
+ text = (api["gates"] || {})[gate["env_var"]] ||
200
+ "This deployment disables #{op.id} because #{gate['env_var']} is off (HTTP #{status}). It is a deployment setting, not a missing resource; do not retry."
201
+ return base.call(Runtime.diag(op.id, "GATE_DISABLED")).code(code).remedy(text).retrying("never").build
202
+ end
203
+ entry = code && (op.agent["remediation"][code] || (api["error_codes"] || {})[code])
204
+ media = "none"
205
+ media = media_type(headers).then { |m| m.empty? ? "none" : m } unless decoded.empty
206
+ non_json = nil
207
+ unless decoded.json
208
+ non_json = (api["non_json"] || []).find do |n|
209
+ n["status"] == status && (n["media"] == media || (n["media"] == "none" && decoded.empty))
210
+ end
211
+ end
212
+ declared = match_response(op.responses, status)
213
+ ambiguous = (api["ambiguous_statuses"] || []).include?(status) || declared&.kind == "ambiguous" || status.between?(500, 599)
214
+ definite = (entry && definite?(entry["category"], entry["retryable"])) || (!entry && non_json && definite?(non_json["category"], non_json["retryable"]))
215
+ if ambiguous && op.mutation? && !definite
216
+ said = entry && !entry["text"].to_s.empty? ? entry["text"] : (non_json && !non_json["text"].to_s.empty? ? non_json["text"] : nil)
217
+ cause = "HTTP #{status} leaves the outcome of this call unknown."
218
+ cause += " #{said}" if said
219
+ return outcome_unknown(ctx, cause, next_action: entry && entry["next_action"], http_status: status, code: code,
220
+ request_id: rid, retry_after_ms: retry_after)
221
+ end
222
+ if entry
223
+ category = entry["category"] || Runtime.category_for_status(status, decoded.json)
224
+ retryable = entry["retryable"]
225
+ text = entry["text"]
226
+ next_action = entry["next_action"]
227
+ elsif non_json
228
+ category = non_json["category"]
229
+ retryable = non_json["retryable"]
230
+ text = non_json["text"]
231
+ else
232
+ category = Runtime.category_for_status(status, decoded.json)
233
+ end
234
+ if category == "OUTCOME_UNKNOWN" && !op.mutation?
235
+ category = "UPSTREAM_UNAVAILABLE"
236
+ retryable = "after_delay" if retryable.nil? || retryable == "same_key_only"
237
+ end
238
+ if text.nil? || text.empty?
239
+ text = Runtime.generic_remediation(category)
240
+ if decoded.json && (said = server_message(decoded.value))
241
+ text += " Server message: #{Util.js_string(said)}"
242
+ end
243
+ end
244
+ base.call(Runtime.diag(op.id, category)).code(code).remedy(text).retrying_opt(retryable).next_action(next_action).build
245
+ end
246
+ end
247
+ end
248
+ end