cloud_events 0.8.2 → 0.9.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: aac5d146b0b5adbac5c05de9af2e135046f0178baea94dea90005b22934c5b49
4
- data.tar.gz: efce8edc6fcc07014e0183c87d955ea16ff5a44a5fac197e45a30f730981c939
3
+ metadata.gz: 716373fdabd76c9559f81defb7af5c8e8f460a1cb71d6b3ac51df1b2a90217e5
4
+ data.tar.gz: 3960c652157b7d9ee652112d840ae4c2ae5cf2e4f8490b8334b62578847007ad
5
5
  SHA512:
6
- metadata.gz: 03c3c93e3ca7e49a67a8366c29f502466848a6e28f418c1ab9621f3dcc3dc050556148bab50e27109337f7bba70dc5c7ddb17e08729e79bbedd599b19f0be11c
7
- data.tar.gz: d0fa89577d80fd1be5ab8d48689371a033da8b19439c24b1750b5ddc0c4d115e642bc19cc2b04f34ccca82b519f186e41f52e94a885c05a50a2387873ae1d4fb
6
+ metadata.gz: 8053f2c1f19ca50cab810d6c5b80982e72e3ffcff3f578ac2a65243243255508739e1653c91e4b9caa7688fe552eec87479634c8fdaececf5855928eb12232e4
7
+ data.tar.gz: d30dc5cde096d2d8f0a4f439d576efcd73bcffb2ba880930bffd14ea4c118f55520cc3ffa98b6d0d1ece942ee0ecdbf0be9e1eb73c4a629858d086a6a24d4fe6
data/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ### v0.9.0 / 2026-03-12
4
+
5
+ * ADDED: Added an implementation of Kafka Binding
6
+
7
+ ### v0.8.3 / 2026-01-15
8
+
9
+ * FIXED: Fixed default charset behavior for various non-text/plain content types
10
+
3
11
  ### v0.8.2 / 2025-11-30
4
12
 
5
13
  * DOCS: Fixed a few typos in documentation and error messages
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.
@@ -22,17 +22,15 @@ module CloudEvents
22
22
  #
23
23
  # @param string [String] Content-Type header value in RFC 2045 format
24
24
  # @param default_charset [String] Optional. The charset to use if none is
25
- # specified. Defaults to `us-ascii`.
25
+ # specified. Defaults to `utf-8` for all types other than `text/plain`
26
+ # for which it defaults to `us-ascii`.
26
27
  #
27
28
  def initialize(string, default_charset: nil)
28
29
  @string = string.to_s
29
- @media_type = "text"
30
- @subtype_base = @subtype = "plain"
31
- @subtype_format = nil
30
+ @media_type = @subtype = @subtype_base = @subtype_format = @charset = nil
32
31
  @params = []
33
- @charset = default_charset || "us-ascii"
34
32
  @error_message = nil
35
- parse(consume_comments(@string.strip))
33
+ parse(consume_comments(@string.strip), default_charset)
36
34
  @canonical_string = "#{@media_type}/#{@subtype}" +
37
35
  @params.map { |k, v| "; #{k}=#{maybe_quote(v)}" }.join
38
36
  full_freeze
@@ -86,8 +84,10 @@ module CloudEvents
86
84
  attr_reader :params
87
85
 
88
86
  ##
89
- # The charset, defaulting to "us-ascii" if none is explicitly set.
90
- # @return [String]
87
+ # Returns the charset, which may be an appropriate default (e.g. `us-ascii`
88
+ # for `text/plain`, or `utf-8` for `application/json`), or may be nil for
89
+ # non-text cases.
90
+ # @return [String,nil]
91
91
  #
92
92
  attr_reader :charset
93
93
 
@@ -124,7 +124,7 @@ module CloudEvents
124
124
 
125
125
  private
126
126
 
127
- def parse(str)
127
+ def parse(str, default_charset)
128
128
  @media_type, str = consume_token(str, downcase: true, error_message: "Failed to parse media type")
129
129
  str = consume_special(str, "/")
130
130
  @subtype, str = consume_token(str, downcase: true, error_message: "Failed to parse subtype")
@@ -139,6 +139,13 @@ module CloudEvents
139
139
  end
140
140
  rescue ParseError => e
141
141
  @error_message = e.message
142
+ ensure
143
+ unless @subtype
144
+ @media_type = "text"
145
+ @subtype_base = @subtype = "plain"
146
+ @subtype_format = nil
147
+ end
148
+ @charset ||= default_charset || choose_default_charset
142
149
  end
143
150
 
144
151
  def consume_token(str, downcase: false, error_message: nil)
@@ -210,6 +217,14 @@ module CloudEvents
210
217
  "\"#{str}\""
211
218
  end
212
219
 
220
+ def choose_default_charset
221
+ if @media_type == "text" && @subtype == "plain"
222
+ "us-ascii"
223
+ elsif @media_type == "text" || @subtype_base == "json" || @subtype_format == "json"
224
+ "utf-8"
225
+ end
226
+ end
227
+
213
228
  def full_freeze
214
229
  instance_variables.each do |iv|
215
230
  instance_variable_get(iv).freeze
@@ -51,6 +51,14 @@ module CloudEvents
51
51
  class AttributeError < CloudEventsError
52
52
  end
53
53
 
54
+ ##
55
+ # An error raised when a protocol binding that does not support batch
56
+ # content mode receives a batch. For example, the Kafka protocol binding
57
+ # does not support batches per the CloudEvents spec.
58
+ #
59
+ class BatchNotSupportedError < CloudEventsError
60
+ end
61
+
54
62
  ##
55
63
  # Alias of UnsupportedFormatError, for backward compatibility.
56
64
  #
@@ -0,0 +1,364 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CloudEvents
4
+ ##
5
+ # Kafka protocol binding for CloudEvents.
6
+ #
7
+ # This class implements the Kafka protocol binding, including decoding of
8
+ # events from Kafka message hashes, and encoding of events to Kafka message
9
+ # hashes. It supports binary (header-based) and structured (body-based)
10
+ # content modes that can delegate to formatters such as JSON.
11
+ #
12
+ # Supports CloudEvents 1.0 only.
13
+ # See https://github.com/cloudevents/spec/blob/main/cloudevents/bindings/kafka-protocol-binding.md.
14
+ #
15
+ # Kafka messages are represented as plain Ruby Hashes with the keys:
16
+ # - `key:` [String, nil] — the Kafka record key
17
+ # - `value:` [String, nil] — the Kafka record value (body)
18
+ # - `headers:` [Hash] — String => String header pairs
19
+ #
20
+ class KafkaBinding
21
+ ##
22
+ # The name of the JSON decoder/encoder.
23
+ # @return [String]
24
+ #
25
+ JSON_FORMAT = "json"
26
+
27
+ ##
28
+ # The default key mapper for encoding.
29
+ # Returns the `partitionkey` extension attribute from the event.
30
+ # @return [Proc]
31
+ #
32
+ DEFAULT_KEY_MAPPER = ->(event) { event["partitionkey"] }
33
+
34
+ ##
35
+ # The default reverse key mapper for decoding.
36
+ # Sets the `partitionkey` extension attribute from the Kafka record key.
37
+ # Returns an empty hash if the key is nil.
38
+ # @return [Proc]
39
+ #
40
+ DEFAULT_REVERSE_KEY_MAPPER = ->(key) { key.nil? ? {} : { "partitionkey" => key } }
41
+
42
+ ##
43
+ # Returns a default Kafka binding, including support for JSON format.
44
+ #
45
+ # @return [KafkaBinding]
46
+ #
47
+ def self.default
48
+ @default ||= begin
49
+ kafka_binding = new
50
+ kafka_binding.register_formatter(JsonFormat.new, encoder_name: JSON_FORMAT)
51
+ kafka_binding.default_encoder_name = JSON_FORMAT
52
+ kafka_binding
53
+ end
54
+ end
55
+
56
+ ##
57
+ # Create an empty Kafka binding.
58
+ #
59
+ # @param key_mapper [Proc,nil] A callable `(event) -> String|nil` used
60
+ # to derive the Kafka record key when encoding. Defaults to
61
+ # {DEFAULT_KEY_MAPPER}. Set to `nil` to always produce a `nil` key.
62
+ # @param reverse_key_mapper [Proc,nil] A callable `(key) -> Hash` used
63
+ # to derive attributes to merge into the event when decoding.
64
+ # Defaults to {DEFAULT_REVERSE_KEY_MAPPER}. Set to `nil` to skip
65
+ # key-to-attribute mapping.
66
+ #
67
+ def initialize(key_mapper: DEFAULT_KEY_MAPPER, reverse_key_mapper: DEFAULT_REVERSE_KEY_MAPPER)
68
+ @key_mapper = key_mapper
69
+ @reverse_key_mapper = reverse_key_mapper
70
+ @event_decoders = Format::Multi.new do |result|
71
+ result&.key?(:event) ? result : nil
72
+ end
73
+ @event_encoders = {}
74
+ @data_decoders = Format::Multi.new do |result|
75
+ result&.key?(:data) && result.key?(:content_type) ? result : nil
76
+ end
77
+ @data_encoders = Format::Multi.new do |result|
78
+ result&.key?(:content) && result.key?(:content_type) ? result : nil
79
+ end
80
+ text_format = TextFormat.new
81
+ @data_decoders.formats.replace([text_format, HttpBinding::DefaultDataFormat])
82
+ @data_encoders.formats.replace([text_format, HttpBinding::DefaultDataFormat])
83
+ @default_encoder_name = nil
84
+ end
85
+
86
+ ##
87
+ # Register a formatter for all operations it supports, based on which
88
+ # methods are implemented by the formatter object. See
89
+ # {CloudEvents::Format} for a list of possible methods.
90
+ #
91
+ # @param formatter [Object] The formatter.
92
+ # @param encoder_name [String] The encoder name under which this
93
+ # formatter will register its encode operations. Optional. If not
94
+ # specified, any event encoder will _not_ be registered.
95
+ # @return [self]
96
+ #
97
+ def register_formatter(formatter, encoder_name: nil)
98
+ encoder_name = encoder_name.to_s.strip.downcase if encoder_name
99
+ decode_event = formatter.respond_to?(:decode_event)
100
+ encode_event = encoder_name if formatter.respond_to?(:encode_event)
101
+ decode_data = formatter.respond_to?(:decode_data)
102
+ encode_data = formatter.respond_to?(:encode_data)
103
+ register_formatter_methods(formatter,
104
+ decode_event: decode_event,
105
+ encode_event: encode_event,
106
+ decode_data: decode_data,
107
+ encode_data: encode_data)
108
+ self
109
+ end
110
+
111
+ ##
112
+ # Registers the given formatter for the given operations. Some arguments
113
+ # are activated by passing `true`, whereas those that rely on a format
114
+ # name are activated by passing in a name string.
115
+ #
116
+ # @param formatter [Object] The formatter.
117
+ # @param decode_event [boolean] If true, register the formatter's
118
+ # {CloudEvents::Format#decode_event} method.
119
+ # @param encode_event [String] If set to a string, use the formatter's
120
+ # {CloudEvents::Format#encode_event} method when that name is
121
+ # requested.
122
+ # @param decode_data [boolean] If true, register the formatter's
123
+ # {CloudEvents::Format#decode_data} method.
124
+ # @param encode_data [boolean] If true, register the formatter's
125
+ # {CloudEvents::Format#encode_data} method.
126
+ # @return [self]
127
+ #
128
+ def register_formatter_methods(formatter,
129
+ decode_event: false,
130
+ encode_event: nil,
131
+ decode_data: false,
132
+ encode_data: false)
133
+ @event_decoders.formats.unshift(formatter) if decode_event
134
+ if encode_event
135
+ encoders = @event_encoders[encode_event] ||= Format::Multi.new do |result|
136
+ result&.key?(:content) && result.key?(:content_type) ? result : nil
137
+ end
138
+ encoders.formats.unshift(formatter)
139
+ end
140
+ @data_decoders.formats.unshift(formatter) if decode_data
141
+ @data_encoders.formats.unshift(formatter) if encode_data
142
+ self
143
+ end
144
+
145
+ ##
146
+ # The name of the encoder to use if none is specified.
147
+ #
148
+ # @return [String,nil]
149
+ #
150
+ attr_accessor :default_encoder_name
151
+
152
+ ##
153
+ # Determine whether a Kafka message is likely a CloudEvent, by
154
+ # inspecting headers only (does not parse the value).
155
+ #
156
+ # @param message [Hash] The Kafka message hash.
157
+ # @return [boolean]
158
+ #
159
+ def probable_event?(message)
160
+ headers = message[:headers] || {}
161
+ return true if headers.key?("ce_specversion")
162
+ content_type_string = headers["content-type"]
163
+ return false unless content_type_string
164
+ content_type = ContentType.new(content_type_string)
165
+ content_type.media_type == "application" && content_type.subtype_base == "cloudevents"
166
+ end
167
+
168
+ ##
169
+ # Decode an event from a Kafka message hash.
170
+ #
171
+ # @param message [Hash] A hash with `:key`, `:value`, and `:headers` keys.
172
+ # @param allow_opaque [boolean] If true, returns {Event::Opaque} for
173
+ # unrecognized structured formats. Default is false.
174
+ # @param reverse_key_mapper [Proc,nil,:NOT_SET] A callable
175
+ # `(key) -> Hash`, or `nil` to skip key mapping. Defaults to the
176
+ # instance's reverse_key_mapper.
177
+ # @param format_args [keywords] Extra args forwarded to formatters.
178
+ # @return [CloudEvents::Event] The decoded event.
179
+ # @raise [NotCloudEventError] if the message is not a CloudEvent.
180
+ # @raise [SpecVersionError] if the specversion is not supported.
181
+ # @raise [UnsupportedFormatError] if a structured format is not recognized.
182
+ # @raise [FormatSyntaxError] if the structured content is malformed.
183
+ #
184
+ def decode_event(message, allow_opaque: false, reverse_key_mapper: :NOT_SET, **format_args)
185
+ reverse_key_mapper = @reverse_key_mapper if reverse_key_mapper == :NOT_SET
186
+ headers = message[:headers] || {}
187
+ content_type_string = headers["content-type"]
188
+ content_type = ContentType.new(content_type_string) if content_type_string
189
+
190
+ event = decode_content(message, headers, content_type, content_type_string, allow_opaque, **format_args)
191
+ apply_reverse_key_mapper(event, message[:key], reverse_key_mapper)
192
+ end
193
+
194
+ ##
195
+ # Encode an event into a Kafka message hash.
196
+ #
197
+ # @param event [CloudEvents::Event,CloudEvents::Event::Opaque] The event.
198
+ # @param structured_format [boolean,String] If false (default), encodes
199
+ # in binary content mode. If true or a format name string, encodes
200
+ # in structured content mode.
201
+ # @param key_mapper [Proc,nil,:NOT_SET] A callable
202
+ # `(event) -> String|nil`, or `nil` to always produce a `nil` key.
203
+ # Defaults to the instance's key_mapper.
204
+ # @param format_args [keywords] Extra args forwarded to formatters.
205
+ # @return [Hash] A hash with `:key`, `:value`, and `:headers` keys.
206
+ #
207
+ def encode_event(event, structured_format: false, key_mapper: :NOT_SET, **format_args)
208
+ key_mapper = @key_mapper if key_mapper == :NOT_SET
209
+ if event.is_a?(Event::Opaque)
210
+ return encode_opaque_event(event)
211
+ end
212
+ unless event.respond_to?(:spec_version)
213
+ raise(SpecVersionError, "Unable to determine specversion")
214
+ end
215
+ unless event.spec_version.start_with?("1.")
216
+ raise(SpecVersionError, "Unrecognized specversion: #{event.spec_version}")
217
+ end
218
+ if structured_format
219
+ encode_structured_event(event, structured_format, key_mapper, **format_args)
220
+ else
221
+ encode_binary_event(event, key_mapper, **format_args)
222
+ end
223
+ end
224
+
225
+ # @private
226
+ OMIT_ATTR_NAMES = ["specversion", "spec_version", "data", "datacontenttype", "data_content_type"].freeze
227
+
228
+ private
229
+
230
+ # Detect content mode, reject batches, and dispatch to the appropriate
231
+ # binary or structured decoder. Raises if the message is not a CloudEvent.
232
+ def decode_content(message, headers, content_type, content_type_string, allow_opaque, **format_args)
233
+ if content_type&.media_type == "application" && content_type.subtype_base == "cloudevents-batch"
234
+ raise(BatchNotSupportedError, "Kafka protocol binding does not support batch content mode")
235
+ end
236
+ if content_type&.media_type == "application" && content_type.subtype_base == "cloudevents"
237
+ return decode_structured_content(message, content_type, allow_opaque, **format_args)
238
+ end
239
+ if headers.key?("ce_specversion")
240
+ return decode_binary_content(message, content_type, **format_args)
241
+ end
242
+ ct_desc = content_type_string ? content_type_string.inspect : "not present"
243
+ raise(NotCloudEventError, "content-type is #{ct_desc}, and ce_specversion header is not present")
244
+ end
245
+
246
+ # Decode a single event from binary content mode. Reads ce_* headers as
247
+ # attributes and the message value as event data.
248
+ def decode_binary_content(message, content_type, **format_args)
249
+ headers = message[:headers] || {}
250
+ spec_version = headers["ce_specversion"]
251
+ raise(SpecVersionError, "Unrecognized specversion: #{spec_version}") unless spec_version =~ /^1(\.|$)/
252
+ attributes = { "spec_version" => spec_version }
253
+ headers.each do |key, value|
254
+ next unless key.start_with?("ce_")
255
+ attr_name = key[3..].downcase
256
+ attributes[attr_name] = value unless OMIT_ATTR_NAMES.include?(attr_name)
257
+ end
258
+ value = message[:value]
259
+ unless value.nil?
260
+ content_type = populate_data_attributes(attributes, value, content_type, spec_version, format_args)
261
+ end
262
+ attributes["data_content_type"] = content_type if content_type
263
+ Event.create(spec_version: spec_version, set_attributes: attributes)
264
+ end
265
+
266
+ # Populate data-related attributes (data_encoded, data, data_content_type)
267
+ # by running the value through registered data decoders. Returns the
268
+ # (possibly updated) content_type.
269
+ def populate_data_attributes(attributes, value, content_type, spec_version, format_args)
270
+ attributes["data_encoded"] = value
271
+ result = @data_decoders.decode_data(spec_version: spec_version,
272
+ content: value,
273
+ content_type: content_type,
274
+ **format_args)
275
+ if result
276
+ attributes["data"] = result[:data]
277
+ content_type = result[:content_type]
278
+ end
279
+ content_type
280
+ end
281
+
282
+ # Decode a single event from structured content mode. Delegates to
283
+ # registered event decoders, falling back to Event::Opaque if allowed.
284
+ def decode_structured_content(message, content_type, allow_opaque, **format_args)
285
+ content = message[:value].to_s
286
+ result = @event_decoders.decode_event(content: content,
287
+ content_type: content_type,
288
+ data_decoder: @data_decoders,
289
+ **format_args)
290
+ if result
291
+ event = result[:event]
292
+ raise(SpecVersionError, "Unable to determine specversion") unless event.respond_to?(:spec_version)
293
+ unless event.spec_version.start_with?("1.")
294
+ raise(SpecVersionError, "Unrecognized specversion: #{event.spec_version}")
295
+ end
296
+ return event
297
+ end
298
+ return Event::Opaque.new(content, content_type) if allow_opaque
299
+ raise(UnsupportedFormatError, "Unknown cloudevents content type: #{content_type}")
300
+ end
301
+
302
+ # Apply the reverse_key_mapper to merge Kafka record key attributes into
303
+ # the decoded event. Returns the event unchanged if the mapper is nil or
304
+ # returns an empty hash.
305
+ def apply_reverse_key_mapper(event, key, reverse_key_mapper)
306
+ return event unless reverse_key_mapper
307
+ mapped_attrs = reverse_key_mapper.call(key)
308
+ return event if mapped_attrs.nil? || mapped_attrs.empty?
309
+ event.with(**mapped_attrs.transform_keys(&:to_sym))
310
+ end
311
+
312
+ # Encode an event in binary content mode. Writes attributes as ce_*
313
+ # headers and event data as the message value.
314
+ def encode_binary_event(event, key_mapper, **format_args)
315
+ key = key_mapper&.call(event)
316
+ headers = {}
317
+ event.to_h.each do |attr_key, value|
318
+ next if ["data", "data_encoded", "datacontenttype"].include?(attr_key)
319
+ headers["ce_#{attr_key}"] = value.to_s
320
+ end
321
+ body, content_type = extract_event_data(event, format_args)
322
+ headers["content-type"] = content_type.to_s if content_type
323
+ { key: key, value: body, headers: headers }
324
+ end
325
+
326
+ # Encode an event in structured content mode using a named format encoder.
327
+ # The entire event is serialized into the message value.
328
+ def encode_structured_event(event, structured_format, key_mapper, **format_args)
329
+ key = key_mapper&.call(event)
330
+ structured_format = default_encoder_name if structured_format == true
331
+ raise(::ArgumentError, "Format name not specified, and no default is set") unless structured_format
332
+ result = @event_encoders[structured_format]&.encode_event(event: event,
333
+ data_encoder: @data_encoders,
334
+ **format_args)
335
+ raise(::ArgumentError, "Unknown format name: #{structured_format.inspect}") unless result
336
+ { key: key, value: result[:content], headers: { "content-type" => result[:content_type].to_s } }
337
+ end
338
+
339
+ # Encode an opaque event by passing through its content and content_type
340
+ # directly, with a nil key.
341
+ def encode_opaque_event(event)
342
+ { key: nil, value: event.content, headers: { "content-type" => event.content_type.to_s } }
343
+ end
344
+
345
+ # Extract the event data and content type for binary mode encoding.
346
+ # Uses data_encoded if present, otherwise delegates to data encoders.
347
+ # Returns [body, content_type], where body is nil for tombstones.
348
+ def extract_event_data(event, format_args)
349
+ body = event.data_encoded
350
+ if body
351
+ [body, event.data_content_type]
352
+ elsif event.data?
353
+ result = @data_encoders.encode_data(spec_version: event.spec_version,
354
+ data: event.data,
355
+ content_type: event.data_content_type,
356
+ **format_args)
357
+ raise(UnsupportedFormatError, "Could not encode data content-type") unless result
358
+ [result[:content], result[:content_type]]
359
+ else
360
+ [nil, nil]
361
+ end
362
+ end
363
+ end
364
+ end
@@ -5,5 +5,5 @@ module CloudEvents
5
5
  # Version of the Ruby CloudEvents SDK
6
6
  # @return [String]
7
7
  #
8
- VERSION = "0.8.2"
8
+ VERSION = "0.9.0"
9
9
  end
data/lib/cloud_events.rb CHANGED
@@ -5,6 +5,7 @@ require "cloud_events/errors"
5
5
  require "cloud_events/event"
6
6
  require "cloud_events/format"
7
7
  require "cloud_events/http_binding"
8
+ require "cloud_events/kafka_binding"
8
9
  require "cloud_events/json_format"
9
10
  require "cloud_events/text_format"
10
11
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cloud_events
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.2
4
+ version: 0.9.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daniel Azuma
@@ -21,6 +21,7 @@ files:
21
21
  - ".yardopts"
22
22
  - CHANGELOG.md
23
23
  - CONTRIBUTING.md
24
+ - LICENSE
24
25
  - MAINTAINERS.md
25
26
  - README.md
26
27
  - RELEASING.md
@@ -36,16 +37,17 @@ files:
36
37
  - lib/cloud_events/format.rb
37
38
  - lib/cloud_events/http_binding.rb
38
39
  - lib/cloud_events/json_format.rb
40
+ - lib/cloud_events/kafka_binding.rb
39
41
  - lib/cloud_events/text_format.rb
40
42
  - lib/cloud_events/version.rb
41
43
  homepage: https://github.com/cloudevents/sdk-ruby
42
44
  licenses:
43
45
  - Apache-2.0
44
46
  metadata:
45
- changelog_uri: https://cloudevents.github.io/sdk-ruby/v0.8.2/file.CHANGELOG.html
47
+ changelog_uri: https://cloudevents.github.io/sdk-ruby/v0.9.0/file.CHANGELOG.html
46
48
  source_code_uri: https://github.com/cloudevents/sdk-ruby
47
49
  bug_tracker_uri: https://github.com/cloudevents/sdk-ruby/issues
48
- documentation_uri: https://cloudevents.github.io/sdk-ruby/v0.8.2
50
+ documentation_uri: https://cloudevents.github.io/sdk-ruby/v0.9.0
49
51
  rdoc_options: []
50
52
  require_paths:
51
53
  - lib
@@ -60,7 +62,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
60
62
  - !ruby/object:Gem::Version
61
63
  version: '0'
62
64
  requirements: []
63
- rubygems_version: 3.6.9
65
+ rubygems_version: 4.0.3
64
66
  specification_version: 4
65
67
  summary: Ruby SDK for CloudEvents
66
68
  test_files: []