|
| 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/json_ingestion/schema_definition/factory_extension" |
| 11 | +require "elastic_graph/json_ingestion/schema_definition/indexing/field_type/enum_extension" |
| 12 | +require "elastic_graph/json_ingestion/schema_definition/indexing/field_type/object_extension" |
| 13 | +require "elastic_graph/json_ingestion/schema_definition/indexing/field_type/scalar_extension" |
| 14 | +require "elastic_graph/json_ingestion/schema_definition/indexing/field_type/union_extension" |
| 15 | +require "elastic_graph/json_ingestion/schema_definition/state_extension" |
| 16 | +require "elastic_graph/graphql/scalar_coercion_adapters/valid_time_zones" |
| 17 | +require "elastic_graph/schema_definition/indexing/field_type/enum" |
| 18 | +require "elastic_graph/schema_definition/indexing/field_type/object" |
| 19 | +require "elastic_graph/schema_definition/indexing/field_type/scalar" |
| 20 | +require "elastic_graph/schema_definition/indexing/field_type/union" |
| 21 | + |
| 22 | +module ElasticGraph |
| 23 | + module JSONIngestion |
| 24 | + # Namespace for all JSON Schema schema definition support. |
| 25 | + # |
| 26 | + # {SchemaDefinition::APIExtension} is the primary entry point and should be used as a schema definition extension module. |
| 27 | + module SchemaDefinition |
| 28 | + # Module designed to be extended onto an {ElasticGraph::SchemaDefinition::API} instance |
| 29 | + # to add JSON Schema ingestion serializer capabilities. |
| 30 | + module APIExtension |
| 31 | + # Default JSON schema options applied to ElasticGraph's built-in scalar types when this extension |
| 32 | + # is loaded. Keyed by the un-overridden type name; the lookup at runtime maps each key through |
| 33 | + # `type_name_overrides` so renamed built-ins still receive the right options. |
| 34 | + BUILT_IN_SCALAR_JSON_SCHEMA_OPTIONS_BY_NAME = { |
| 35 | + "Boolean" => {type: "boolean"}, |
| 36 | + "Float" => {type: "number"}, |
| 37 | + "ID" => {type: "string"}, |
| 38 | + "Int" => {type: "integer", minimum: INT_MIN, maximum: INT_MAX}, |
| 39 | + "String" => {type: "string"}, |
| 40 | + "Cursor" => {type: "string"}, |
| 41 | + "Date" => {type: "string", format: "date"}, |
| 42 | + "DateTime" => {type: "string", format: "date-time"}, |
| 43 | + "LocalTime" => {type: "string", pattern: VALID_LOCAL_TIME_JSON_SCHEMA_PATTERN}, |
| 44 | + "TimeZone" => {type: "string", enum: GraphQL::ScalarCoercionAdapters::VALID_TIME_ZONES.to_a.freeze}, |
| 45 | + "Untyped" => {type: ["array", "boolean", "integer", "number", "object", "string"].freeze}, |
| 46 | + "JsonSafeLong" => {type: "integer", minimum: JSON_SAFE_LONG_MIN, maximum: JSON_SAFE_LONG_MAX}, |
| 47 | + "LongString" => {type: "integer", minimum: LONG_STRING_MIN, maximum: LONG_STRING_MAX} |
| 48 | + }.freeze |
| 49 | + |
| 50 | + # Wires up the factory extension when this module is extended onto an API instance. |
| 51 | + # |
| 52 | + # @param api [ElasticGraph::SchemaDefinition::API] the API instance to extend |
| 53 | + # @return [void] |
| 54 | + # @api private |
| 55 | + def self.extended(api) |
| 56 | + # Prepend our indexing-field-type extensions onto the core classes so they participate in |
| 57 | + # `to_json_schema` / `format_field_json_schema_customizations` / `json_schema_field_metadata_by_field_name`. |
| 58 | + # Guarded so re-extending an already-extended API instance is a no-op. |
| 59 | + ::ElasticGraph::SchemaDefinition::Indexing::FieldType::Enum.prepend(Indexing::FieldType::EnumExtension) unless ::ElasticGraph::SchemaDefinition::Indexing::FieldType::Enum < Indexing::FieldType::EnumExtension |
| 60 | + ::ElasticGraph::SchemaDefinition::Indexing::FieldType::Object.prepend(Indexing::FieldType::ObjectExtension) unless ::ElasticGraph::SchemaDefinition::Indexing::FieldType::Object < Indexing::FieldType::ObjectExtension |
| 61 | + ::ElasticGraph::SchemaDefinition::Indexing::FieldType::Scalar.prepend(Indexing::FieldType::ScalarExtension) unless ::ElasticGraph::SchemaDefinition::Indexing::FieldType::Scalar < Indexing::FieldType::ScalarExtension |
| 62 | + ::ElasticGraph::SchemaDefinition::Indexing::FieldType::Union.prepend(Indexing::FieldType::UnionExtension) unless ::ElasticGraph::SchemaDefinition::Indexing::FieldType::Union < Indexing::FieldType::UnionExtension |
| 63 | + |
| 64 | + state = api.state.extend(StateExtension) # : ::ElasticGraph::SchemaDefinition::State & StateExtension |
| 65 | + state.reserved_type_names << EVENT_ENVELOPE_JSON_SCHEMA_NAME |
| 66 | + api.factory.extend FactoryExtension |
| 67 | + |
| 68 | + # Build a lookup from final (post-`type_name_overrides`) names to JSON schema options. We can't |
| 69 | + # key directly on `type.name` because users may have overridden the names of built-in scalars |
| 70 | + # (e.g. `Cursor` → `PreCursor`); the keys in `BUILT_IN_SCALAR_JSON_SCHEMA_OPTIONS_BY_NAME` are |
| 71 | + # always the un-overridden names. |
| 72 | + options_by_final_name = BUILT_IN_SCALAR_JSON_SCHEMA_OPTIONS_BY_NAME.to_h do |name, options| |
| 73 | + [api.state.type_ref(name).to_final_form.name, options] |
| 74 | + end |
| 75 | + |
| 76 | + api.on_built_in_types do |type| |
| 77 | + if (options = options_by_final_name[type.name]) |
| 78 | + scalar_type = type # : ::ElasticGraph::SchemaDefinition::SchemaElements::ScalarType & SchemaElements::ScalarTypeExtension |
| 79 | + scalar_type.json_schema(**options) |
| 80 | + elsif type.name == api.state.type_ref("GeoLocation").to_final_form.name |
| 81 | + # @type var geo_location_type: ::ElasticGraph::SchemaDefinition::SchemaElements::TypeWithSubfields & SchemaElements::ObjectInterfaceExtension |
| 82 | + geo_location_type = _ = type |
| 83 | + names = api.state.schema_elements |
| 84 | + |
| 85 | + # We use `nullable: false` because `GeoLocation` is indexed as a single `geo_point` field, |
| 86 | + # and therefore can't support a `latitude` without a `longitude` or vice-versa. |
| 87 | + latitude = geo_location_type.graphql_fields_by_name.fetch(names.latitude) # : ::ElasticGraph::SchemaDefinition::SchemaElements::Field & SchemaElements::FieldExtension |
| 88 | + longitude = geo_location_type.graphql_fields_by_name.fetch(names.longitude) # : ::ElasticGraph::SchemaDefinition::SchemaElements::Field & SchemaElements::FieldExtension |
| 89 | + latitude.json_schema minimum: -90, maximum: 90, nullable: false |
| 90 | + longitude.json_schema minimum: -180, maximum: 180, nullable: false |
| 91 | + end |
| 92 | + end |
| 93 | + end |
| 94 | + |
| 95 | + # Defines the version number of the current JSON schema. Importantly, every time a change is made that impacts the JSON schema |
| 96 | + # artifact, the version number must be incremented to ensure that each different version of the JSON schema is identified by a unique |
| 97 | + # version number. The publisher will then include this version number in published events to identify the version of the schema it |
| 98 | + # was using. This avoids the need to deploy the publisher and ElasticGraph indexer at the same time to keep them in sync. |
| 99 | + # |
| 100 | + # @note While this is an important part of how ElasticGraph is designed to support schema evolution, it can be annoying constantly |
| 101 | + # have to increment this while rapidly changing the schema during prototyping. You can disable the requirement to increment this |
| 102 | + # on every JSON schema change by setting `enforce_json_schema_version` to `false` in your `Rakefile`. |
| 103 | + # |
| 104 | + # @param version [Integer] current version number of the JSON schema artifact |
| 105 | + # @return [void] |
| 106 | + # @see Local::RakeTasks#enforce_json_schema_version |
| 107 | + def json_schema_version(version) |
| 108 | + state = json_ingestion_state |
| 109 | + |
| 110 | + if !version.is_a?(Integer) || version < 1 |
| 111 | + raise Errors::SchemaError, "`json_schema_version` must be a positive integer. Specified version: #{version}" |
| 112 | + end |
| 113 | + |
| 114 | + if state.json_schema_version |
| 115 | + raise Errors::SchemaError, "`json_schema_version` can only be set once on a schema. Previously-set version: #{state.json_schema_version}" |
| 116 | + end |
| 117 | + |
| 118 | + state.json_schema_version = version |
| 119 | + state.json_schema_version_setter_location = caller_locations(1, 1).to_a.first |
| 120 | + nil |
| 121 | + end |
| 122 | + |
| 123 | + # Defines strictness of the JSON schema validation. By default, the JSON schema will require all fields to be provided by the |
| 124 | + # publisher (but they can be nullable) and will ignore extra fields that are not defined in the schema. Use this method to |
| 125 | + # configure this behavior. |
| 126 | + # |
| 127 | + # @param allow_omitted_fields [bool] Whether nullable fields can be omitted from indexing events. |
| 128 | + # @param allow_extra_fields [bool] Whether extra fields (e.g. beyond fields defined in the schema) can be included in indexing events. |
| 129 | + # @return [void] |
| 130 | + # |
| 131 | + # @note If you allow both omitted fields and extra fields, ElasticGraph's JSON schema validation will allow (and ignore) misspelled |
| 132 | + # field names in indexing events. For example, if the ElasticGraph schema has a nullable field named `parentId` but the publisher |
| 133 | + # accidentally provides it as `parent_id`, ElasticGraph would happily ignore the `parent_id` field entirely, because `parentId` |
| 134 | + # is allowed to be omitted and `parent_id` would be treated as an extra field. Therefore, we recommend that you only set one of |
| 135 | + # these to `true` (or none). |
| 136 | + def json_schema_strictness(allow_omitted_fields: false, allow_extra_fields: true) |
| 137 | + state = json_ingestion_state |
| 138 | + |
| 139 | + unless [true, false].include?(allow_omitted_fields) |
| 140 | + raise Errors::SchemaError, "`allow_omitted_fields` must be true or false" |
| 141 | + end |
| 142 | + |
| 143 | + unless [true, false].include?(allow_extra_fields) |
| 144 | + raise Errors::SchemaError, "`allow_extra_fields` must be true or false" |
| 145 | + end |
| 146 | + |
| 147 | + state.allow_omitted_json_schema_fields = allow_omitted_fields |
| 148 | + state.allow_extra_json_schema_fields = allow_extra_fields |
| 149 | + nil |
| 150 | + end |
| 151 | + |
| 152 | + private |
| 153 | + |
| 154 | + # Returns the API's `state` narrowed to include this gem's `StateExtension`. Centralizes |
| 155 | + # the Steep cast that's needed because Steep can't see the `extend(StateExtension)` applied |
| 156 | + # at runtime in `extended`. |
| 157 | + def json_ingestion_state |
| 158 | + state # : ::ElasticGraph::SchemaDefinition::State & StateExtension |
| 159 | + end |
| 160 | + end |
| 161 | + end |
| 162 | + end |
| 163 | +end |
0 commit comments