Skip to content

Commit cacc0b4

Browse files
authored
Route events through a typed Event value (#1398)
## Why Every consumer of an indexing event reached into a `Hash` with string keys. The shape of the envelope lived only in scattered `fetch` calls, Steep could not check it, and each consumer had to repeat the defaults for optional fields. A `Data` value with typed members states the envelope once. An `Event` exists only after an ingestion adapter validates its envelope, so every instance has the typed fields the envelope declares. ## What - `Indexer::Event`, with members `op`, `type`, `id`, `version`, `record`, `schema_version`, `ingestion_format`, `message_id`, and `latency_timestamps`. - Typed accessors in place of `event["x"]` and `event.fetch("x")` across `EventID`, `FailedEventError`, `IndexingFailuresError`, `Operation::Factory`, `Operation::Update`, `DatastoreIndexingRouter`, `Processor`, `IngestionAdapter`, the JSON ingestion adapter, `WarehouseDumper`, and `TestSupport::Converters`. - `FailedEventError` delegates `id`, `op`, `type`, `version`, `record`, and `message_id` to its event through `Forwardable`, and includes `IndexingFailuresError::_IndexingFailure` so that Steep enforces the interface it satisfies. - The JSON adapter's `events_from` returns `Event`s through `Event.from_validated_hash`. `Event#record` keeps the native record type of the adapter, which is a `Hash` for JSON. An ingestion format with a different record type can therefore carry its own. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
2 parents 8c318dc + 8b6e554 commit cacc0b4

44 files changed

Lines changed: 616 additions & 394 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎elasticgraph-indexer/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ require "elastic_graph/indexer"
4848

4949
indexer = ElasticGraph::Indexer.from_yaml_file("config/settings/local.yaml")
5050

51-
events = [] # JSON events read from an async datastream
51+
# `ElasticGraph::Indexer::Event` instances, built by an ingestion adapter such as the one
52+
# in `elasticgraph-json_ingestion` after it validates the event envelope.
53+
events = []
5254
indexer.processor.process(events)
5355
```

‎elasticgraph-indexer/lib/elastic_graph/indexer/datastore_indexing_router.rb‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def bulk(operations, refresh: false)
6868
unless unsupported_ops.empty?
6969
raise IndexingFailuresError,
7070
"The index definitions for #{unsupported_ops.size} operations " \
71-
"(#{unsupported_ops.map { |o| Indexer::EventID.from_event(o.event) }.join(", ")}) " \
71+
"(#{unsupported_ops.map { |o| o.event.event_id }.join(", ")}) " \
7272
"were configured to be inaccessible. Check the configuration, or avoid sending " \
7373
"events of this type to this ElasticGraph indexer."
7474
end
@@ -269,7 +269,7 @@ def source_event_versions_in_index(operations)
269269

270270
def opaque_id_parts_for_source_event_versions(operations)
271271
type_counts = operations
272-
.group_by { |op| op.event.fetch("type") }
272+
.group_by { |op| op.event.type }
273273
.sort_by(&:first)
274274
.map { |type_name, ops| "#{type_name}:#{ops.size}" }
275275

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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/constants"
10+
require "elastic_graph/indexer/event_id"
11+
12+
module ElasticGraph
13+
class Indexer
14+
# An indexing event with a validated envelope. Ingestion adapters build events after they
15+
# validate the envelope in their own format, so every `Event` instance has typed envelope
16+
# fields. `record` keeps the adapter's native record type (a `Hash` for JSON events).
17+
#
18+
# @!attribute [r] op
19+
# @return [String] the operation to apply (`upsert`)
20+
# @!attribute [r] type
21+
# @return [String] the GraphQL type of the record
22+
# @!attribute [r] id
23+
# @return [String] the unique identifier of the record
24+
# @!attribute [r] version
25+
# @return [Integer] version used to order events for the same `type` and `id`
26+
# @!attribute [r] record
27+
# @return [Object] the record payload, in the ingestion adapter's native type
28+
# @!attribute [r] schema_version
29+
# @return [Integer] the version of the ingestion schema the publisher used
30+
# @!attribute [r] ingestion_format
31+
# @return [String] the format tag that selects the ingestion adapter
32+
# @!attribute [r] message_id
33+
# @return [String, nil] the id of the transport message that carried the event
34+
# @!attribute [r] latency_timestamps
35+
# @return [Hash<String, String>] ISO8601 timestamps from which indexing latency is measured
36+
Event = ::Data.define(:op, :type, :id, :version, :record, :schema_version, :ingestion_format, :message_id, :latency_timestamps) do
37+
# @implements Event[R]
38+
39+
def initialize(op:, type:, id:, version:, record:, schema_version:, ingestion_format:, message_id: nil, latency_timestamps: {})
40+
super
41+
end
42+
43+
# @return [EventID] identifies this event by its `type`, `id`, and `version`
44+
def event_id
45+
EventID.new(type: type, id: id, version: version)
46+
end
47+
48+
# Builds an event from a JSON event hash whose envelope has already been validated.
49+
#
50+
# @param hash [Hash<String, Object>] a validated JSON event
51+
# @return [Event]
52+
def self.from_validated_hash(hash)
53+
latency_timestamps = hash["latency_timestamps"] || {} # : ::Hash[::String, ::String]
54+
55+
new(
56+
op: hash.fetch("op"),
57+
type: hash.fetch("type"),
58+
id: hash.fetch("id"),
59+
version: hash.fetch("version"),
60+
record: hash.fetch("record"),
61+
schema_version: hash.fetch(JSON_SCHEMA_VERSION_KEY),
62+
ingestion_format: hash.fetch(INGESTION_FORMAT_KEY, "json"),
63+
message_id: hash["message_id"],
64+
latency_timestamps: latency_timestamps
65+
)
66+
end
67+
end
68+
69+
# Steep weirdly expects them here...
70+
# @dynamic initialize, config, datastore_core, schema_artifacts, datastore_router, monotonic_clock
71+
# @dynamic processor, operation_factory, ingestion_adapters_by_format, logger
72+
# @dynamic self.from_parsed_yaml
73+
end
74+
end

‎elasticgraph-indexer/lib/elastic_graph/indexer/event_id.rb‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,14 @@ class Indexer
1515
# easy to put these ids in a comma-separated list.
1616
EventID = ::Data.define(:type, :id, :version) do
1717
# @implements EventID
18-
def self.from_event(event)
19-
new(type: event["type"], id: event["id"], version: event["version"])
18+
19+
# Builds an id from a decoded payload whose envelope is not yet known to be valid, so no
20+
# {Event} exists for it. Use {Event#event_id} for a validated event.
21+
#
22+
# @param hash [Hash<String, Object>] a decoded indexing payload
23+
# @return [EventID]
24+
def self.from_decoded_hash(hash)
25+
new(type: hash["type"], id: hash["id"], version: hash["version"])
2026
end
2127

2228
def to_s

‎elasticgraph-indexer/lib/elastic_graph/indexer/failed_event_error.rb‎

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,17 @@
88

99
require "elastic_graph/errors"
1010
require "elastic_graph/indexer/event_id"
11+
require "forwardable"
1112

1213
module ElasticGraph
1314
class Indexer
1415
# Indicates an event that we attempted to process which failed for some reason. It may have
1516
# failed due to a validation issue before we even attempted to write it to the datastore, or it
1617
# could have failed in the datastore itself.
1718
class FailedEventError < Errors::Error
18-
# @dynamic main_message, event, operations, message_id, message
19+
extend ::Forwardable
20+
21+
# @dynamic main_message, event, operations, id, op, type, version, record, message_id, message
1922

2023
# The "main" part of the error message (without the `full_id` portion).
2124
attr_reader :main_message
@@ -51,37 +54,15 @@ def versioned_operations
5154
end
5255

5356
def full_id
54-
event_id = EventID.from_event(event).to_s
55-
if (message_id = self.message_id)
57+
event_id = event.event_id.to_s
58+
if (message_id = event.message_id)
5659
"#{event_id} (message_id: #{message_id})"
5760
else
5861
event_id
5962
end
6063
end
6164

62-
def id
63-
event["id"]
64-
end
65-
66-
def op
67-
event["op"]
68-
end
69-
70-
def type
71-
event["type"]
72-
end
73-
74-
def version
75-
event["version"]
76-
end
77-
78-
def record
79-
event["record"]
80-
end
81-
82-
def message_id
83-
event["message_id"]
84-
end
65+
def_delegators :event, :id, :op, :type, :version, :record, :message_id
8566
end
8667
end
8768
end

‎elasticgraph-indexer/lib/elastic_graph/indexer/ingestion_adapter.rb‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ module IngestionAdapter
1515
# Defines the ingestion adapter interface. Adapter classes are not required to subclass this,
1616
# but must implement these methods.
1717
class Interface
18-
# Validates the given event and resolves the record preparer appropriate for the event's
19-
# ingestion schema version. The indexer selects this adapter from the event's format tag.
20-
# The indexer builds operations from the event in the returned result, so an adapter can
21-
# return a prepared copy of the event.
18+
# Validates the record of the given event and resolves the record preparer appropriate for
19+
# the event's ingestion schema version. The indexer selects this adapter from the event's
20+
# format tag. The indexer builds operations from the event in the returned result, so an
21+
# adapter can return a prepared copy of the event.
2222
#
23-
# @param event [Hash<String, Object>] an ElasticGraph indexing event
24-
# @param skip_record_validation [Boolean] whether to skip record validation; the event envelope must still be validated
23+
# @param event [Event] an ElasticGraph indexing event with a validated envelope
24+
# @param skip_record_validation [Boolean] whether to skip record validation
2525
# @return [ValidationResult] the result of validating the event
2626
def validate_event(event, skip_record_validation: false)
2727
# simplecov:disable -- must return a result to satisfy Steep type checking but never called
@@ -42,7 +42,7 @@ def validate_event(event, skip_record_validation: false)
4242
# and a non-nil `record_preparer` indicates a valid event.
4343
#
4444
# @!attribute [r] event
45-
# @return [Hash<String, Object>, nil] the event to build operations from, when the event is valid
45+
# @return [Event, nil] the event to build operations from, when the event is valid
4646
# @!attribute [r] record_preparer
4747
# @return [Object, nil] preparer for the event's record, when the event is valid
4848
# @!attribute [r] failure
@@ -52,7 +52,7 @@ def validate_event(event, skip_record_validation: false)
5252

5353
# Builds a result for a valid event.
5454
#
55-
# @param event [Hash<String, Object>] the event to build operations from; an adapter may return a prepared copy
55+
# @param event [Event] the event to build operations from; an adapter may return a prepared copy
5656
# @param record_preparer [Object] preparer for the event's record
5757
# @return [ValidationResult]
5858
def self.valid(event, record_preparer)

‎elasticgraph-indexer/lib/elastic_graph/indexer/operation/factory.rb‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class Factory < Support::MemoizableData.define(
2525
:skip_record_validation_percents_by_type
2626
)
2727
def build(event)
28-
format = event.fetch(INGESTION_FORMAT_KEY, "json")
28+
format = event.ingestion_format
2929
adapter = ingestion_adapters_by_format[format]
3030

3131
unless adapter
@@ -43,7 +43,7 @@ def build(event)
4343
private
4444

4545
def build_for_adapter(event, adapter)
46-
skip_record_validation = skip_validation?(event["type"], event)
46+
skip_record_validation = skip_validation?(event)
4747
validation_result = adapter.validate_event(event, skip_record_validation: skip_record_validation)
4848

4949
if (failure = validation_result.failure)
@@ -75,7 +75,7 @@ def build_success_result(event, record_preparer, type_with_skipped_validation:)
7575
# would have gotten had we validated up front. A clean bill of health from the validator means the
7676
# error was never about the data (a schema artifact defect, or a bug) and must not be swallowed.
7777
def build_success_result_isolating_malformed_records(event, record_preparer, adapter)
78-
build_success_result(event, record_preparer, type_with_skipped_validation: event.fetch("type"))
78+
build_success_result(event, record_preparer, type_with_skipped_validation: event.type)
7979
rescue => exception
8080
failure = adapter.validate_event(event).failure
8181
# `raise` is overridden below to stop this class from *originating* an error instead of returning a
@@ -89,18 +89,18 @@ def build_success_result_isolating_malformed_records(event, record_preparer, ada
8989
# configured percent with a single multiply instead of dividing on every event.
9090
CRC32_SPACE_PER_PERCENT = (1 << 32) / 100.0
9191

92-
# Decides whether to skip per-record validation for `event` of `type`. The decision is
92+
# Decides whether to skip per-record validation for `event`. The decision is
9393
# deterministic per event id: a stable `Zlib.crc32` of `EventID#to_s` maps each event to a
9494
# point in the CRC32 space, and we skip validation for the configured percentage of that
9595
# space. Same event id => same decision across pods and retries, so retries never flip a
9696
# record between validated and skipped. `String#hash` is unsuitable here, as `RUBY_HASH_SEED`
9797
# is per-process. The `<= 0` and `>= 100` guards keep the endpoints exact, so no float
9898
# boundary error can make a `0` percent skip a record or a `100` percent validate one.
99-
def skip_validation?(type, event)
100-
percent = skip_record_validation_percents_by_type[type]
99+
def skip_validation?(event)
100+
percent = skip_record_validation_percents_by_type[event.type]
101101
return false if percent.nil? || percent <= 0
102102
return true if percent >= 100
103-
::Zlib.crc32(EventID.from_event(event).to_s) < percent * CRC32_SPACE_PER_PERCENT
103+
::Zlib.crc32(event.event_id.to_s) < percent * CRC32_SPACE_PER_PERCENT
104104
end
105105

106106
def build_failed_result(event, validation_target, validation_message)
@@ -120,8 +120,8 @@ def build_failed_result(event, validation_target, validation_message)
120120
rescue => exception
121121
logger.warn({
122122
"message_type" => "FailedEventOperationBuildingFailure",
123-
"message_id" => event["message_id"],
124-
"event_id" => EventID.from_event(event).to_s,
123+
"message_id" => event.message_id,
124+
"event_id" => event.event_id.to_s,
125125
"error_class" => exception.class.name,
126126
"error_message" => exception.message
127127
})
@@ -135,8 +135,7 @@ def build_all_operations_for(event, record_preparer)
135135
# If `type` is not a known type (as indicated by `runtime_metadata` being nil)
136136
# then we can't build a derived indexing type update operation. That case will only happen when we build
137137
# operations for an `FailedEventError` rather than to execute.
138-
type = event.fetch("type")
139-
return [] unless (runtime_metadata = schema_artifacts.runtime_metadata.object_types_by_name[type])
138+
return [] unless (runtime_metadata = schema_artifacts.runtime_metadata.object_types_by_name[event.type])
140139

141140
runtime_metadata.update_targets.flat_map do |update_target|
142141
ids_to_skip = skip_derived_indexing_type_updates.fetch(update_target.type, ::Set.new)
@@ -155,10 +154,10 @@ def build_all_operations_for(event, record_preparer)
155154
if skipped
156155
logger.info({
157156
"message_type" => "SkippingUpdate",
158-
"message_id" => event["message_id"],
157+
"message_id" => event.message_id,
159158
"update_target" => update_target.type,
160159
"id" => op.doc_id,
161-
"event_id" => EventID.from_event(event).to_s
160+
"event_id" => event.event_id.to_s
162161
})
163162
end
164163
end

‎elasticgraph-indexer/lib/elastic_graph/indexer/operation/result.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def event
4848
end
4949

5050
def event_id
51-
EventID.from_event(event)
51+
event.event_id
5252
end
5353

5454
def summary

‎elasticgraph-indexer/lib/elastic_graph/indexer/operation/update.rb‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ def self.operations_for(
2828
destination_index_mapping:
2929
)
3030
prepared_record = record_preparer.prepare_for_index(
31-
event["type"],
32-
event["record"] || {"id" => event["id"]},
31+
event.type,
32+
event.record,
3333
destination_index_mapping.fetch("properties")
3434
)
3535

@@ -78,15 +78,15 @@ def type
7878
end
7979

8080
def description
81-
if update_target.type == event.fetch("type")
81+
if update_target.type == event.type
8282
"#{update_target.type} update"
8383
else
84-
"#{update_target.type} update (from #{event.fetch("type")})"
84+
"#{update_target.type} update (from #{event.type})"
8585
end
8686
end
8787

8888
def inspect
89-
"#<#{self.class.name} event=#{EventID.from_event(event)} target=#{update_target.type}>"
89+
"#<#{self.class.name} event=#{event.event_id} target=#{update_target.type}>"
9090
end
9191
alias_method :to_s, :inspect
9292

@@ -141,7 +141,7 @@ def message_from_thrown_painless_exception(update)
141141
def script_params
142142
initial_params = update_target.params_for(
143143
doc_id: doc_id,
144-
event: event,
144+
event: event.to_h.transform_keys(&:to_s),
145145
prepared_record: prepared_record
146146
)
147147

‎elasticgraph-indexer/lib/elastic_graph/indexer/processor.rb‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def categorize_failures(failures, events)
109109
end
110110

111111
if superseded_failures.any?
112-
superseded_ids = superseded_failures.map { |f| EventID.from_event(f.event).to_s }
112+
superseded_ids = superseded_failures.map { |f| f.event.event_id.to_s }
113113
@logger.warn(
114114
"Ignoring #{superseded_ids.size} malformed event(s) because they have been superseded " \
115115
"by corrected events targeting the same id: #{superseded_ids.join(", ")}."
@@ -129,7 +129,7 @@ def calculate_latency_metrics(successful_operations, noop_results)
129129
latencies_in_ms_from = {} # : Hash[String, Integer]
130130
slo_results = {} # : Hash[String, String]
131131

132-
latency_timestamps = event.fetch("latency_timestamps", _ = {})
132+
latency_timestamps = event.latency_timestamps
133133
latency_timestamps.each do |ts_name, ts_value|
134134
metric_value = ((current_time - Time.iso8601(ts_value)) * 1000).round
135135

@@ -144,10 +144,10 @@ def calculate_latency_metrics(successful_operations, noop_results)
144144

145145
@logger.info({
146146
"message_type" => "ElasticGraphIndexingLatencies",
147-
"message_id" => event["message_id"],
148-
"event_type" => event.fetch("type"),
149-
"event_id" => EventID.from_event(event).to_s,
150-
JSON_SCHEMA_VERSION_KEY => event.fetch(JSON_SCHEMA_VERSION_KEY),
147+
"message_id" => event.message_id,
148+
"event_type" => event.type,
149+
"event_id" => event.event_id.to_s,
150+
"schema_version" => event.schema_version,
151151
"latencies_in_ms_from" => latencies_in_ms_from,
152152
"slo_results" => slo_results,
153153
"result" => result

0 commit comments

Comments
 (0)