Skip to content

Commit 9d7aea7

Browse files
authored
Generate protobuf indexing event envelopes (#1405)
## Why ElasticGraph generates domain protobuf messages, but they lack the event fields an indexer needs: operation, type, ID, and version. ## What Add an event envelope and batch message to `schema.proto`, alongside the domain messages for ingestible types. Preserve field numbers as types are removed or restored. ## How The envelope refers to existing domain messages through a `record` oneof, using names such as `product`. Latency metadata uses `google.protobuf.Timestamp` values. Stable field numbers are stored in `proto_field_numbers.yaml`. Envelope fields render in field-number order, with a separate stanza for the record alternatives. Errors for reserved or colliding envelope field names explain how to fix them. Tests cover proto2 and proto3 generation, reserved transport type names, field-name collisions, and field numbers for removed and restored types. Integration tests cover timestamp round trips. The shared schema test helper compiles every nonempty generated schema with `protoc`, including fixtures with external imports. ## Risk Low. This extends the generated protobuf schema without changing runtime ingestion. ## Testing No manual testing. ## Bigger picture First of four PRs for protobuf ingestion. The next PR allows events without a JSON schema version. The independent JRuby test-recorder fix is in #1410.
1 parent 3e8c59f commit 9d7aea7

20 files changed

Lines changed: 374 additions & 54 deletions

File tree

‎elasticgraph-proto_ingestion/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,9 @@ end
215215
```
216216

217217
Each call to `protobuf` replaces the full protobuf configuration. The override above omits
218-
`import:`, so `schema.proto` no longer imports `google/protobuf/timestamp.proto`. An override that
219-
omits `field_comment:` likewise drops the built-in comment.
218+
`import:`, so the scalar no longer requires `google/protobuf/timestamp.proto`. The generated event
219+
envelope still requires that import for its latency timestamps. An override that omits
220+
`field_comment:` likewise drops the built-in comment.
220221

221222
## Type Mappings
222223

‎elasticgraph-proto_ingestion/lib/elastic_graph/proto_ingestion/schema_definition/api_extension.rb‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ module APIExtension
2929
def self.extended(api)
3030
api.state.extend(StateExtension)
3131
api.factory.extend(FactoryExtension)
32+
api.state.reserved_type_names.merge(%w[ElasticGraphEventEnvelope ElasticGraphEventBatch])
3233
end
3334

3435
# Configures protobuf artifact generation behavior.

‎elasticgraph-proto_ingestion/lib/elastic_graph/proto_ingestion/schema_definition/schema.rb‎

Lines changed: 74 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ class Schema
2626
# The protobuf syntax emitted when the schema does not configure one.
2727
DEFAULT_SYNTAX = "proto3"
2828

29+
# Field declarations for the indexing event's transport metadata, in allocation order.
30+
ENVELOPE_METADATA_FIELDS = {
31+
"op" => "optional string",
32+
"id" => "optional string",
33+
"version" => "optional int64",
34+
"latency_timestamps" => "map<string, google.protobuf.Timestamp>"
35+
}.freeze
36+
2937
# Normalizes a configured `syntax` to one of {SUPPORTED_SYNTAXES}.
3038
#
3139
# Both the `proto_schema_artifacts` API and this class validate through here so that a
@@ -143,6 +151,68 @@ def field_label_prefix(repeated:)
143151

144152
private
145153

154+
def envelope_definitions
155+
record_fields = envelope_record_fields
156+
active_names = ENVELOPE_METADATA_FIELDS.keys + record_fields.keys
157+
metadata = render_envelope_fields(ENVELOPE_METADATA_FIELDS, indent: " ")
158+
alternatives = render_envelope_fields(record_fields, indent: " ")
159+
reserved = render_reserved_envelope_fields(active_names)
160+
161+
body_sections = [metadata, " oneof record {\n#{alternatives}\n }", reserved].reject(&:empty?)
162+
envelope = <<~PROTO
163+
message ElasticGraphEventEnvelope {
164+
#{body_sections.join("\n\n")}
165+
}
166+
PROTO
167+
168+
batch = <<~PROTO
169+
message ElasticGraphEventBatch {
170+
repeated ElasticGraphEventEnvelope events = 1;
171+
}
172+
PROTO
173+
174+
{"ElasticGraphEventEnvelope" => envelope.strip, "ElasticGraphEventBatch" => batch.strip}
175+
end
176+
177+
def envelope_record_fields
178+
type_names_by_field_name = {} # : ::Hash[::String, ::String]
179+
180+
@ingestible_types_by_name.values.sort_by(&:name).to_h do |type|
181+
# @type var proto_type: SchemaElements::ObjectInterfaceAndUnionExtension
182+
proto_type = _ = type
183+
field_name = Support::Casing.to_upper_snake(proto_type.proto_name).downcase
184+
if ENVELOPE_METADATA_FIELDS.key?(field_name) || field_name == "record"
185+
raise Errors::SchemaError, "Ingestible type `#{type.name}` maps to reserved protobuf envelope field `#{field_name}`. " \
186+
"Rename `#{type.name}` so its snake_case name does not conflict with a reserved envelope field."
187+
end
188+
if (existing_type_name = type_names_by_field_name[field_name])
189+
raise Errors::SchemaError, "Ingestible types `#{existing_type_name}` and `#{type.name}` map to " \
190+
"the same protobuf envelope field `#{field_name}`. " \
191+
"Rename one of these types so their names remain distinct when converted to snake_case."
192+
end
193+
194+
type_names_by_field_name[field_name] = type.name
195+
[field_name, proto_type.proto_type_reference(@package_name)]
196+
end
197+
end
198+
199+
def render_envelope_fields(fields, indent:)
200+
fields.map do |name, declaration|
201+
number = field_number_for(
202+
message_name: "ElasticGraphEventEnvelope",
203+
type_name: "ElasticGraphEventEnvelope",
204+
public_field_name: name
205+
)
206+
[number, "#{indent}#{declaration} #{name} = #{number};"]
207+
end.sort_by(&:first).map(&:last).join("\n")
208+
end
209+
210+
def render_reserved_envelope_fields(active_names)
211+
reserved_field_numbers_for("ElasticGraphEventEnvelope", active_names).map do |name, number|
212+
" reserved #{number}; // Previously used by #{name}."
213+
end.join("\n")
214+
end
215+
146216
# Selects the ingestible types and every type transitively referenced by their protobuf
147217
# representations. All traversal state is local so repeated calls are independent.
148218
def proto_types
@@ -163,19 +233,17 @@ def proto_types
163233
end
164234

165235
def render_definitions(types)
166-
types
167-
.sort_by(&:proto_name)
168-
.filter_map { |type| type.to_proto(self, @package_name) }
169-
.join("\n\n")
236+
definitions = types.to_h { |type| [type.proto_name, type.to_proto(self, @package_name)] }
237+
definitions.merge(envelope_definitions).compact.sort.map(&:last).join("\n\n")
170238
end
171239

172240
# Every type reports the proto file it needs imported, or `nil` when it needs none. Today only
173241
# scalar types map to an externally defined proto type, but enum and object types can start
174242
# requiring an import without any change here.
175243
def render_imports(types)
176-
imports = types.filter_map(&:protobuf_import).uniq.sort
244+
imports = (types.filter_map(&:protobuf_import) + ["google/protobuf/timestamp.proto"]).uniq.sort
177245

178-
imports.empty? ? [] : [imports.map { |import| %(import "#{import}";) }.join("\n")]
246+
[imports.map { |import| %(import "#{import}";) }.join("\n")]
179247
end
180248

181249
def render_header_lines

‎elasticgraph-proto_ingestion/sig/elastic_graph/proto_ingestion/schema_definition/schema.rbs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ module ElasticGraph
66

77
SUPPORTED_SYNTAXES: ::Array[::String]
88
DEFAULT_SYNTAX: ::String
9+
ENVELOPE_METADATA_FIELDS: ::Hash[::String, ::String]
910

1011
def self.validate_syntax: ((::Symbol | ::String)) -> ::String
1112
def self.validate_header_lines: (::Array[::String]) -> ::Array[::String]
@@ -42,6 +43,10 @@ module ElasticGraph
4243

4344
private
4445

46+
def envelope_definitions: () -> ::Hash[::String, ::String]
47+
def envelope_record_fields: () -> ::Hash[::String, ::String]
48+
def render_envelope_fields: (::Hash[::String, ::String], indent: ::String) -> ::String
49+
def render_reserved_envelope_fields: (::Array[::String]) -> ::String
4550
def proto_types: () -> ::Array[untyped]
4651
def render_definitions: (::Array[untyped] types) -> ::String
4752
def render_imports: (::Array[untyped] types) -> ::Array[::String]
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2024 - 2026 Block, Inc.
2+
//
3+
// Use of this source code is governed by an MIT-style
4+
// license that can be found in the LICENSE file or at
5+
// https://opensource.org/licenses/MIT.
6+
7+
// Minimal external type for the scalar import specs. The schema helper supplies this
8+
// fixture to protoc so generated references to example.AType can compile.
9+
// The a/ and z/ paths test alphabetical import ordering independently of scalar
10+
// definition order. Keep them separate to preserve that coverage.
11+
12+
syntax = "proto3";
13+
package example;
14+
15+
message AType {}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2024 - 2026 Block, Inc.
2+
//
3+
// Use of this source code is governed by an MIT-style
4+
// license that can be found in the LICENSE file or at
5+
// https://opensource.org/licenses/MIT.
6+
7+
// Minimal stand-in for an external Date message used by the built-in scalar override
8+
// spec. The schema helper supplies this fixture to protoc at the configured import
9+
// path so the generated google.type.Date reference can compile. Its fields are not
10+
// relevant to the import and field-comment behavior that the spec exercises.
11+
12+
syntax = "proto3";
13+
package google.type;
14+
15+
message Date {}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2024 - 2026 Block, Inc.
2+
//
3+
// Use of this source code is governed by an MIT-style
4+
// license that can be found in the LICENSE file or at
5+
// https://opensource.org/licenses/MIT.
6+
7+
// Minimal external type for the custom scalar mapping spec. The schema helper
8+
// supplies this fixture to protoc so the generated myapp.types.Money reference can
9+
// compile. The hyphenated directory and dotted filename exercise valid import paths
10+
// that do not simply mirror the protobuf package name.
11+
12+
syntax = "proto3";
13+
package myapp.types;
14+
15+
message Money {}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2024 - 2026 Block, Inc.
2+
//
3+
// Use of this source code is governed by an MIT-style
4+
// license that can be found in the LICENSE file or at
5+
// https://opensource.org/licenses/MIT.
6+
7+
// Minimal external type for the spec that imports only referenced scalar types.
8+
// The schema helper supplies this fixture to protoc so example.UsedType can compile.
9+
// The unused.proto and graphql_only_field.proto paths deliberately have no fixtures:
10+
// those imports must be absent because generated messages do not reference them.
11+
12+
syntax = "proto3";
13+
package example;
14+
15+
message UsedType {}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Copyright 2024 - 2026 Block, Inc.
2+
//
3+
// Use of this source code is governed by an MIT-style
4+
// license that can be found in the LICENSE file or at
5+
// https://opensource.org/licenses/MIT.
6+
7+
// Minimal external types for the scalar import specs. The schema helper supplies
8+
// this fixture to protoc so both generated type references can compile.
9+
// Two scalars import this file to test import deduplication. Its z/ path sorts
10+
// after a/types.proto even though these scalars are defined first in the spec.
11+
12+
syntax = "proto3";
13+
package example;
14+
15+
message FirstZType {}
16+
message SecondZType {}

‎elasticgraph-proto_ingestion/spec/integration/elastic_graph/proto_ingestion/schema_definition/rake_tasks_spec.rb‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ module SchemaDefinition
3434
start_with(
3535
"// Generated by `bundle exec rake schema_artifacts:dump`.\n" \
3636
"// DO NOT EDIT BY HAND. Any edits will be lost the next time the rake task is run.\n"
37-
).and(a_string_including('syntax = "proto3";', "message Product", "string name = 2;"))
37+
).and(a_string_including('syntax = "proto3";', "message Product", "string name = 2;", "message ElasticGraphEventEnvelope", "message ElasticGraphEventBatch"))
3838
)
3939
end
4040

@@ -74,6 +74,7 @@ module SchemaDefinition
7474
expect(parsed_proto_field_numbers).to eq({
7575
"enums" => {},
7676
"messages" => {
77+
"ElasticGraphEventEnvelope" => envelope_field_number_mapping("product"),
7778
"Product" => {
7879
"fields" => {
7980
"id" => 1,

0 commit comments

Comments
 (0)