ExAwsConfigurator

Coverage Status hex.pm hex.pm hex.pm

Simple json based configurator for AWS SNS/SQS services, use to setup your topics and queues or/and to help to handle topics and queues with prefix or environment based name.

check our documentation

Requirements

Apps that can't meet these (older Elixir/OTP, or pinned to hackney 1.x, ex_aws < 2.7 or ex_aws_sns < 2.3.5) can stay on 1.x (~> 1.5).

Installation

The package can be installed by adding jason to your list of dependencies in mix.exs:

def deps do
  [
    {:ex_aws_configurator, "~> 2.0"}
  ]
end

Configuring ExAws

that package use ExAws to make requests to AWS, you will must to set ex_aws configuration into your config file to:

config :ex_aws,
  access_key_id: "<AWS_ACCESS_KEY_ID>",
  secret_access_key: "<AWS_SECRET_ACCESS_KEY>"

alternatively, you can set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY on your system environment, see ExAws for more.

Configuring ExAwsConfigurator

look for the config.exs example above:

config :ex_aws_configurator,
  account_id: "000000000000",
  queues: %{
    an_queue: %{
      environment: "an_environment",
      prefix: "queue_prefix",
      region: "us-east-1",
      topics: [:an_topic]
    },
    # ...
  },
  topics: %{
    an_topic: %{environment: "an_environment", prefix: "prefix", region: "us-east-1"},
    another_topic: %{},
    # ...
  }

assuming prod environment, when run ExAwsConfigurator.setup() will:

  1. create queue named queue_prefix_an_environment_an_queue on us-east-1 AWS region
  2. create topic named prefix_an_environment_an_topic on us-east-1 AWS region
  3. create topic named prod_another_topic on default AWS region
  4. subscribe queue queue_prefix_an_environment_an_queue into topic prefix_an_environment_an_topic

queue and topic name composition is: prefix + environment + key joined by _.

Name Default Required Description
account_id nil true your AWS account id, this is used to calculate topic/queue arn
queues [] true list of queues configuration
topics [] true list of topic configuration
environment Mix.env() no current environment, this is used to compose topic/queue name, use nil to skip
prefix nil no Used to compose topic/queue name.
region System.get_env("AWS_REGION") no use to specify aws region or to override ex_aws default region
topics [] no list of topics that the queue will subscribe to, must be an atom and the topic must be specified on topics list

ExAwsConfigurator.setup() is idempotent: topics and queues that already exist have their mutable attributes (policy, redrive policy, timeouts...) updated to match the configuration, so it is safe to run it on every deploy. It never deletes anything.

External accounts (topics owned by other AWS accounts)

To subscribe a queue to a topic that belongs to another AWS account (another business unit, for example), declare the account under accounts and reference it from the topic:

config :ex_aws_configurator,
  account_id: System.get_env("AWS_ACCOUNT_ID"),   # the default account
  region: "sa-east-1",
  accounts: %{
    health: %{id: System.get_env("AWS_HEALTH_ACCOUNT_ID"), region: "sa-east-1"}
  },
  topics: %{
    subscription_activated: %{prefix: "health_api", account: :health},
    pet_plan_canceled: %{prefix: "health_backoffice", account: :health, on_unauthorized: :warn},
    legacy_topic: %{arn: "arn:aws:sns:sa-east-1:111111111111:some-name-outside-our-convention"}
  },
  queues: %{
    traits_health_plan: %{prefix: "my_app", topics: [:subscription_activated, :pet_plan_canceled]}
  }

Account options:

Name Default Required Description
id nil true the AWS account id; accepts {:system, "ENV_VAR"}
region global region no region where the account resources live

Besides account_id, region, environment, prefix, separator and attributes, topics accept:

Name Default Required Description
account :default no name of the account (declared in accounts) that owns the topic
arn nil no raw topic ARN; replaces name composition, account and region
on_unauthorized global on_unauthorized (:error) no :error or :warn, what to do when the owner of an external topic refuses the subscription

ExAwsConfigurator.setup/0 needs, besides the create permissions, sqs:GetQueueUrl, sqs:SetQueueAttributes, sqs:TagQueue, sns:GetTopicAttributes and sns:SetTopicAttributes on your own account.

Telemetry

Every call that touches AWS (SNS.publish/3, SQS.send_message/3, setup/0 and each resource it ensures) is a :telemetry span: [:ex_aws_configurator, :publish | :send_message | :create_topic | :create_queue | :subscribe | :setup] with :start, :stop and :exception events. The metadata names the resource (topic/queue atom, ARN, region, account) and the :stop event carries result (:ok/:error) and the error. See ExAwsConfigurator.Telemetry for the full list.

To get them as metrics, add telemetry_metrics to your deps and append the ready-made definitions to the reporter your app already runs:

# lib/my_app_web/telemetry.ex
def metrics do
  [
    counter("my_app.api.request.count"),
    # ...
  ] ++ ExAwsConfigurator.Telemetry.metrics("my_app")
end

That gives my_app.sns.publish.count/.duration/.exception.count (tagged by topic and result), the same for my_app.sqs.send_message (tagged by queue) and my_app.setup.count/.duration.

Trace propagation

To link the consumer trace to the publisher one, configure a propagator: its headers are added as string message_attributes to every message published or sent. With opentelemetry_api in your deps:

config :ex_aws_configurator,
  propagator: ExAwsConfigurator.Propagator.OpenTelemetry

Any other tracer works through a module implementing ExAwsConfigurator.Propagator or a {module, function, args} returning {name, value} pairs.

On the consumer side (Broadway SQS), ask the producer for the attributes and continue the trace before processing the message:

alias ExAwsConfigurator.Propagator.OpenTelemetry, as: Propagation

# producer options
message_attribute_names: Propagation.header_names()

def handle_message(_processor, message, _context) do
  token = Propagation.extract(message.metadata.message_attributes)

  try do
    OpenTelemetry.Tracer.with_span "orders.process", %{kind: :consumer} do
      process(message)
    end
  after
    OpenTelemetry.Ctx.detach(token)
  end
end

Upgrading from 1.x

if you prefer more control on topics and queues creation you can use the create/subscribe functions separately

ExAwsConfigurator.SNS.create_topic(:an_topic)
ExAwsConfigurator.SQS.create_queue(:an_queue)
ExAwsConfigurator.SQS.subscribe(:an_queue, :an_topic)

Every function of ExAwsConfigurator.SNS and ExAwsConfigurator.SQS accepts either the atom that names the resource in the configuration (the key MUST be present on config.exs) or the %ExAwsConfigurator.Topic{}/%ExAwsConfigurator.Queue{} struct itself, which is handy to drive the adapters from a struct you built or fetched once:

queue = ExAwsConfigurator.get_queue(:an_queue)

ExAwsConfigurator.SQS.create_queue(queue)
for topic <- queue.topics, do: ExAwsConfigurator.SQS.subscribe(queue, topic)

this package provide some helpers to publish or send message too, for complete use please, check our documentation

Contributing

feel free to contribute, issues and pull requests are welcome

License

The MIT License (MIT)

Copyright (c) 2014-2020 CargoSense, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.