equipoise 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: de1fcce8a6fbfaed1a0009371d6350128ac310533cbbd52baf0f0883f8d9cdcf
4
+ data.tar.gz: d2ea1aced1956bba17728d81a0677900010b4ad8d041397756bd8fd09b0459f6
5
+ SHA512:
6
+ metadata.gz: d9a0dacc4037a20322ed758c1ee56999d50a8bde0585bb0e9bd47f4e363c52bdf0df121ef6b0d2bf4832705e54d2eb183633ebf15891333294cac45e1187de74
7
+ data.tar.gz: 8808b757de5b892e82a106162c77372d7e9baafce7a67ac9162d362a5751cf65ee023db04430409d25a9e410730c0bf3f55b541446d5d1e61d03b8af2c2bd8da
data/CHANGELOG.md ADDED
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `equipoise` gem are documented here. The format
4
+ follows [Keep a Changelog](https://keepachangelog.com/); the project uses
5
+ semantic versioning once published.
6
+
7
+ ## [Unreleased]
8
+
9
+ ### Added
10
+
11
+ - **Activity / event ingestion** — `contacts.record_activity(external_id:,
12
+ event_type:, label:, occurred_at:, metadata:)` posts an external event onto a
13
+ contact's timeline, plus `contacts.subscribe` / `contacts.unsubscribe`
14
+ convenience wrappers (the subscription events toggle `Contact#subscribed` and
15
+ log the change server-side).
16
+ - Producer-safety hardening (from AMP integration feedback):
17
+ - **Environment/key-prefix guard** — `Configuration#validate!` refuses an
18
+ `eq_test_` key pointed at the production host (test creds → live CRM) and an
19
+ `eq_live_` key pointed at localhost. Kills the "test key wrote into the real
20
+ CRM" footgun for every producer.
21
+ - **`Equipoise::Error#retryable?`** taxonomy — `true` for 429/5xx and any
22
+ `ConnectionError`, `false` for every 4xx. A producer's job becomes
23
+ `rescue Equipoise::Error => e; raise if e.retryable?`.
24
+ - **`Equipoise.disable!` / `enable!` / `disabled?`** test mode — when disabled,
25
+ the client short-circuits to a no-op before any network call or validation,
26
+ so a stray `EQUIPOISE_API_KEY` in a test env can't make a live call.
27
+ - Initial producer client (External CRM Sync, S12):
28
+ - `Equipoise.configure` / `Equipoise.client` with env-based, rotation-aware
29
+ credentials.
30
+ - `client.contacts.sync` / `batch_sync` (chunks to 500, deterministic per-chunk
31
+ `Idempotency-Key`) / `deactivate` / `find`.
32
+ - `client.custom_fields` declare/list/get/update/delete.
33
+ - Typed errors (`AuthenticationError`, `ForbiddenError`, `NotFoundError`,
34
+ `ConflictError`, `ValidationError#details`, `RateLimitError#retry_after`,
35
+ `ServerError`, `ConnectionError`).
36
+ - Bounded retry/backoff on 429 + 5xx + network errors; `use_ssl` derived from
37
+ the URL scheme (local `http` works).
38
+ - Optional Rails add-on: `Equipoise::Syncable` concern + `rails g
39
+ equipoise:install`.
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/NOTICE ADDED
@@ -0,0 +1,12 @@
1
+ Equipoise Ruby Client
2
+ Copyright 2026 Equipoise (Mind Tonic)
3
+
4
+ This product includes software developed at Equipoise.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this software except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ See the LICENSE file distributed with this software for the full terms.
data/README.md ADDED
@@ -0,0 +1,168 @@
1
+ # equipoise
2
+
3
+ Ruby client for the [Equipoise](https://app.equipoi.se) **External CRM Sync API**.
4
+
5
+ A "producer" (a Rails app like AMP, a Stripe importer, a spreadsheet job, …)
6
+ uses this gem to upsert its people into an Equipoise account's CRM as Contacts.
7
+ The gem is a **thin transport** — all business logic (matching, de-duplication,
8
+ tag reconciliation, custom-field coercion) lives server-side in the receiver's
9
+ `Crm::ContactSyncService`. This client just handles auth, JSON, idempotency,
10
+ bounded retry/backoff, and typed errors.
11
+
12
+ - **Contract:** [`EXTERNAL_CRM_SYNC_API.openapi.yaml`](../../documentation/integrations/EXTERNAL_CRM_SYNC_API.openapi.yaml) (OpenAPI 3.1)
13
+ - **Guide:** [`EXTERNAL_CRM_SYNC.md`](../../documentation/integrations/EXTERNAL_CRM_SYNC.md)
14
+
15
+ > Pre-1.0 and unpublished — consumed by AMP as a `path:`/git dependency first,
16
+ > published to RubyGems only once proven.
17
+
18
+ ## Install
19
+
20
+ ```ruby
21
+ # In the producer app's Gemfile
22
+ gem "equipoise", path: "../equipoise/gems/equipoise" # or git:
23
+ ```
24
+
25
+ ## Configure
26
+
27
+ `api_key` and `base_url` are read from `EQUIPOISE_API_KEY` / `EQUIPOISE_API_URL`
28
+ **automatically**, on every request — so rotating the secret in the environment
29
+ needs no redeploy. `configure` just sets the `source` (and any overrides):
30
+
31
+ ```ruby
32
+ Equipoise.configure do |c|
33
+ c.source = "AMP" # this producer's source id (case-sensitive)
34
+ end
35
+ ```
36
+
37
+ Assign `c.api_key` explicitly only if you source the secret elsewhere (e.g.
38
+ Rails credentials) — an explicit value is captured and is no longer
39
+ rotation-aware. For a trusted TLS-terminating internal endpoint reached over
40
+ plain HTTP, set `c.allow_insecure_http = true` (otherwise an `http://` URL to a
41
+ non-loopback host is refused, so the key is never sent in cleartext).
42
+
43
+ Under Rails, run `rails g equipoise:install` to generate
44
+ `config/initializers/equipoise.rb`.
45
+
46
+ ## Use
47
+
48
+ ```ruby
49
+ # Upsert one contact (201 created / 200 updated; no duplicate on email change).
50
+ res = Equipoise.client.contacts.sync(
51
+ external_id: user.id, email: user.email, name: user.name, tags: ["AMP"]
52
+ )
53
+ res.sync_status # => "created" | "updated"
54
+
55
+ # Safe retry of a single sync:
56
+ Equipoise.client.contacts.sync(
57
+ external_id: user.id, email: user.email, idempotency_key: request_id
58
+ )
59
+
60
+ # Batch backfill — chunks to ≤500/call, one bad item never fails the batch.
61
+ # It never raises mid-batch: per-item rejections and chunk-level transport
62
+ # failures both come back as failed items, so earlier successes are preserved.
63
+ result = Equipoise.client.contacts.batch_sync(
64
+ users.map { |u| { external_id: u.id, email: u.email } }
65
+ )
66
+ result.failed.each { |item| log(item[:external_id], item[:errors]) }
67
+
68
+ # Deactivate when someone leaves the producer (Contact is retained):
69
+ Equipoise.client.contacts.deactivate(external_id: user.id)
70
+
71
+ # Read back:
72
+ Equipoise.client.contacts.find(external_id: user.id)
73
+
74
+ # Record an external event on the contact's timeline:
75
+ Equipoise.client.contacts.record_activity(external_id: user.id, event_type: "completed_course", label: "Intro to Ruby")
76
+ # "subscribed"/"unsubscribed" toggle the contact's email subscription + log it:
77
+ Equipoise.client.contacts.unsubscribe(external_id: user.id)
78
+ Equipoise.client.contacts.subscribe(external_id: user.id)
79
+ ```
80
+
81
+ ### Errors
82
+
83
+ Everything inherits from `Equipoise::Error`:
84
+
85
+ ```ruby
86
+ begin
87
+ Equipoise.client.contacts.sync(external_id: u.id, email: u.email)
88
+ rescue Equipoise::ValidationError => e
89
+ e.details # field-level errors
90
+ rescue Equipoise::RateLimitError => e
91
+ sleep(e.retry_after || 1) # honor Retry-After (nil if the server sent none)
92
+ rescue Equipoise::AuthenticationError, Equipoise::ForbiddenError => e
93
+ # bad/expired key, missing scope, or source-pinned mismatch
94
+ end
95
+ ```
96
+
97
+ **Retry taxonomy.** Every error answers `#retryable?` (`true` for 429/5xx and
98
+ `ConnectionError`, `false` for 4xx), so a background job is trivially correct
99
+ without memorizing status codes:
100
+
101
+ ```ruby
102
+ class EquipoiseSyncJob < ApplicationJob
103
+ def perform(user) = Equipoise.client.contacts.sync(**user.equipoise_payload)
104
+ rescue Equipoise::Error => e
105
+ raise if e.retryable? # let the queue back off; permanent errors just discard
106
+ Rails.logger.warn("[equipoise] dropped: #{e.message}")
107
+ end
108
+ ```
109
+
110
+ ### Custom fields
111
+
112
+ Declare the typed fields your source owns (upsert by key); values then ride
113
+ along on a sync via `custom_fields:`:
114
+
115
+ ```ruby
116
+ Equipoise.client.custom_fields.declare(
117
+ key: "tier", field_type: "select", options: { choices: %w[gold silver] }, source: "AMP"
118
+ )
119
+ Equipoise.client.contacts.sync(external_id: user.id, email: user.email, custom_fields: { tier: "gold" })
120
+ ```
121
+
122
+ ### Rails models (optional)
123
+
124
+ ```ruby
125
+ class User < ApplicationRecord
126
+ include Equipoise::Syncable
127
+
128
+ def equipoise_external_id = id.to_s
129
+ def equipoise_contact_attributes
130
+ { email:, name: full_name, tags: ["AMP"] }
131
+ end
132
+ end
133
+ ```
134
+
135
+ The default `equipoise_sync!` posts inline on `after_commit` (create/update).
136
+ In production, override it to enqueue a job so a web request never blocks on the
137
+ round-trip. In development, ensure the queue runs inline or the post never fires.
138
+ Call `deactivate_from_equipoise` from your soft-delete path.
139
+
140
+ ## Testing (in a producer app)
141
+
142
+ Disable the gem in your test environment so a stray `EQUIPOISE_API_KEY` can never
143
+ make a live call — disabled calls short-circuit to a no-op before any network or
144
+ validation:
145
+
146
+ ```ruby
147
+ # spec/rails_helper.rb (or test env)
148
+ Equipoise.disable!
149
+ ```
150
+
151
+ ## Safety guards
152
+
153
+ - **Environment/key mismatch** — `validate!` refuses an `eq_test_` key aimed at
154
+ the production host, and an `eq_live_` key aimed at localhost. (Staging /
155
+ custom-domain hosts are not flagged.)
156
+ - **Cleartext** — refuses an `http://` base_url to any non-loopback host unless
157
+ `allow_insecure_http = true`.
158
+
159
+ ## Development
160
+
161
+ The spec suite is DB-less and Rails-less — it runs against a real loopback HTTP
162
+ mock server (`spec/support/mock_server.rb`), which is what proves `use_ssl` is
163
+ derived from the URL scheme rather than hardcoded.
164
+
165
+ ```bash
166
+ bundle install
167
+ bundle exec rspec
168
+ ```
@@ -0,0 +1,45 @@
1
+ # =============================================================================
2
+ # Equipoise::BatchResult
3
+ # =============================================================================
4
+ #
5
+ # The aggregated outcome of a batch_sync across all chunks. Each item mirrors the
6
+ # server's per-item shape — { external_id:, status:, ok:, errors? } — with symbol
7
+ # keys for ergonomic walking:
8
+ #
9
+ # result = client.contacts.batch_sync(records)
10
+ # result.failed.each { |item| retry_one(item[:external_id], item[:errors]) }
11
+ #
12
+ # Used by: Equipoise::Contacts#batch_sync
13
+ # =============================================================================
14
+
15
+ module Equipoise
16
+ class BatchResult
17
+ include Enumerable
18
+
19
+ attr_reader :items
20
+
21
+ def initialize(raw_items)
22
+ @items = Array(raw_items).map { |item| Util.symbolize_keys(item) }
23
+ end
24
+
25
+ def each(&block)
26
+ items.each(&block)
27
+ end
28
+
29
+ def size
30
+ items.size
31
+ end
32
+
33
+ def succeeded
34
+ items.select { |item| item[:ok] }
35
+ end
36
+
37
+ def failed
38
+ items.reject { |item| item[:ok] }
39
+ end
40
+
41
+ def all_ok?
42
+ items.all? { |item| item[:ok] }
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,188 @@
1
+ # =============================================================================
2
+ # Equipoise::Client
3
+ # =============================================================================
4
+ #
5
+ # The HTTP transport. Holds a Configuration, exposes the resource namespaces
6
+ # (`#contacts`, `#custom_fields`), and performs requests with:
7
+ #
8
+ # - Bearer auth (`Authorization: Bearer <prefix>.<secret>`) + JSON headers
9
+ # - TLS chosen from the URL scheme — `use_ssl = uri.scheme == "https"` — so a
10
+ # local `http://localhost:3000` dev loop works. (Configuration#validate!
11
+ # refuses an http:// base_url to a non-loopback host so the key is never
12
+ # sent in cleartext.)
13
+ # - bounded retry with backoff on transient failures (429 + 5xx + network),
14
+ # never on a 4xx the producer must handle (422/409/404/403). Backoff honors
15
+ # a server Retry-After and is capped by max_retry_backoff either way.
16
+ # - typed errors: every non-2xx becomes an ApiError subclass; every transport
17
+ # failure becomes a ConnectionError. Nothing raw escapes the gem.
18
+ #
19
+ # No business logic — the receiver (Crm::ContactSyncService) owns all of it.
20
+ #
21
+ # Used by: Equipoise.client, Equipoise::Contacts, Equipoise::CustomFields
22
+ # =============================================================================
23
+
24
+ module Equipoise
25
+ class Client
26
+ RETRYABLE_STATUSES = [429, 500, 502, 503, 504].freeze
27
+
28
+ # Transient transport errors worth retrying.
29
+ RETRYABLE_NETWORK_ERRORS = [
30
+ Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH,
31
+ Net::OpenTimeout, Net::ReadTimeout, SocketError, EOFError, IOError
32
+ ].freeze
33
+
34
+ # Other transport failures — wrapped into ConnectionError but NOT retried
35
+ # (a TLS cert failure won't fix itself on a retry). Listed after the
36
+ # retryable rescue, so the more-specific list wins.
37
+ WRAPPABLE_NETWORK_ERRORS = [
38
+ OpenSSL::SSL::SSLError, SystemCallError, Net::ProtocolError, Net::HTTPBadResponse
39
+ ].freeze
40
+
41
+ attr_reader :config
42
+
43
+ def initialize(config = Equipoise.configuration)
44
+ @config = config
45
+ end
46
+
47
+ def contacts
48
+ @contacts ||= Contacts.new(self)
49
+ end
50
+
51
+ def custom_fields
52
+ @custom_fields ||= CustomFields.new(self)
53
+ end
54
+
55
+ # — Claude authored — the single request chokepoint. Returns a Response on
56
+ # 2xx; raises a typed ApiError (or ConnectionError) otherwise.
57
+ def request(method, path, body: nil, query: nil, headers: {})
58
+ return null_response if config.disabled? # test-mode short-circuit (#5) — before validate! or any I/O
59
+
60
+ config.validate!
61
+ uri = build_uri(path, query)
62
+ attempt = 0
63
+
64
+ loop do
65
+ response =
66
+ begin
67
+ perform(method, uri, body, headers)
68
+ rescue *RETRYABLE_NETWORK_ERRORS => e
69
+ raise wrap_connection_error(e) if attempt >= config.max_retries
70
+
71
+ attempt += 1
72
+ backoff(attempt, nil)
73
+ next
74
+ rescue *WRAPPABLE_NETWORK_ERRORS => e
75
+ raise wrap_connection_error(e)
76
+ end
77
+
78
+ return response if response.success?
79
+
80
+ if retryable?(response.status) && attempt < config.max_retries
81
+ attempt += 1
82
+ backoff(attempt, response)
83
+ next
84
+ end
85
+
86
+ raise log_error(ApiError.from_response(response))
87
+ end
88
+ end
89
+
90
+ private
91
+
92
+ def perform(method, uri, body, extra_headers)
93
+ http = build_http(uri)
94
+ request = build_request(method, uri, body, extra_headers)
95
+ raw = http.start { |conn| conn.request(request) }
96
+ Response.new(status: raw.code.to_i, headers: header_hash(raw), body: parse_body(raw.body))
97
+ end
98
+
99
+ # The use_ssl fix lives here: derive TLS from the scheme, never hardcode it.
100
+ def build_http(uri)
101
+ Net::HTTP.new(uri.host, uri.port).tap do |http|
102
+ http.use_ssl = uri.scheme == "https"
103
+ http.open_timeout = config.open_timeout
104
+ http.read_timeout = config.read_timeout
105
+ end
106
+ end
107
+
108
+ def build_request(method, uri, body, extra_headers)
109
+ klass = {
110
+ get: Net::HTTP::Get, post: Net::HTTP::Post,
111
+ patch: Net::HTTP::Patch, delete: Net::HTTP::Delete
112
+ }.fetch(method)
113
+
114
+ request = klass.new(uri.request_uri)
115
+ request["Authorization"] = "Bearer #{config.api_key}"
116
+ request["Accept"] = "application/json"
117
+ request["User-Agent"] = config.user_agent
118
+ extra_headers.each { |key, value| request[key] = value }
119
+
120
+ if body
121
+ request["Content-Type"] = "application/json"
122
+ request.body = JSON.generate(body)
123
+ end
124
+
125
+ request
126
+ end
127
+
128
+ def build_uri(path, query)
129
+ base = config.base_url.to_s.sub(%r{/\z}, "")
130
+ uri = URI.parse("#{base}#{path}")
131
+ uri.query = URI.encode_www_form(query) if query && !query.empty?
132
+ uri
133
+ end
134
+
135
+ def header_hash(raw)
136
+ {}.tap { |h| raw.each_header { |key, value| h[key.downcase] = value } }
137
+ end
138
+
139
+ def parse_body(raw_body)
140
+ return nil if raw_body.nil? || raw_body.empty?
141
+
142
+ JSON.parse(raw_body)
143
+ rescue JSON::ParserError
144
+ { "raw" => raw_body }
145
+ end
146
+
147
+ def retryable?(status)
148
+ RETRYABLE_STATUSES.include?(status)
149
+ end
150
+
151
+ def backoff(attempt, response)
152
+ delay = backoff_delay(attempt, response)
153
+ log_retry(attempt, response, delay)
154
+ sleep(delay) if delay.positive?
155
+ end
156
+
157
+ # Honor a server Retry-After when present, else exponential from
158
+ # retry_backoff_base — capped by max_retry_backoff in BOTH cases so a raised
159
+ # max_retries can never block longer than the configured ceiling.
160
+ def backoff_delay(attempt, response)
161
+ server = response&.retry_after
162
+ delay = server || (config.retry_backoff_base * (2**(attempt - 1)))
163
+ [delay, config.max_retry_backoff].min
164
+ end
165
+
166
+ def wrap_connection_error(error)
167
+ log_error(ConnectionError.new(error.message))
168
+ end
169
+
170
+ def log_retry(attempt, response, delay)
171
+ return unless config.logger
172
+
173
+ reason = response ? "HTTP #{response.status}" : "network error"
174
+ config.logger.warn("[equipoise] retry #{attempt}/#{config.max_retries} after #{reason}; waiting #{delay}s")
175
+ end
176
+
177
+ def log_error(error)
178
+ config.logger&.warn("[equipoise] #{error.class}: #{error.message}")
179
+ error
180
+ end
181
+
182
+ # Benign no-op response returned when the gem is disabled (test mode). Shaped
183
+ # like a normal envelope so callers (and Syncable) don't crash.
184
+ def null_response
185
+ Response.new(status: 200, headers: {}, body: { "data" => {}, "meta" => { "disabled" => true } })
186
+ end
187
+ end
188
+ end