Packages
avrora
0.21.0
0.30.2
0.30.1
0.30.0
0.29.2
0.29.1
0.29.0
0.28.0
0.27.0
0.26.0
0.25.0
0.24.2
0.24.1
0.24.0
0.23.0
0.22.0
0.21.1
0.21.0
0.20.0
0.19.0
0.18.1
0.18.0
0.17.0
0.16.0
0.15.0
0.14.1
0.14.0
0.13.0
0.12.0
0.11.0
0.10.0
0.9.1
0.9.0
0.8.1
0.8.0
0.7.1
0.7.0
0.6.0
0.5.1
0.5.0
0.4.0
0.3.1
0.3.0
0.2.2
0.2.1
0.2.0
0.1.1-beta
0.1.0-beta
An Elixir library for working with Avro messages conveniently. It supports local schema files and Confluent® schema registry.
Current section
Files
Jump to
Current section
Files
lib/avrora/codec/plain.ex
defmodule Avrora.Codec.Plain do
@moduledoc """
An Avro encoder/decoder working with a plain Avro messages.
It works with a binary format, which doesn't include any schema inside
like Object Container File or the magic bytes for a Schema Registry.
"""
@behaviour Avrora.Codec
alias Avrora.AvroDecoderOptions
alias Avrora.Resolver
@impl true
def is_decodable(payload) when is_binary(payload), do: true
@impl true
def extract_schema(_payload), do: {:error, :schema_not_found}
@impl true
def decode(_payload), do: {:error, :schema_required}
@impl true
def decode(payload, schema: schema) when is_binary(payload) do
with {:ok, schema} <- resolve(schema), do: do_decode(payload, schema)
end
@impl true
def encode(payload, schema: schema) when is_binary(payload) or is_map(payload) do
with {:ok, schema} <- resolve(schema), do: do_encode(payload, schema)
end
defp resolve(schema) do
cond do
is_binary(schema.full_name) && is_reference(schema.lookup_table) -> {:ok, schema}
is_binary(schema.full_name) -> Resolver.resolve(schema.full_name)
true -> {:error, :unusable_schema}
end
end
defp do_decode(payload, schema) do
decoded =
:avro_binary_decoder.decode(
payload,
schema.full_name,
schema.lookup_table,
AvroDecoderOptions.options()
)
{:ok, decoded}
rescue
MatchError -> {:error, :schema_mismatch}
error -> {:error, error}
end
defp do_encode(payload, schema) do
encoded =
schema.lookup_table
|> :avro_binary_encoder.encode(schema.full_name, payload)
|> List.wrap()
|> :erlang.list_to_binary()
{:ok, encoded}
rescue
error -> {:error, error}
end
end