audience-kit 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Audience
4
+ module Kit
5
+ # Which fields an audience's schema has, as far as the SDK's documents need to know. The API leaves a module's
6
+ # fields out of an audience that hasn't installed it (Facebook Pages, Google Places, RSVP, Ticketing, Friends...),
7
+ # and asking for one fails the whole operation with +undefinedField+; the SDK builds its documents from this.
8
+ class SchemaShape
9
+ # @return [Hash{String => Array<String>}, nil] every type's fields, by type; nil assumes every field is there
10
+ attr_reader :fields
11
+
12
+ def initialize(fields = nil)
13
+ @fields = fields
14
+ end
15
+
16
+ # Assumes every field is there: the first try of each operation, so an audience with every module needs one
17
+ # call.
18
+ # @return [SchemaShape]
19
+ def self.everything
20
+ new(nil)
21
+ end
22
+
23
+ # @param type [String]
24
+ # @param field [String]
25
+ # @return [Boolean]
26
+ def has?(type, field)
27
+ fields.nil? || fields.fetch(type, []).include?(field)
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,580 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Audience
4
+ module Kit
5
+ # Talks to the AudienceKit API on behalf of one audience and, once signed in, one person.
6
+ #
7
+ # Sign in with a Facebook, Google or Apple token the page obtained, use an application API key or a service
8
+ # token, or {#adopt} a credential minted elsewhere. After that, every call carries the token as
9
+ # +Authorization: Bearer <token>+ and the API contract version as +X-AudienceKit-API-Version+. When the API
10
+ # rejects a person's session, the call raises {Error} with {Error::UNAUTHENTICATED} and the credential is
11
+ # forgotten.
12
+ #
13
+ # The calls every app makes ({#venues}, {#events}, {#rsvp_event}...) are in {Operations}; run your own documents
14
+ # with {#graphql}.
15
+ #
16
+ # @example A script with an application API key
17
+ # session = Audience::Kit::Session.new(
18
+ # configuration: Audience::Kit::Configuration.new(host: "hotmess.social")
19
+ # )
20
+ # session.use_bearer_token(ENV.fetch("AUDIENCEKIT_TOKEN"))
21
+ # session.venues.each { |venue| puts venue.name }
22
+ class Session
23
+ include Operations
24
+
25
+ # How long before a service token's session expires the SDK trades the token again, in seconds.
26
+ SERVICE_RENEW_BEFORE = 60
27
+
28
+ # @return [Configuration]
29
+ attr_reader :configuration
30
+
31
+ # @param configuration [Configuration] where the API is and which audience to speak for
32
+ # @param store [#load, #save, #delete] where the credential is kept ({MemoryCredentialStore} by default;
33
+ # {SessionCredentialStore} for a website)
34
+ # @param http [Faraday::Connection, nil] the connection requests go through; pass one to set timeouts, a proxy,
35
+ # instrumentation or a test adapter
36
+ def initialize(configuration: Configuration.new, store: MemoryCredentialStore.new, http: nil)
37
+ @configuration = configuration
38
+ @store = store
39
+ @http = http || Faraday.new { |f| f.options.timeout = 30 }
40
+ @resolved_audience_id = nil
41
+ @schema_fields = {}
42
+ @service_token = nil
43
+ end
44
+
45
+ # A session configured from the environment, for servers and scripts: +AUDIENCEKIT_TOKEN+ (a service token,
46
+ # +akst_...+, or another bearer value such as an application API key) and, when set, +AUDIENCEKIT_BASE_URL+,
47
+ # +AUDIENCEKIT_AUDIENCE_ID+, +AUDIENCEKIT_HOST+ and +AUDIENCEKIT_ENVIRONMENT+.
48
+ # @param env [Hash{String => String}] where to read them from
49
+ # @param http [Faraday::Connection, nil]
50
+ # @return [Session]
51
+ def self.from_env(env = ENV, http: nil)
52
+ read = ->(name) { env.fetch("AUDIENCEKIT_#{name}", nil).then { |value| value.to_s.empty? ? nil : value } }
53
+ build(
54
+ configuration: Configuration.new(base_url: read["BASE_URL"] || PRODUCTION_BASE_URL, host: read["HOST"],
55
+ audience_id: read["AUDIENCE_ID"],
56
+ environment: read["ENVIRONMENT"] || Environment::PRODUCTION),
57
+ token: read["TOKEN"], http: http
58
+ )
59
+ end
60
+
61
+ # A session that uses +token+: a service token (+akst_...+), traded when first needed, or anything else, sent
62
+ # as is.
63
+ # @return [Session]
64
+ def self.build(configuration:, token: nil, http: nil)
65
+ session = new(configuration: configuration, http: http)
66
+ if token&.start_with?("akst_")
67
+ session.instance_variable_set(:@service_token, token)
68
+ elsif token
69
+ session.use_bearer_token(token)
70
+ end
71
+ session
72
+ end
73
+
74
+ # @!group Session
75
+
76
+ # Whether a credential is stored. The API may still reject it.
77
+ # @return [Boolean]
78
+ def signed_in?
79
+ !load_credential.nil?
80
+ end
81
+
82
+ # The stored credential: who is signed in, to which audience, and the token. Never log the token.
83
+ # @return [Credential, nil]
84
+ def credential
85
+ load_credential
86
+ end
87
+
88
+ # The stored session token, for the rare connection the SDK doesn't make itself (an Action Cable client).
89
+ # @return [String, nil]
90
+ def session_token
91
+ load_credential&.token
92
+ end
93
+
94
+ # Exchanges a Facebook user access token for a session and stores it. Sends the configured host and Facebook
95
+ # app ID, so the API checks the token against the right Facebook app and binds the session to the audience.
96
+ # @param access_token [String]
97
+ # @param device [DeviceDescription]
98
+ # @return [Credential]
99
+ # @raise [Error] {Error::SIGN_IN_REJECTED} when the API refuses the token
100
+ def sign_in_with_facebook_token(access_token, device:)
101
+ sign_in("/v1/token", facebook_body({ "facebook_token" => access_token }, device))
102
+ end
103
+
104
+ # Exchanges the code from Facebook's OAuth dialog for a session and stores it. The API trades the code with the
105
+ # app secret, so +redirect_uri+ must be exactly the one the dialog was opened with.
106
+ # @param code [String]
107
+ # @param redirect_uri [String]
108
+ # @param device [DeviceDescription]
109
+ # @param facebook_app_id [String, nil] overrides the configured app
110
+ # @return [Credential]
111
+ def sign_in_with_facebook_code(code, redirect_uri:, device:, facebook_app_id: nil)
112
+ fields = { "code" => code, "redirect_uri" => redirect_uri, "facebook_app_id" => facebook_app_id }.compact
113
+ sign_in("/v1/token", facebook_body(fields, device))
114
+ end
115
+
116
+ # Exchanges a Google ID token (from Google Identity Services) for a session and stores it. Pass +access_token+
117
+ # (an OAuth token for +https://www.googleapis.com/auth/user.emails.read+) and the API can also match an
118
+ # existing account by the Google account's other verified emails.
119
+ # @param id_token [String]
120
+ # @param device [DeviceDescription]
121
+ # @param name [String, nil]
122
+ # @param access_token [String, nil]
123
+ # @return [Credential]
124
+ def sign_in_with_google(id_token, device:, name: nil, access_token: nil)
125
+ sign_in("/v1/token/google", { "id_token" => id_token, "access_token" => access_token,
126
+ "host" => configuration.host, "device" => device.to_body,
127
+ "name" => name }.compact)
128
+ end
129
+
130
+ # Connects a Google account to the signed-in account, so Google signs in to it from then on, and stores the
131
+ # session the API answers with. A refusal raises {Error::SIGN_IN_FAILED} and keeps the current session.
132
+ # @return [Credential]
133
+ def connect_google(id_token, device:)
134
+ sign_in("/v1/token/google", { "id_token" => id_token, "host" => configuration.host,
135
+ "device" => device.to_body, "connect" => true }.compact, authenticated: true)
136
+ end
137
+
138
+ # Exchanges a Sign in with Apple credential for a session and stores it (+POST /v1/token/apple+). On the web,
139
+ # Sign in with Apple JS returns the identity token, an authorization code and the redirect URI it used; pass the
140
+ # nonce you gave it. Apple gives the person's name only the first time; pass it then.
141
+ # @return [Credential]
142
+ def sign_in_with_apple(identity_token, device:, authorization_code: nil, redirect_uri: nil, nonce: nil,
143
+ first_name: nil, last_name: nil)
144
+ sign_in("/v1/token/apple", {
145
+ "identity_token" => identity_token, "authorization_code" => authorization_code,
146
+ "redirect_uri" => redirect_uri, "nonce" => nonce, "first_name" => first_name, "last_name" => last_name,
147
+ "host" => configuration.host, "device" => device.to_body
148
+ }.compact)
149
+ end
150
+
151
+ # Signs in with an App Review code (+POST /v1/token/review+). It works only while the audience is in App
152
+ # Review; a wrong or expired code raises {Error::SIGN_IN_REJECTED}.
153
+ # @return [Credential]
154
+ def sign_in_with_review_code(code, device:)
155
+ sign_in("/v1/token/review", { "code" => code.strip, "host" => configuration.host,
156
+ "device" => device.to_body }.compact)
157
+ end
158
+
159
+ # Connects Facebook to the signed-in account (one that signed in with Apple or Google), with the code from
160
+ # Facebook's OAuth dialog, and stores the new session the API returns.
161
+ # @return [Credential]
162
+ def connect_facebook(code, redirect_uri:, device:)
163
+ body = facebook_body({ "code" => code, "redirect_uri" => redirect_uri, "connect" => true }, device)
164
+ sign_in("/v1/token", body, authenticated: true)
165
+ end
166
+
167
+ # Re-issues the session token at +POST /v1/token/refresh+ (the same session, signed with the API's current key)
168
+ # and stores it.
169
+ # @return [Credential]
170
+ def refresh_session
171
+ store(decode_credential(request("/v1/token/refresh", method: :post)))
172
+ end
173
+
174
+ # Uses an audience service token (+akst_<prefix>_<secret>+, minted by an admin in the audience's console): a
175
+ # server or agent acting for the audience rather than a person. The SDK trades it at +POST /v1/token/service+
176
+ # for an hour-long session now, trades it again a minute before that runs out, and once more when the API
177
+ # refuses the session. A token with +public:read+ reads the public listings ({Operations#public_listings}).
178
+ # @param service_token [String]
179
+ # @return [Credential]
180
+ # @raise [Error] {Error::UNAUTHENTICATED} when the token is invalid or revoked
181
+ def use_service_token(service_token)
182
+ @service_token = service_token
183
+ trade_service_token
184
+ end
185
+
186
+ # Sends +token+ as is (an application's API key, or a session JWT on its own) as +Authorization: Bearer+, to
187
+ # the configured base URL and audience.
188
+ # @param token [String]
189
+ # @return [Credential]
190
+ def use_bearer_token(token)
191
+ @service_token = nil
192
+ store(Credential.new(token: token, audience_id: configuration.audience_id, role: "bearer",
193
+ endpoint: "#{configuration.base_url.chomp("/")}/v1/graphql"))
194
+ end
195
+
196
+ # Makes +credential+ the session: one minted outside the SDK (a venue device's) or one the app stored itself.
197
+ # GraphQL goes to the API instance the credential's endpoint names, for its audience.
198
+ # @param credential [Credential]
199
+ # @return [Credential]
200
+ def adopt(credential)
201
+ store(credential)
202
+ end
203
+
204
+ # Moves the session to another audience (+POST /v1/admin/choices+) and returns its credential, stored and in
205
+ # use. The API allows it for platform-console sessions; anyone else gets {Error::FORBIDDEN}.
206
+ # @return [Credential]
207
+ def switch_audience(audience_id)
208
+ store(decode_credential(request("/v1/admin/choices", method: :post, body: { "audience_id" => audience_id })))
209
+ end
210
+
211
+ # Ends the session: forgets the credential, then revokes the token with +DELETE /v1/token+ so it stops working
212
+ # everywhere. The credential is forgotten even when that call fails; a 401 or 404 (the session was already
213
+ # gone) is not an error.
214
+ # @return [void]
215
+ def sign_out
216
+ credential = load_credential
217
+ @service_token = nil
218
+ forget
219
+ return if credential.nil?
220
+
221
+ response = perform(:delete, "/v1/token", token: credential.token)
222
+ return if response.success? || [401, 404].include?(response.status)
223
+
224
+ raise error_for_status(response.status, response.body)
225
+ end
226
+
227
+ # Deletes the signed-in person's account for good (App Store guideline 5.1.1(v), Google Play's account
228
+ # deletion rule). The API erases their data and signs them out everywhere, so the credential is forgotten too.
229
+ # It can't be undone: ask first.
230
+ # @return [Boolean] whether the account is gone; when it isn't, the person stays signed in
231
+ def delete_account
232
+ data = graphql(Queries::DELETE_ACCOUNT, { "confirm" => true }, operation_name: "DeleteAccount")
233
+ return false unless data.dig("deleteAccount", "deleted") == true
234
+
235
+ forget
236
+ true
237
+ end
238
+
239
+ # Ends the session because the API refused +token+ on a connection the SDK didn't make itself. Forgets the
240
+ # credential once: when the store no longer holds +token+ it does nothing and returns false.
241
+ # @return [Boolean]
242
+ def session_rejected(token)
243
+ stored = load_credential
244
+ return false if token.nil? || stored.nil? || stored.token != token
245
+
246
+ forget
247
+ true
248
+ end
249
+
250
+ # @!endgroup
251
+
252
+ # @!group The audience
253
+
254
+ # The audience's public branding for the configured host (or +host+). No sign-in needed. Pass +app+ (a bundle
255
+ # ID) to have it carry that app's release config too.
256
+ # @return [Hash]
257
+ def branding(host: configuration.host, app: nil)
258
+ raise Error.missing_configuration("branding needs a host") if host.nil?
259
+
260
+ query = { "host" => host }
261
+ query["app"] = app unless app.to_s.empty?
262
+ decode_object(request("/v1/branding", query: query, authenticated: false))
263
+ end
264
+
265
+ # The audience this session reads: the stored credential's audience, else the configured ID, else the audience
266
+ # that owns the configured host (looked up once).
267
+ # @return [String]
268
+ # @raise [Error] {Error::MISSING_CONFIGURATION} with neither an audience ID nor a host
269
+ def audience_id
270
+ id = load_credential&.audience_id || configuration.audience_id || @resolved_audience_id
271
+ return id if id
272
+ raise Error.missing_configuration("set an audience_id or a host") if configuration.host.nil?
273
+
274
+ id = branding.dig("audience", "id")
275
+ raise Error.decoding("The branding had no audience id.") unless id.is_a?(String)
276
+
277
+ @resolved_audience_id = id
278
+ end
279
+
280
+ # @!endgroup
281
+
282
+ # @!group GraphQL
283
+
284
+ # Runs a GraphQL operation against the audience's endpoint and returns its +data+.
285
+ #
286
+ # The request goes to the API instance the stored credential names (the configured base URL before sign-in).
287
+ # Raises when the response carries errors, even alongside data.
288
+ # @param document [String]
289
+ # @param variables [Hash, nil]
290
+ # @param operation_name [String, nil]
291
+ # @param endpoint [String] {GraphQLEndpoint::CONSUMER}
292
+ # @return [Hash] the response's +data+, with the schema's (camelCase) keys
293
+ # @raise [Error] {Error.graphql} for GraphQL errors; see {Error} for the rest
294
+ # @example
295
+ # data = session.graphql(<<~GRAPHQL, { "first" => 5 })
296
+ # query Soon($first: Int) { events { list(first: $first) { nodes { id name startAt } } } }
297
+ # GRAPHQL
298
+ # Audience::Kit::Event.list(data.dig("events", "list"))
299
+ def graphql(document, variables = nil, operation_name: nil, endpoint: GraphQLEndpoint::CONSUMER)
300
+ ensure_service_session
301
+ credential = load_credential
302
+ body = { "query" => document, "variables" => variables, "operationName" => operation_name }.compact
303
+ type, name = Session.describe(document, operation_name)
304
+ # Apollo's operation headers, which APM agents record with each request.
305
+ headers = { "X-APOLLO-OPERATION-TYPE" => type, "X-APOLLO-OPERATION-NAME" => name }.compact
306
+ path = GraphQLEndpoint.path(audience_id, endpoint)
307
+ json = decode_object(request(path, method: :post, body: body, headers: headers,
308
+ base_url: configuration.api_base(credential)))
309
+ # Errors first: a refused mutation comes back as {"errors":[...],"data":{"field":null}}.
310
+ if json["errors"].is_a?(Array) && !json["errors"].empty?
311
+ raise Error.graphql(json["errors"].map { |error| GraphQLError.from_h(error) })
312
+ end
313
+ raise Error.decoding("The response had no data.") unless json["data"].is_a?(Hash)
314
+
315
+ json["data"]
316
+ end
317
+
318
+ # Runs the operation the block builds, first for an audience with every module; when the API refuses a field
319
+ # (+undefinedField+), asks the schema which fields +types+ have and runs it again with only those. The answer
320
+ # is cached for the session, so later operations go straight to the right document.
321
+ # @param types [Array<String>]
322
+ # @param variables [Hash, nil]
323
+ # @param operation_name [String]
324
+ # @yieldparam shape [SchemaShape]
325
+ # @yieldreturn [String] the document
326
+ # @return [Hash]
327
+ def shaped_graphql(types, variables, operation_name, &document)
328
+ known = cached_schema_fields(types)
329
+ return graphql(document.call(SchemaShape.new(known)), variables, operation_name: operation_name) if known
330
+
331
+ begin
332
+ graphql(document.call(SchemaShape.everything), variables, operation_name: operation_name)
333
+ rescue Error => e
334
+ raise unless e.undefined_field?
335
+
336
+ graphql(document.call(SchemaShape.new(schema_fields(types))), variables, operation_name: operation_name)
337
+ end
338
+ end
339
+
340
+ # The fields each of +types+ has in the audience's schema (introspection), by type name; a type the schema
341
+ # doesn't have is left out. Cached for the session (until sign-in or sign-out).
342
+ # @param types [Array<String>]
343
+ # @return [Hash{String => Array<String>}]
344
+ def schema_fields(types, endpoint: GraphQLEndpoint::CONSUMER)
345
+ prefix = "#{audience_id}|#{endpoint}|"
346
+ missing = types.uniq.reject { |type| @schema_fields.key?(prefix + type) }.sort
347
+ unless missing.empty?
348
+ selections = missing.each_with_index.map do |name, index|
349
+ "t#{index}: __type(name: \"#{name}\") { fields(includeDeprecated: true) { name } }"
350
+ end
351
+ result = graphql("query SchemaFields { #{selections.join(" ")} }", operation_name: "SchemaFields",
352
+ endpoint: endpoint)
353
+ missing.each_with_index do |name, index|
354
+ fields = result.dig("t#{index}", "fields")
355
+ @schema_fields[prefix + name] = Array(fields).filter_map { |field| field["name"] if field.is_a?(Hash) }
356
+ end
357
+ end
358
+ shape_from_cache(prefix, types)
359
+ end
360
+
361
+ # {#schema_fields}'s answer when the session already has it for every one of +types+, without asking the API;
362
+ # nil otherwise.
363
+ # @return [Hash{String => Array<String>}, nil]
364
+ def cached_schema_fields(types, endpoint: GraphQLEndpoint::CONSUMER)
365
+ prefix = "#{audience_id}|#{endpoint}|"
366
+ types.all? { |type| @schema_fields.key?(prefix + type) } ? shape_from_cache(prefix, types) : nil
367
+ rescue Error
368
+ nil
369
+ end
370
+
371
+ # @!endgroup
372
+
373
+ # @!group REST
374
+
375
+ # Sends a request to one of the API's REST endpoints and returns the body of a successful response.
376
+ # @param path [String] e.g. +/v1/branding+
377
+ # @param method [Symbol] +:get+, +:post+, +:delete+...
378
+ # @param query [Hash] query parameters
379
+ # @param body [Object, nil] a JSON body
380
+ # @param authenticated [Boolean] whether to send the session token; a 401 on an authenticated request ends a
381
+ # person's session
382
+ # @param headers [Hash] headers beyond the ones every call carries
383
+ # @param base_url [String, nil] another API instance than the configured one
384
+ # @return [String]
385
+ def request(path, method: :get, query: {}, body: nil, authenticated: true, headers: {}, base_url: nil)
386
+ retried = false
387
+ loop do
388
+ token = nil
389
+ base = base_url
390
+ if authenticated
391
+ ensure_service_session
392
+ stored = load_credential or raise Error.not_signed_in
393
+ token = stored.token
394
+ # A REST call follows a service session to the instance that issued it, like GraphQL.
395
+ base ||= configuration.api_base(stored) if stored.service?
396
+ end
397
+ response = perform(method, path, query: query, body: body, token: token, headers: headers, base_url: base)
398
+ return response.body.to_s if response.success?
399
+
400
+ if response.status == 401 && token
401
+ if @service_token && !retried
402
+ # The service session was refused (revoked, or signed with a retired key): trade the token again.
403
+ retried = true
404
+ trade_service_token
405
+ next
406
+ end
407
+ session_rejected(token)
408
+ raise Error.unauthorized
409
+ end
410
+ raise error_for_status(response.status, response.body)
411
+ end
412
+ end
413
+
414
+ # Resolves a URL the API sent (absolute, or a path relative to the base URL).
415
+ # @param string [String, nil]
416
+ # @return [String, nil]
417
+ def url(string)
418
+ return nil if string.to_s.empty?
419
+ return string if string.match?(%r{\A[a-z][a-z0-9+.-]*://}i)
420
+
421
+ "#{configuration.base_url.chomp("/")}/#{string.delete_prefix("/")}"
422
+ end
423
+
424
+ # @!endgroup
425
+
426
+ # An operation's type and name, from its document (or +operation_name+), for the monitoring headers.
427
+ # @return [Array(String, String)]
428
+ def self.describe(document, operation_name)
429
+ match = /\A\s*(query|mutation|subscription)\b\s*([A-Za-z_]\w*)?/.match(document)
430
+ return ["query", operation_name] unless match
431
+
432
+ [match[1], operation_name || match[2]]
433
+ end
434
+
435
+ # @return [String]
436
+ def inspect
437
+ "#<#{self.class.name} base_url=#{configuration.base_url} signed_in=#{signed_in?}>"
438
+ end
439
+
440
+ private
441
+
442
+ def ensure_service_session
443
+ return if @service_token.nil?
444
+
445
+ stored = load_credential
446
+ trade_service_token if stored.nil? || stored.expires_within?(SERVICE_RENEW_BEFORE)
447
+ end
448
+
449
+ def trade_service_token
450
+ response = perform(:post, "/v1/token/service", body: { "service_token" => @service_token })
451
+ if [401, 403].include?(response.status)
452
+ @service_token = nil
453
+ raise Error.new("The service token was refused: it is invalid or was revoked.",
454
+ code: Error::UNAUTHENTICATED, status: response.status)
455
+ end
456
+ raise error_for_status(response.status, response.body) unless response.success?
457
+
458
+ store(decode_credential(response.body))
459
+ end
460
+
461
+ def sign_in(path, body, authenticated: false)
462
+ token = (load_credential&.token or raise Error.not_signed_in) if authenticated
463
+ response = perform(:post, path, body: body, token: token)
464
+ raise Error.sign_in_rejected if response.status == 401
465
+
466
+ if response.status == 400
467
+ fault = rest_error_body(response.body)
468
+ unless fault["error"] == Error::UNSUPPORTED_API_VERSION_ERROR
469
+ raise Error.sign_in_failed(fault["message"] || fault.dig("fault", "message"))
470
+ end
471
+ end
472
+ raise error_for_status(response.status, response.body) unless response.success?
473
+
474
+ store(decode_credential(response.body))
475
+ end
476
+
477
+ def facebook_body(fields, device)
478
+ fields.merge("host" => configuration.host, "facebook_app_id" => configuration.facebook_app_id) { |_, a, _| a }
479
+ .merge("device" => device.to_body).compact
480
+ end
481
+
482
+ def store(credential)
483
+ begin
484
+ @store.save(credential)
485
+ rescue StandardError => e
486
+ raise Error.storage(e.message)
487
+ end
488
+ @resolved_audience_id = nil
489
+ @schema_fields = {}
490
+ credential
491
+ end
492
+
493
+ def forget
494
+ begin
495
+ @store.delete
496
+ rescue StandardError
497
+ # The token is revoked (or the account is gone) either way.
498
+ end
499
+ @resolved_audience_id = nil
500
+ @schema_fields = {}
501
+ end
502
+
503
+ def load_credential
504
+ @store.load
505
+ rescue StandardError
506
+ nil
507
+ end
508
+
509
+ def shape_from_cache(prefix, types)
510
+ types.to_h { |type| [type, @schema_fields.fetch(prefix + type, [])] }.reject { |_, fields| fields.empty? }
511
+ end
512
+
513
+ def perform(method, path, query: {}, body: nil, token: nil, headers: {}, base_url: nil)
514
+ url = "#{(base_url || configuration.base_url).chomp("/")}/#{path.delete_prefix("/")}"
515
+ url += "?#{URI.encode_www_form(query)}" unless query.empty?
516
+ all = {
517
+ "Accept" => "application/json", CLIENT_HEADER => Kit.client_header, API_VERSION_HEADER => API_VERSION
518
+ }
519
+ all[Environment::HEADER] = configuration.environment unless configuration.environment == Environment::PRODUCTION
520
+ all["Authorization"] = "Bearer #{token}" if token
521
+ all.merge!(headers)
522
+ payload = nil
523
+ unless body.nil?
524
+ all["Content-Type"] = "application/json"
525
+ payload = JSON.generate(body)
526
+ end
527
+ @http.run_request(method, url, payload, all)
528
+ rescue Faraday::Error => e
529
+ raise Error.network(e)
530
+ end
531
+
532
+ # The error for an unsuccessful REST status, reading the API's { "error": "<code>", "message": "..." } body.
533
+ def error_for_status(status, data)
534
+ body = rest_error_body(data)
535
+ message = body["message"] || body.dig("fault", "message")
536
+ message = nil unless message.is_a?(String)
537
+ code = body["error"].is_a?(String) ? body["error"] : nil
538
+ case status
539
+ when 401 then Error.unauthorized
540
+ when 403 then Error.forbidden(message)
541
+ when 404 then Error.not_found(message)
542
+ when 426 then Error.update_required(body["minimum_sdk_version"].to_s, message)
543
+ else
544
+ if status == 400 && code == Error::UNSUPPORTED_API_VERSION_ERROR
545
+ text = message || "This version of the app is out of date. Update it to keep going."
546
+ supported = body["supported"]
547
+ text += " (API versions served: #{supported.join(", ")}.)" if supported.is_a?(Array) && !supported.empty?
548
+ return Error.new(text, code: Error::UNSUPPORTED_API_VERSION, status: 400)
549
+ end
550
+ code = code&.upcase || { 400 => Error::INVALID, 409 => Error::CONFLICT, 422 => Error::INVALID,
551
+ 429 => Error::RATE_LIMITED }[status]
552
+ code ||= Error::INTERNAL if status >= 500
553
+ Error.http(status, code, message)
554
+ end
555
+ end
556
+
557
+ def rest_error_body(data)
558
+ decoded = JSON.parse(data.to_s)
559
+ decoded.is_a?(Hash) ? decoded : {}
560
+ rescue JSON::ParserError
561
+ {}
562
+ end
563
+
564
+ def decode_object(data)
565
+ decoded = JSON.parse(data.to_s)
566
+ raise Error.decoding("The response was not a JSON object.") unless decoded.is_a?(Hash)
567
+
568
+ decoded
569
+ rescue JSON::ParserError => e
570
+ raise Error.decoding(e.message)
571
+ end
572
+
573
+ def decode_credential(data)
574
+ Credential.from_h(decode_object(data))
575
+ rescue ArgumentError => e
576
+ raise Error.decoding(e.message)
577
+ end
578
+ end
579
+ end
580
+ end
@@ -2,6 +2,11 @@
2
2
 
3
3
  module Audience
4
4
  module Kit
5
- VERSION = "0.2.0"
5
+ # The gem's semantic version. It is versioned on its own, apart from the Swift and Kotlin SDKs' VERSION.
6
+ VERSION = "0.3.0"
7
+
8
+ # The API contract this SDK speaks, the date it was last broken: sent as +X-AudienceKit-API-Version+ on every
9
+ # request and kept on each {Credential}.
10
+ API_VERSION = "2026-10-11"
6
11
  end
7
12
  end