openhub-bo-core 0.1.0-x86_64-linux

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: a67a9391c368677c150636065e2ddb0c9255305919e43d06106879e6bb86ee1c
4
+ data.tar.gz: 298e16c0b9e41b9aaf92eca45601ce33cfb9d79b34e7f7f8cc3c4c46bafc178e
5
+ SHA512:
6
+ metadata.gz: b43eb5a5fd708efee02452e4a3821431725a7bdd5b315fc4e9ca353b2bf213baa1a8c48a1c991f302341bf57ccd8f3b9c8614f1df59bf96e7b480cb046451a8c
7
+ data.tar.gz: 55e992a3dfebcb499733c22556e4fe0cc787eb556e2e45f8b13dea9739e8f5599e9d25e91323337b9edf9fec755e4f38a8c1d40726f104b1aedcf7ecbcce86f3
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,8 @@
1
+ openhub-bo
2
+ Copyright 2026 Felix Daniel Coca Calvimontes
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ This is an unofficial integration. "Red Enlace", "ATC" and "OpenHub" are names
7
+ and trademarks of their respective owners; this project is not affiliated with,
8
+ endorsed by or supported by them.
data/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # openhub-bo-core
2
+
3
+ Base compartida de las gemas `openhub-bo` para **Red Enlace (ATC) OpenHub**, Bolivia:
4
+ sesión OAuth2 con caché de token (thread-safe), transporte HTTP (`Net::HTTP`, sin
5
+ dependencias), errores tipados y tipos comunes. Normalmente llega como dependencia
6
+ de cada producto.
7
+
8
+ ```ruby
9
+ require "openhub_bo/core"
10
+
11
+ session = OpenhubBo::Core::Session.new(ENV["CLIENT_ID"], ENV["CLIENT_SECRET"], environment: :sandbox)
12
+ # pásala a OpenhubBo::Qr::QrClient.new(session), etc. Todos comparten el token.
13
+ ```
14
+
15
+ - Errores: `Core::Error` → `ValidationError#field`, `AuthenticationError#status`,
16
+ `ApiError#status/#code/#errors/#retryable?`, `TransportError#maybe_sent`,
17
+ `AmbiguousOutcomeError#operation/#code` (una operación no idempotente pudo
18
+ aplicarse), `DecodeError`, `WebhookAuthError`.
19
+ - Montos: entradas `BigDecimal`, `Integer` o `String` (`Float` → `TypeError`); salidas `BigDecimal`.
20
+ - Transporte propio: cualquier objeto con `perform(request) -> Core::Response`.
21
+ - Tests: `require "openhub_bo/core/testing"` → `Core::Testing::MockGateway`.
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenhubBo
4
+ module Core
5
+ ApiFieldError = Data.define(:message, :field, :code)
6
+
7
+ # Base class for every error raised by openhub-bo.
8
+ class Error < StandardError
9
+ # Whether repeating the same call later may succeed.
10
+ def retryable? = false
11
+ end
12
+
13
+ # Input rejected locally, before calling OpenHub.
14
+ class ValidationError < Error
15
+ attr_reader :field
16
+
17
+ def initialize(message, field:)
18
+ super("invalid `#{field}`: #{message}")
19
+ @field = field
20
+ end
21
+ end
22
+
23
+ # Credentials or access token rejected by OpenHub.
24
+ class AuthenticationError < Error
25
+ attr_reader :status
26
+
27
+ def initialize(message, status:)
28
+ super("authentication failed (HTTP #{status}): #{message}")
29
+ @status = status
30
+ end
31
+ end
32
+
33
+ # OpenHub answered with an error.
34
+ class ApiError < Error
35
+ attr_reader :status, :errors
36
+
37
+ def initialize(message, status:, errors: [], retryable: false)
38
+ super("OpenHub error (HTTP #{status}): #{message}")
39
+ @status = status
40
+ @errors = errors
41
+ @retryable = retryable
42
+ end
43
+
44
+ def retryable? = @retryable
45
+
46
+ # Code of the first field error, e.g. "TRANSACCION_NO_ENCONTRADA".
47
+ def code = errors.map(&:code).compact.first
48
+ end
49
+
50
+ # The response could not be understood.
51
+ class DecodeError < Error; end
52
+
53
+ # Incoming webhook did not carry the expected secret.
54
+ class WebhookAuthError < Error; end
55
+
56
+ # Network failure. `maybe_sent` is false when the request never left
57
+ # (connection refused, connect timeout): retrying is then always safe.
58
+ class TransportError < Error
59
+ attr_reader :maybe_sent
60
+
61
+ def initialize(message, maybe_sent:)
62
+ super(message)
63
+ @maybe_sent = maybe_sent
64
+ end
65
+
66
+ def retryable? = true
67
+ end
68
+
69
+ # A non-idempotent call (generating a QR, paying a payout...) may or may not
70
+ # have been applied: the response was lost, or OpenHub reported the result as
71
+ # unconfirmed (payout codes 94/96). Deliberately not a TransportError so
72
+ # generic retry loops do not repeat it. Query the status before retrying.
73
+ class AmbiguousOutcomeError < Error
74
+ attr_reader :operation, :errors
75
+
76
+ def initialize(operation, cause, errors: [])
77
+ super("outcome of `#{operation}` is unknown: #{cause}")
78
+ @operation = operation
79
+ @errors = errors
80
+ end
81
+
82
+ def code = errors.map(&:code).compact.first
83
+ end
84
+
85
+ # Contract violation between a gem and its native extension (a bug).
86
+ class CoreError < Error; end
87
+
88
+ module_function
89
+
90
+ # Maps an error from the native core; `op` is the native op name
91
+ # (e.g. "payouts.pay.parse").
92
+ def error_from_core(data, op = "")
93
+ kind = data["kind"]
94
+ message = data.fetch("message", "unknown error")
95
+ errors = Array(data["errors"]).map do |e|
96
+ ApiFieldError.new(message: e["message"], field: e["field"], code: e["code"])
97
+ end
98
+ case kind
99
+ when "validation" then ValidationError.new(message, field: data["field"])
100
+ when "authentication" then AuthenticationError.new(message, status: data["status"])
101
+ when "api"
102
+ ApiError.new(message, status: data["status"], errors: errors, retryable: data["retryable"] == true)
103
+ when "ambiguous"
104
+ AmbiguousOutcomeError.new(op.sub(/\.(build|parse)\z/, ""), message, errors: errors)
105
+ when "decode" then DecodeError.new(message)
106
+ when "webhook_auth" then WebhookAuthError.new(message)
107
+ else CoreError.new(message)
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "time"
5
+
6
+ module OpenhubBo
7
+ module Core
8
+ module Environment
9
+ DEVELOPMENT = :development
10
+ SANDBOX = :sandbox
11
+ PRODUCTION = :production
12
+ ALL = [DEVELOPMENT, SANDBOX, PRODUCTION].freeze
13
+ end
14
+
15
+ # Status shared by every product family (symbols); `raw_status` keeps the original.
16
+ module PaymentStatus
17
+ ALL = %i[pending processing paid cancelled expired rejected reversed error unknown].freeze
18
+ NOT_FINAL = %i[pending processing unknown].freeze
19
+
20
+ def self.final?(status) = !NOT_FINAL.include?(status)
21
+ end
22
+
23
+ # OpenHub timestamps carry no offset: they are Bolivia time.
24
+ BOLIVIA_OFFSET = "-04:00"
25
+
26
+ # Where ATC must POST notifications. ATC sends `key: value` as a header; it is
27
+ # the only authentication, so use a long random value.
28
+ Webhook = Data.define(:url, :value, :key) do
29
+ def initialize(url:, value:, key: "x-api-key") = super
30
+
31
+ def to_wire = { "url" => url, "key" => key, "value" => value }
32
+
33
+ def inspect = "#<#{self.class.name} url=#{url.inspect} key=#{key.inspect} value=[FILTERED]>"
34
+ alias_method :to_s, :inspect
35
+ end
36
+
37
+ module_function
38
+
39
+ # Amounts cross the native boundary as exact decimal strings.
40
+ def amount(value)
41
+ case value
42
+ when BigDecimal then value.to_s("F")
43
+ when Integer then value.to_s
44
+ when String then value
45
+ else
46
+ raise TypeError,
47
+ "amount must be BigDecimal, Integer or String, not #{value.class} " \
48
+ "(floats are rejected to avoid rounding errors)"
49
+ end
50
+ end
51
+
52
+ def seconds(value)
53
+ raise TypeError, "expected Integer seconds, not #{value.class}" unless value.is_a?(Integer)
54
+
55
+ value
56
+ end
57
+
58
+ def iso_date(value) = value.is_a?(Date) ? value.iso8601 : value
59
+
60
+ def decimal(value) = value.nil? ? nil : BigDecimal(value)
61
+
62
+ # Parses an OpenHub timestamp, assuming Bolivia time when it has no offset.
63
+ def local_time(value)
64
+ return nil if value.nil? || value.empty?
65
+
66
+ has_offset = value.match?(/(Z|[+-]\d{2}:?\d{2})\z/)
67
+ Time.iso8601(has_offset ? value : value.tr(" ", "T") + BOLIVIA_OFFSET)
68
+ rescue ArgumentError
69
+ nil
70
+ end
71
+
72
+ # Defines an immutable value class from the core's snake_case JSON.
73
+ #
74
+ # Payer = Core.model(:name, :document_id)
75
+ # Qr = Core.model(:reference, :amount, :payer, casts: { amount: :decimal, payer: Payer })
76
+ #
77
+ # Casts: :decimal (BigDecimal), :symbol, :time (Bolivia time), a model class,
78
+ # or [ModelClass] for lists.
79
+ def model(*fields, casts: {}, &block)
80
+ klass = Data.define(*fields, &block)
81
+ klass.define_singleton_method(:from_h) do |hash|
82
+ return nil if hash.nil?
83
+
84
+ attrs = fields.to_h { |field| [field, Core.cast(hash[field.to_s], casts[field])] }
85
+ new(**attrs)
86
+ end
87
+ klass
88
+ end
89
+
90
+ def cast(value, how)
91
+ return value if how.nil? || value.nil?
92
+
93
+ case how
94
+ when :decimal then BigDecimal(value.to_s)
95
+ when :symbol then value.to_sym
96
+ when :time then local_time(value)
97
+ when Array then value.map { |item| how.first.from_h(item) }
98
+ else how.from_h(value)
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenhubBo
4
+ module Core
5
+ # A native extension exposing `call(op, payload) -> String`. Checks the
6
+ # protocol on load and caches the operation catalog from `describe`, so
7
+ # declared operations are validated when the gem is required.
8
+ class NativeBridge
9
+ attr_reader :operations, :version
10
+
11
+ def initialize(mod)
12
+ protocol = mod.protocol_version
13
+ unless protocol == SUPPORTED_PROTOCOL
14
+ raise LoadError,
15
+ "#{mod} speaks core protocol #{protocol}, this gem expects #{SUPPORTED_PROTOCOL}; " \
16
+ "install matching openhub-bo versions"
17
+ end
18
+ @mod = mod
19
+ @version = mod.version
20
+ @operations = invoke("describe", {}).to_h { |entry| [entry["name"], entry] }.freeze
21
+ end
22
+
23
+ def invoke(op, payload)
24
+ result = JSON.parse(@mod.call(op, JSON.generate(payload)))
25
+ return result["value"] if result["ok"]
26
+
27
+ raise Core.error_from_core(result["error"], op)
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenhubBo
4
+ module Core
5
+ # An HTTP endpoint implemented by a native extension. Declaring one with a
6
+ # name the extension does not know raises LoadError at require time.
7
+ class Op
8
+ attr_reader :native, :name
9
+
10
+ def initialize(native, name, &decode)
11
+ info = native.operations[name]
12
+ raise LoadError, "native extension has no operation `#{name}`" unless info && info["kind"] == "operation"
13
+
14
+ @native = native
15
+ @name = name
16
+ @decode = decode || ->(value) { value }
17
+ @info = info
18
+ end
19
+
20
+ def idempotent? = @info["idempotent"] == true
21
+
22
+ # Client timeout (seconds) recommended by ATC for this endpoint, if any.
23
+ def timeout = @info["timeout_secs"]
24
+
25
+ def build(config, token, input)
26
+ request = native.invoke("#{name}.build", { "config" => config, "token" => token, "input" => input })
27
+ request["timeout"] = timeout if timeout
28
+ request
29
+ end
30
+
31
+ def parse(input, response)
32
+ @decode.call(native.invoke("#{name}.parse", { "input" => input, "response" => response.to_wire }))
33
+ end
34
+ end
35
+
36
+ # A pure native function (no HTTP), e.g. webhook parsing.
37
+ class Handler
38
+ def initialize(native, name, &decode)
39
+ info = native.operations[name]
40
+ raise LoadError, "native extension has no handler `#{name}`" unless info && info["kind"] == "handler"
41
+
42
+ @native = native
43
+ @name = name
44
+ @decode = decode || ->(value) { value }
45
+ end
46
+
47
+ def call(input) = @decode.call(@native.invoke(@name, input))
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenhubBo
4
+ module Core
5
+ NATIVE = NativeBridge.new(Native)
6
+ TOKEN = Op.new(NATIVE, "token")
7
+
8
+ # Credentials, token cache and execution of operations. Share one session
9
+ # between product clients (QrClient.new(session), PixClient.new(session)...)
10
+ # so they reuse the OAuth token. Thread-safe.
11
+ class Session
12
+ attr_reader :environment
13
+
14
+ def initialize(client_id, client_secret = nil, basic_token: nil, environment: Environment::SANDBOX,
15
+ base_url: nil, timeout: 30, transport: nil)
16
+ @environment = environment.to_sym
17
+ unless Environment::ALL.include?(@environment)
18
+ raise ValidationError.new("must be one of #{Environment::ALL.join(', ')}", field: "environment")
19
+ end
20
+
21
+ @config = {
22
+ "client_id" => client_id,
23
+ "client_secret" => client_secret,
24
+ "basic_token" => basic_token,
25
+ "environment" => @environment.to_s,
26
+ "base_url" => base_url
27
+ }
28
+ @transport = transport || NetHttpTransport.new(timeout: timeout)
29
+ @token = nil
30
+ @lock = Mutex.new
31
+ # Fail fast on missing credentials instead of at the first request.
32
+ TOKEN.build(@config, nil, token_input)
33
+ end
34
+
35
+ # Runs `op`: token, build, send, parse; refreshes a rejected token once.
36
+ def execute(op, input)
37
+ 2.times do |attempt|
38
+ token = ensure_token
39
+ response = deliver(op, op.build(@config, token, input))
40
+ begin
41
+ return op.parse(input, response)
42
+ rescue AuthenticationError
43
+ raise if attempt == 1
44
+
45
+ invalidate(token)
46
+ end
47
+ end
48
+ end
49
+
50
+ def close = @transport.close
51
+
52
+ def inspect = "#<#{self.class.name} client_id=#{@config['client_id'].inspect} environment=#{@environment}>"
53
+ alias_method :to_s, :inspect
54
+
55
+ private
56
+
57
+ def ensure_token
58
+ @lock.synchronize do
59
+ token = @token
60
+ return token if token && Time.now.to_i < token["expires_at"]
61
+
62
+ @token = TOKEN.parse(token_input, deliver(TOKEN, TOKEN.build(@config, nil, token_input)))
63
+ end
64
+ end
65
+
66
+ def invalidate(token)
67
+ @lock.synchronize { @token = nil if @token && @token["access_token"] == token["access_token"] }
68
+ end
69
+
70
+ def deliver(op, request)
71
+ @transport.perform(request)
72
+ rescue TransportError => e
73
+ raise AmbiguousOutcomeError.new(op.name, e) if e.maybe_sent && !op.idempotent?
74
+
75
+ raise
76
+ end
77
+
78
+ def token_input = { "now" => Time.now.to_i }
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "openhub_bo/core"
5
+
6
+ module OpenhubBo
7
+ module Core
8
+ module Testing
9
+ # In-memory fake of the OpenHub gateway (Sensedia): handles the OAuth token
10
+ # and the access_token/client_id check like the real gateway; tests or
11
+ # product gems register routes on top. Use it as a Session transport:
12
+ #
13
+ # gateway = MockGateway.new
14
+ # gateway.route("GET", %r{/qr/simple/v2/verify/(\d+)\z}) { |req, m| Response.new(status: 200, body: "...") }
15
+ # session = gateway.session
16
+ class MockGateway
17
+ BASE_URL = "https://openhub.mock"
18
+ TOKEN_PATH = "/oauth-client-credentials/access-token"
19
+
20
+ attr_reader :client_id, :client_secret, :requests, :token_requests
21
+
22
+ def initialize(client_id: "test-client", client_secret: "test-secret", token_ttl: 3600)
23
+ @client_id = client_id
24
+ @client_secret = client_secret
25
+ @token_ttl = token_ttl
26
+ @requests = []
27
+ @token_requests = 0
28
+ @tokens = []
29
+ @routes = []
30
+ end
31
+
32
+ def route(method, pattern, &handler)
33
+ @routes << [method.to_s.upcase, pattern, handler]
34
+ self
35
+ end
36
+
37
+ # Answers matching requests with a fixed status and body.
38
+ def stub(method, pattern, status:, body:)
39
+ route(method, pattern) { Response.new(status: status, body: body) }
40
+ end
41
+
42
+ def session(client_secret: @client_secret, **kwargs)
43
+ Session.new(@client_id, client_secret, base_url: BASE_URL, transport: self, **kwargs)
44
+ end
45
+
46
+ def revoke_tokens = @tokens.clear
47
+
48
+ def perform(request)
49
+ @requests << request
50
+ path = URI(request["url"]).path
51
+ return token_response(request) if path.end_with?(TOKEN_PATH)
52
+ return Response.new(status: 401, body: "Access Token in the request, identified by HEADER access_token, is invalid.") unless authorized?(request)
53
+
54
+ @routes.each do |method, pattern, handler|
55
+ next unless request["method"] == method && (match = pattern.match(path))
56
+
57
+ return handler.call(request, match)
58
+ end
59
+ Response.new(status: 404, body: JSON.generate({ "success" => false, "message" => "Not found", "errors" => [] }))
60
+ end
61
+
62
+ def close; end
63
+
64
+ private
65
+
66
+ def token_response(request)
67
+ @token_requests += 1
68
+ expected = "Basic #{["#{@client_id}:#{@client_secret}"].pack("m0")}"
69
+ unless request["headers"]["Authorization"] == expected
70
+ return Response.new(status: 401, body: JSON.generate({ "error" => "invalid_client", "error_description" => "Bad credentials" }))
71
+ end
72
+
73
+ token = SecureRandom.uuid
74
+ @tokens << token
75
+ # Sandbox answers 201 with token_type "access_token" and no scope.
76
+ Response.new(status: 201, body: JSON.generate({ "access_token" => token, "token_type" => "access_token", "expires_in" => @token_ttl }))
77
+ end
78
+
79
+ def authorized?(request)
80
+ @tokens.include?(request["headers"]["access_token"]) && request["headers"]["client_id"] == @client_id
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module OpenhubBo
8
+ module Core
9
+ Response = Data.define(:status, :body) do
10
+ def to_wire = { "status" => status, "body" => body }
11
+ end
12
+
13
+ # Sends requests built by the native core. Any object responding to
14
+ # `perform(request) -> Response` works: inject your own for proxies,
15
+ # logging or fakes. `request` is {"method", "url", "headers", "body",
16
+ # "timeout"?}; raise TransportError on network failures.
17
+ class NetHttpTransport
18
+ # Failures where the request provably never reached the server.
19
+ NOT_SENT = [
20
+ Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Net::OpenTimeout, SocketError
21
+ ].freeze
22
+ MAYBE_SENT = [
23
+ Net::ReadTimeout, Net::WriteTimeout, EOFError, IOError, Errno::ECONNRESET, Errno::EPIPE,
24
+ OpenSSL::SSL::SSLError
25
+ ].freeze
26
+
27
+ def initialize(timeout: 30, open_timeout: 10)
28
+ @timeout = timeout
29
+ @open_timeout = open_timeout
30
+ end
31
+
32
+ def perform(request)
33
+ uri = URI(request["url"])
34
+ http = Net::HTTP.new(uri.host, uri.port)
35
+ http.use_ssl = uri.scheme == "https"
36
+ http.open_timeout = @open_timeout
37
+ http.read_timeout = request["timeout"] || @timeout
38
+ http.write_timeout = request["timeout"] || @timeout
39
+ body = request["body"]
40
+ message = Net::HTTPGenericRequest.new(
41
+ request["method"], !body.nil?, true, uri.request_uri, request["headers"]
42
+ )
43
+ message.body = body if body
44
+ response = http.start { |conn| conn.request(message) }
45
+ Response.new(status: response.code.to_i, body: response.body.to_s.dup.force_encoding(Encoding::UTF_8))
46
+ rescue *NOT_SENT => e
47
+ raise TransportError.new("#{e.class}: #{e.message}", maybe_sent: false)
48
+ rescue *MAYBE_SENT => e
49
+ raise TransportError.new("#{e.class}: #{e.message}", maybe_sent: true)
50
+ end
51
+
52
+ def close; end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenhubBo
4
+ module Core
5
+ VERSION = "0.1.0"
6
+ # Core FFI protocol this Ruby code speaks (see `openhub_bo_core::ffi`).
7
+ SUPPORTED_PROTOCOL = 2
8
+ end
9
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Shared foundation of the openhub-bo gems: session, transport, errors and
4
+ # common types for the Red Enlace (ATC) OpenHub APIs.
5
+ require "bigdecimal"
6
+ require "json"
7
+
8
+ require_relative "core/version"
9
+ require_relative "core/errors"
10
+ require_relative "core/models"
11
+ require_relative "core/native_bridge"
12
+ require_relative "core/op"
13
+ require_relative "core/transport"
14
+ begin
15
+ # Precompiled gems ship one binary per Ruby minor version.
16
+ require "openhub_bo/core/#{RUBY_VERSION[/\d+\.\d+/]}/openhub_bo_core"
17
+ rescue LoadError
18
+ require "openhub_bo/core/openhub_bo_core"
19
+ end
20
+ require_relative "core/session"
metadata ADDED
@@ -0,0 +1,108 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: openhub-bo-core
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: x86_64-linux
6
+ authors:
7
+ - Felix Daniel Coca Calvimontes
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-10-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bigdecimal
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '3.1'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '5'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '3.1'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '5'
33
+ - !ruby/object:Gem::Dependency
34
+ name: json
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '2.6'
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: '4'
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '2.6'
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '4'
53
+ description: Sesión OAuth, transporte, errores y tipos compartidos de los clientes
54
+ openhub-bo para Red Enlace (ATC) OpenHub, Bolivia. Núcleo en Rust compartido con
55
+ los paquetes openhub-bo de Python y TypeScript. Integración no oficial, sin afiliación
56
+ con Red Enlace (ATC).
57
+ email:
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - LICENSE
63
+ - NOTICE
64
+ - README.md
65
+ - lib/openhub_bo/core.rb
66
+ - lib/openhub_bo/core/3.2/openhub_bo_core.so
67
+ - lib/openhub_bo/core/3.3/openhub_bo_core.so
68
+ - lib/openhub_bo/core/3.4/openhub_bo_core.so
69
+ - lib/openhub_bo/core/4.0/openhub_bo_core.so
70
+ - lib/openhub_bo/core/errors.rb
71
+ - lib/openhub_bo/core/models.rb
72
+ - lib/openhub_bo/core/native_bridge.rb
73
+ - lib/openhub_bo/core/op.rb
74
+ - lib/openhub_bo/core/session.rb
75
+ - lib/openhub_bo/core/testing.rb
76
+ - lib/openhub_bo/core/transport.rb
77
+ - lib/openhub_bo/core/version.rb
78
+ homepage: https://github.com/drkpkg/openhub-bo-integration
79
+ licenses:
80
+ - Apache-2.0
81
+ metadata:
82
+ rubygems_mfa_required: 'true'
83
+ source_code_uri: https://github.com/drkpkg/openhub-bo-integration
84
+ bug_tracker_uri: https://github.com/drkpkg/openhub-bo-integration/issues
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '3.2'
94
+ - - "<"
95
+ - !ruby/object:Gem::Version
96
+ version: 4.1.dev
97
+ required_rubygems_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '0'
102
+ requirements: []
103
+ rubygems_version: 3.5.23
104
+ signing_key:
105
+ specification_version: 4
106
+ summary: Sesión OAuth, transporte, errores y tipos compartidos de los clientes openhub-bo
107
+ para Red Enlace (ATC) OpenHub, Bolivia
108
+ test_files: []