Skip to content

Commit 2684bc8

Browse files
jwilsNeon
andauthored
Prepare native protobuf records for indexing (#1442)
## Why The indexer needs datastore hashes, but protobuf publishers produce native messages. Converting them into public record hashes first adds a full traversal and extra allocations. ## What Prepare native protobuf messages directly into datastore records in one pass using the generated protobuf runtime metadata and `google-protobuf` descriptors. ## How `ProtoIngestion::RecordPreparer` caches field plans built from protobuf descriptors. Sparse runtime metadata supplies field-name overrides, enum names, and scalar types. Renamed built-in scalars retain their indexing preparers, and enum symbols and numbers map consistently across Ruby runtimes. The preparer applies shared scalar rules, unwraps abstract `oneof` records, prepares message scalars such as `google.protobuf.Timestamp` from their canonical protobuf JSON form through the scalar's indexing preparer, and parses and canonicalizes `Untyped` leaves. The shared indexing pipeline adds `__counts` afterward. Preserves field presence, explicit defaults, exact 64-bit integers, nested lists, and concrete types in a single pass. ## Risk Adds `ProtoIngestion::RecordPreparer` and `RuntimeMetadata::Schema.from_schema_artifacts`, which become active when #1450 registers the protobuf ingestion adapter. Runtime dependencies are `elasticgraph-indexer` and `google-protobuf`. ## Testing No manual testing. Covered by integration specs in `record_preparer_spec.rb` and unit specs in `runtime_metadata/schema_spec.rb`. ## Bigger picture Builds on #1441's protobuf publishing test support. Native record validation, adapter registration, and activation of the shared indexing parity suite follow in #1450. --------- Signed-off-by: Josh Wilson <joshuaw@squareup.com> Co-authored-by: Neon <f833053fa3445a7878359a1bd17c4f6b4ed1ceb3e7414f306f4929b1f9032d02@buzz>
1 parent 177dff1 commit 2684bc8

11 files changed

Lines changed: 610 additions & 10 deletions

File tree

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
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+
# frozen_string_literal: true
8+
9+
require "elastic_graph/proto_ingestion"
10+
require "elastic_graph/proto_ingestion/proto_conversions"
11+
require "elastic_graph/proto_ingestion/runtime_metadata/schema"
12+
require "elastic_graph/support/thread_safe_cache"
13+
require "google/protobuf"
14+
require "json"
15+
16+
module ElasticGraph
17+
module ProtoIngestion
18+
# Prepares native protobuf messages directly into datastore records. Message descriptors supply
19+
# the structure once per message class, and runtime metadata supplies the ElasticGraph ingestion
20+
# facts that descriptors cannot express.
21+
# @private
22+
class RecordPreparer
23+
def initialize(schema_artifacts)
24+
@metadata = RuntimeMetadata::Schema.from_schema_artifacts(schema_artifacts)
25+
@scalar_types_by_name = schema_artifacts.runtime_metadata.scalar_types_by_name
26+
@types = Support::ThreadSafeCache.new # : Support::ThreadSafeCache[::Class, typePlan]
27+
@enums = Support::ThreadSafeCache.new # : Support::ThreadSafeCache[::Google::Protobuf::EnumDescriptor, ::Hash[::Symbol | ::Integer, ::String?]]
28+
end
29+
30+
# Implements the indexer's record-preparer interface without an intermediate public record hash.
31+
# Does not mutate the native message or its nested values.
32+
def prepare_for_index(_type_name, message, mapping_properties)
33+
type = resolve_type(message.class.descriptor)
34+
type.prepare(message, mapping_properties)
35+
end
36+
37+
private
38+
39+
# Resolved once per protobuf message class (together with all nested message types) so
40+
# preparation acquires the `@types` lock once per root record and never re-inspects descriptors.
41+
# @private
42+
Type = ::Data.define(:name, :fields) do
43+
# @implements Type
44+
45+
def prepare(message, mapping_properties)
46+
prepared = {} # : ::Hash[::String, untyped]
47+
fields.each { |field| field.prepare_into(prepared, message, mapping_properties) }
48+
49+
typename_type = mapping_properties&.dig("__typename", "type")
50+
if typename_type && typename_type != "constant_keyword"
51+
prepared["__typename"] = name
52+
end
53+
54+
prepared
55+
end
56+
end
57+
58+
# Prepares a message of a union or interface type by dispatching its `value` oneof
59+
# to the pre-resolved concrete `Type` for the active alternative.
60+
# @private
61+
AbstractType = ::Data.define(:types_by_alternative) do
62+
# @implements AbstractType
63+
64+
def prepare(message, mapping_properties)
65+
alternative = message.value
66+
return nil unless alternative
67+
68+
types_by_alternative.fetch(alternative).prepare(message.public_send(alternative), mapping_properties)
69+
end
70+
end
71+
72+
# @private
73+
Field = ::Data.define(:name, :name_in_index, :presence_method, :list_depth, :leaf_preparer, :child_type) do
74+
# @implements Field
75+
76+
# Adds this field's prepared value to `prepared`, unless `message` leaves this singular field unset.
77+
def prepare_into(prepared, message, mapping_properties)
78+
return if presence_method && !message.public_send(presence_method)
79+
80+
nested_mapping = child_type ? mapping_properties&.dig(name_in_index, "properties") : nil
81+
prepared[name_in_index] = prepare_value(message[name], nested_mapping, list_depth)
82+
end
83+
84+
private
85+
86+
def prepare_value(value, nested_mapping, depth)
87+
if depth > 0
88+
return value.map do |item|
89+
prepare_value((depth > 1) ? item.values : item, nested_mapping, depth - 1)
90+
end
91+
end
92+
93+
if (child = child_type)
94+
child.prepare(value, nested_mapping)
95+
else
96+
preparer = leaf_preparer # : ^(untyped) -> untyped
97+
preparer.call(value)
98+
end
99+
end
100+
end
101+
private_constant :Type, :AbstractType, :Field
102+
103+
def resolve_type(descriptor)
104+
@types.fetch_or_store(descriptor.msgclass) { build_type(descriptor) }
105+
end
106+
107+
def build_type(descriptor)
108+
if (oneof = descriptor.lookup_oneof("value"))
109+
types_by_alternative = {} # : ::Hash[::Symbol, Type | AbstractType]
110+
oneof.each do |field|
111+
subtype = field.subtype # : ::Google::Protobuf::Descriptor
112+
types_by_alternative[field.name.to_sym] = resolve_type(subtype)
113+
end
114+
return AbstractType.new(types_by_alternative)
115+
end
116+
117+
name = type_name_for(descriptor)
118+
overrides = @metadata.types_by_name[name]&.fields_by_name || {}
119+
fields = descriptor.map do |entry|
120+
field = entry # : ::Google::Protobuf::FieldDescriptor
121+
build_field(descriptor, field, overrides[field.name])
122+
end
123+
124+
Type.new(name, fields)
125+
end
126+
127+
def build_field(descriptor, field, field_meta)
128+
name = field.name
129+
name_in_index = field_meta&.name_in_index || name
130+
presence_method = (field.label == :repeated) ? nil : :"has_#{name}?"
131+
132+
list_depth = 0
133+
leaf = field
134+
while leaf.label == :repeated
135+
list_depth += 1
136+
break unless leaf.type == :message
137+
138+
wrapper = leaf.subtype # : ::Google::Protobuf::Descriptor
139+
break unless wrapper.name.start_with?("#{descriptor.name}.")
140+
141+
leaf = wrapper.lookup("values") # : ::Google::Protobuf::FieldDescriptor
142+
end
143+
144+
case leaf.type
145+
when :enum
146+
enum_descriptor = leaf.subtype # : ::Google::Protobuf::EnumDescriptor
147+
enum_values = build_enum(enum_descriptor)
148+
# Events with unknown enum numbers are rejected before preparation.
149+
leaf_preparer = ->(value) { enum_values.fetch(value) }
150+
when :message
151+
message_descriptor = leaf.subtype # : ::Google::Protobuf::Descriptor
152+
if message_descriptor.name.start_with?("#{@metadata.package_name}.")
153+
child_type = resolve_type(message_descriptor)
154+
else
155+
leaf_preparer = build_scalar_preparer(leaf, field_meta, message_descriptor: message_descriptor)
156+
end
157+
else
158+
leaf_preparer = build_scalar_preparer(leaf, field_meta)
159+
end
160+
161+
Field.new(name, name_in_index, presence_method, list_depth, leaf_preparer, child_type)
162+
end
163+
164+
def build_enum(descriptor)
165+
@enums.fetch_or_store(descriptor) do
166+
name = type_name_for(descriptor)
167+
overrides = @metadata.types_by_name[name]&.non_standard_enum_values_by_name || {}
168+
entries = descriptor.to_h
169+
prefix = entries.key(0).to_s.delete_suffix("_UNSPECIFIED")
170+
values = {} # : ::Hash[::Symbol | ::Integer, ::String?]
171+
172+
entries.each do |symbol, number|
173+
key = symbol.to_s
174+
value = (number == 0) ? nil : (overrides[key] || ProtoConversions.enum_value_to_eg_name(key, prefix))
175+
# JRuby can expose repeated enum values as numbers rather than symbols.
176+
values[symbol] = values[number] = value
177+
end
178+
179+
values
180+
end
181+
end
182+
183+
def build_scalar_preparer(leaf_field, field_meta, message_descriptor: nil)
184+
if (type_name = field_meta&.type)
185+
scalar = @metadata.types_by_name.fetch(type_name).scalar
186+
end
187+
188+
proto_type = message_descriptor ? message_descriptor.name : leaf_field.type.to_s
189+
type_name ||= DEFAULT_SCALARS_BY_PROTO_TYPE.fetch(proto_type)
190+
preparer = @scalar_types_by_name.fetch(type_name).load_indexing_preparer.extension_class # : singleton(SchemaArtifacts::RuntimeMetadata::ScalarIndexingPreparerInterface)
191+
192+
if message_descriptor
193+
# Message scalars (such as `google.protobuf.Timestamp`) are prepared from their canonical protobuf JSON form.
194+
->(value) { preparer.prepare_for_indexing(::JSON.parse(::Google::Protobuf.encode_json(value))) }
195+
elsif scalar == "Untyped"
196+
->(value) { preparer.prepare_for_indexing(::JSON.parse(value)) }
197+
else
198+
->(value) { preparer.prepare_for_indexing(value) }
199+
end
200+
end
201+
202+
def type_name_for(descriptor)
203+
descriptor.name.delete_prefix("#{@metadata.package_name}.")
204+
end
205+
end
206+
end
207+
end

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
#
77
# frozen_string_literal: true
88

9+
require "elastic_graph/errors"
10+
require "elastic_graph/proto_ingestion/indexer_extension"
911
require "elastic_graph/proto_ingestion/runtime_metadata/type"
1012

1113
module ElasticGraph
@@ -20,6 +22,16 @@ module RuntimeMetadata
2022
Schema = ::Data.define(:package_name, :types_by_name) do
2123
# @implements Schema
2224

25+
def self.from_schema_artifacts(schema_artifacts)
26+
extension = schema_artifacts.runtime_metadata.indexer_extension_modules.find do |candidate|
27+
candidate.extension_ref.fetch("name") == IndexerExtension.name
28+
end
29+
unless extension
30+
raise Errors::ConfigError, "Protobuf runtime metadata is missing. Enable `ElasticGraph::ProtoIngestion::SchemaDefinition::APIExtension` and dump schema artifacts."
31+
end
32+
from_hash(extension.extension_ref.fetch("config"))
33+
end
34+
2335
def self.from_hash(hash)
2436
types = hash["types_by_name"] || {} # : ::Hash[::String, untyped]
2537
new(

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#
77
# frozen_string_literal: true
88

9+
require "elastic_graph/proto_ingestion/indexer_extension"
910
require "elastic_graph/proto_ingestion/schema_definition/schema"
1011
require "elastic_graph/schema_artifacts/runtime_metadata/component_extension"
1112

@@ -38,7 +39,7 @@ def proto_field_number_mappings
3839
def build_runtime_metadata
3940
metadata = super
4041
extension = SchemaArtifacts::RuntimeMetadata::ComponentExtension.new({
41-
"name" => "ElasticGraph::ProtoIngestion::IndexerExtension",
42+
"name" => IndexerExtension.name,
4243
"require_path" => "elastic_graph/proto_ingestion/indexer_extension",
4344
"config" => protobuf_schema_generator.proto_ingestion_metadata.to_dumpable_hash
4445
})

‎elasticgraph-proto_ingestion/lib/elastic_graph/proto_ingestion/schema_definition/schema_elements/scalar_type_extension.rb‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ def proto_type_reference(_package_name)
9999
proto_name
100100
end
101101

102-
# Returns the scalar's original name when it differs from the default for its protobuf type.
102+
# Returns the canonical scalar name when its wire type or customized name needs metadata.
103103
#
104104
# @return [RuntimeMetadata::Type]
105105
def proto_ingestion_metadata
@@ -109,7 +109,7 @@ def proto_ingestion_metadata
109109
RuntimeMetadata::Type.new(
110110
fields_by_name: {},
111111
non_standard_enum_values_by_name: {},
112-
scalar: (scalar_name == default_scalar) ? nil : scalar_name
112+
scalar: (scalar_name == default_scalar && name == scalar_name) ? nil : scalar_name
113113
)
114114
end
115115
end
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
module ElasticGraph
2+
module ProtoIngestion
3+
class RecordPreparer
4+
type typePlan = Type | AbstractType
5+
6+
@metadata: RuntimeMetadata::Schema
7+
@scalar_types_by_name: ::Hash[::String, SchemaArtifacts::RuntimeMetadata::ScalarType]
8+
@types: Support::ThreadSafeCache[::Class, typePlan]
9+
@enums: Support::ThreadSafeCache[::Google::Protobuf::EnumDescriptor, ::Hash[::Symbol | ::Integer, ::String?]]
10+
11+
def initialize: (schemaArtifacts) -> void
12+
def prepare_for_index: (::String, untyped, ::Hash[::String, untyped]?) -> ::Hash[::String, untyped]?
13+
14+
class Type < ::Data
15+
attr_reader name: ::String
16+
attr_reader fields: ::Array[Field]
17+
def self.new: (::String, ::Array[Field]) -> Type
18+
def prepare: (untyped, ::Hash[::String, untyped]?) -> ::Hash[::String, untyped]
19+
end
20+
21+
class AbstractType < ::Data
22+
attr_reader types_by_alternative: ::Hash[::Symbol, typePlan]
23+
def self.new: (::Hash[::Symbol, typePlan]) -> AbstractType
24+
def prepare: (untyped, ::Hash[::String, untyped]?) -> ::Hash[::String, untyped]?
25+
end
26+
27+
class Field < ::Data
28+
attr_reader name: ::String
29+
attr_reader name_in_index: ::String
30+
attr_reader presence_method: ::Symbol?
31+
attr_reader list_depth: ::Integer
32+
attr_reader leaf_preparer: (^(untyped) -> untyped)?
33+
attr_reader child_type: typePlan?
34+
def self.new: (::String, ::String, ::Symbol?, ::Integer, (^(untyped) -> untyped)?, typePlan?) -> Field
35+
def prepare_into: (::Hash[::String, untyped], untyped, ::Hash[::String, untyped]?) -> void
36+
37+
private
38+
39+
def prepare_value: (untyped, ::Hash[::String, untyped]?, ::Integer) -> untyped
40+
end
41+
42+
private
43+
44+
def resolve_type: (::Google::Protobuf::Descriptor) -> typePlan
45+
def build_type: (::Google::Protobuf::Descriptor) -> typePlan
46+
def build_field: (::Google::Protobuf::Descriptor, ::Google::Protobuf::FieldDescriptor, RuntimeMetadata::Field?) -> Field
47+
def build_enum: (::Google::Protobuf::EnumDescriptor) -> ::Hash[::Symbol | ::Integer, ::String?]
48+
def build_scalar_preparer: (
49+
::Google::Protobuf::FieldDescriptor,
50+
RuntimeMetadata::Field?,
51+
?message_descriptor: ::Google::Protobuf::Descriptor?
52+
) -> ^(untyped) -> untyped
53+
def type_name_for: (::Google::Protobuf::Descriptor | ::Google::Protobuf::EnumDescriptor) -> ::String
54+
end
55+
end
56+
end

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ module ElasticGraph
77

88
def initialize: (package_name: ::String, types_by_name: ::Hash[::String, Type]) -> void
99
def self.new: (package_name: ::String, types_by_name: ::Hash[::String, Type]) -> Schema
10+
def self.from_schema_artifacts: (schemaArtifacts) -> Schema
1011
def self.from_hash: (::Hash[::String, untyped]) -> Schema
1112
def to_dumpable_hash: () -> ::Hash[::String, untyped]
1213
end
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module Google
2+
module Protobuf
3+
class FieldDescriptor
4+
# rbs_collection describes this accessor as Symbol?, but google-protobuf returns a descriptor.
5+
def subtype: () -> (Descriptor | EnumDescriptor)? | ...
6+
end
7+
end
8+
end

0 commit comments

Comments
 (0)