1billion 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 78c6eeb54b13842149735e3952342d1df6cc842d839ef2613ab514f88614e154
4
+ data.tar.gz: c36f261aeba5d655864b46799822cdda662460cc7ba3f282409b1bbc91cbfc3a
5
+ SHA512:
6
+ metadata.gz: e4645bfe43ecd62f36aa1b2ac00f4c3d6ad15c3f076a9ec9deb273a4ed170eb1e485d6cf6293722e74af25dd1bff7da97f46df7258f9f8656adeb3ac5f1ee0c1
7
+ data.tar.gz: 3aec8ade1e1dc23ae0f5b48fd532c3d81faffad982ad88e19f2b025febdeb92ba1298a834833d7eccab8529a6d68635806e44deb840df7687418bbc2ea8fbfea
data/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thadeu Esteves
4
+
5
+ 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:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
data/README.md ADDED
@@ -0,0 +1,205 @@
1
+ <h1 align="center">
2
+ <a href="https://1billion.clowk.in">1billion</a>
3
+ </h1>
4
+
5
+ <p align="center">
6
+ <b>Transactional e-mail on its own sending infrastructure.</b><br>
7
+ The official Ruby SDK.
8
+ </p>
9
+
10
+ <p align="center">
11
+ <a href="https://1billion.clowk.in"><b>Website</b></a> ·
12
+ <a href="https://1billion.clowk.in"><b>Get an API key</b></a> ·
13
+ <a href="https://1billion.clowk.in/openapi.yml"><b>API reference</b></a> ·
14
+ <a href="CHANGELOG.md"><b>Changelog</b></a>
15
+ </p>
16
+
17
+ <p align="center">
18
+ <a href="https://github.com/clowk-in/1billion-ruby/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/clowk-in/1billion-ruby/actions/workflows/ci.yml/badge.svg"></a>
19
+ <a href="https://rubygems.org/gems/1billion"><img alt="Gem Version" src="https://img.shields.io/gem/v/1billion.svg"></a>
20
+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-blue.svg"></a>
21
+ </p>
22
+
23
+ The official Ruby client of [1billion](https://1billion.clowk.in): transactional e-mail on its own sending
24
+ infrastructure. Send a login code, a receipt or a reset link from Rails or from plain Ruby, and read what
25
+ happened to each recipient.
26
+
27
+ - **Rails with one line.** An ActionMailer delivery method: your mailers do not change.
28
+ - **No dependencies.** Only the Ruby standard library (`net/http`, `json`).
29
+ - **Safe retries.** A `503` or a network error is tried again with the same `Idempotency-Key`, so a retry never
30
+ sends a mail twice.
31
+ - **Clear errors.** `OneBillion::NoCredits` and `OneBillion::Refused` tell you what to do next.
32
+ - **Address validation.** A verdict, a score and the signals of an address, before you send to it.
33
+
34
+ > Use it only on a server. An API key must never reach a browser.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ bundle add 1billion
40
+ ```
41
+
42
+ Ruby 3.1 or newer. The gem is named `1billion`; its code is under `OneBillion`, because a Ruby constant can
43
+ not start with a digit.
44
+
45
+ Make an API key in the [console](https://1billion.clowk.in), and verify the domain that you send from.
46
+
47
+ ## Rails (ActionMailer)
48
+
49
+ ```ruby
50
+ # config/environments/production.rb
51
+ config.action_mailer.delivery_method = :onebillion
52
+ config.action_mailer.onebillion_settings = { api_key: ENV["ONEBILLION_KEY"] }
53
+ ```
54
+
55
+ That is all. Your mailers and views do not change:
56
+
57
+ ```ruby
58
+ class UserMailer < ApplicationMailer
59
+ def login_code(user, code)
60
+ @code = code
61
+
62
+ mail(to: user.email, subject: "Your code")
63
+ end
64
+ end
65
+
66
+ UserMailer.login_code(user, "482913").deliver_later
67
+ ```
68
+
69
+ The gem sends the finished MIME message to every recipient (`to`, `cc` and `bcc`), and the `Message-ID` is
70
+ the `Idempotency-Key`: the same message sent twice goes out once. Send with `deliver_later`, so a slow
71
+ network never holds a web request.
72
+
73
+ | Setting | Default | What |
74
+ |---|---|---|
75
+ | `api_key` | (required) | the API key of the app |
76
+ | `url` | `https://1billion.clowk.in` | another console, for example a dev stack |
77
+
78
+ ## The client
79
+
80
+ ```ruby
81
+ client = OneBillion::Client.new(api_key: ENV["ONEBILLION_KEY"])
82
+
83
+ answer = client.send_mail(
84
+ from: "Acme <hi@acme.com>",
85
+ to: ["jane@example.com"],
86
+ subject: "Your code",
87
+ text: "Your code is 482 913",
88
+ html: "<p>Your code is <b>482 913</b></p>",
89
+ priority: "high",
90
+ idempotency_key: "login-jane-482913"
91
+ )
92
+
93
+ answer["messages"] # => [{ "id" => "9f2c…", "to" => "jane@example.com", "status" => "accepted" }]
94
+ ```
95
+
96
+ `send_mail` returns when 1billion has the mail (`202`, status `accepted`). The delivery runs after that, with
97
+ its own retries.
98
+
99
+ | Argument | What |
100
+ |---|---|
101
+ | `from` | a sender on a verified domain of the app, with a name or without one |
102
+ | `to`, `cc`, `bcc` | the recipients |
103
+ | `reply_to` | the reply address |
104
+ | `text`, `html` | the body: one of them or both |
105
+ | `attachments` | `[{ filename:, content_type:, content: }]`, with `content` in base64 |
106
+ | `priority` | `"normal"` (the default) or `"high"`: mail that a person waits for goes first |
107
+ | `raw` | a finished MIME message, in place of the fields above |
108
+ | `idempotency_key` | the same key in 30 days returns the first answer and sends nothing again |
109
+
110
+ When you do not pass an `idempotency_key`, the client makes one and uses it for its own retries.
111
+
112
+ ### Read a message
113
+
114
+ ```ruby
115
+ client.message("9f2c…")
116
+ # => { "id" => "9f2c…", "status" => "sent", "attempts" => 1, "last_error" => nil, ... }
117
+ ```
118
+
119
+ `status` is `accepted`, `queued`, `sending`, `sent`, `bounced` or `suppressed`. `sent` means that the mail
120
+ server of the recipient accepted the message. Messages stay for 30 days.
121
+
122
+ ### Validate an address
123
+
124
+ ```ruby
125
+ client.validate("jane@gmial.com")
126
+ # => { "result" => "risky", "reason" => "possible_typo", "score" => 0.3,
127
+ # "did_you_mean" => "jane@gmail.com", "disposable" => false, "role" => false, ... }
128
+ ```
129
+
130
+ `result` is `deliverable`, `risky` or `undeliverable`. A validation sends nothing and costs 100 credits.
131
+
132
+ ### Suppressions
133
+
134
+ A hard bounce or a complaint puts the address on the suppression list of the app, and 1billion stops sending
135
+ to it. When the address works again:
136
+
137
+ ```ruby
138
+ client.unsuppress("jane@example.com")
139
+ ```
140
+
141
+ ## Errors
142
+
143
+ ```ruby
144
+ begin
145
+ client.send_mail(**mail)
146
+ rescue OneBillion::NoCredits => error
147
+ # 429: no credits for these recipients today. They come back at 00:00 in the time
148
+ # zone of the workspace (error.body["retry_after"] seconds), or buy a pack
149
+ # (error.body["buy_url"]).
150
+ rescue OneBillion::Refused => error
151
+ # 422: a bad message, a domain that is not verified, or a recipient that failed a
152
+ # check (error.check, error.address).
153
+ rescue OneBillion::Error => error
154
+ # Any other answer: error.status and error.body. status is nil for a network error.
155
+ end
156
+ ```
157
+
158
+ | Status | Error | What |
159
+ |---|---|---|
160
+ | `401` | `OneBillion::Error` | a bad API key |
161
+ | `403` | `OneBillion::Error` | the sends of the workspace are paused (low reputation); a person reviews it |
162
+ | `422` | `OneBillion::Refused` | fix the message or the recipient |
163
+ | `429` | `OneBillion::NoCredits` | no credits today |
164
+ | `503` | — | tried again by the client |
165
+
166
+ Only a `503` and a network error are tried again: 3 tries in all, with a wait that doubles (0.5 s, then 1 s).
167
+ No other error is tried again, because a second try gives the same answer.
168
+
169
+ ## Options
170
+
171
+ ```ruby
172
+ OneBillion::Client.new(
173
+ api_key: ENV["ONEBILLION_KEY"],
174
+ url: "http://localhost:3100", # https://1billion.clowk.in by default
175
+ timeout: 5, # seconds, 10 by default
176
+ backoff: 1 # the first wait between tries, 0.5 s by default
177
+ )
178
+ ```
179
+
180
+ Each request has the `User-Agent` `onebillion-ruby/<version>` (with `actionmailer` from the delivery
181
+ method), so the console shows which mails came from the SDK.
182
+
183
+ ## Start sending
184
+
185
+ 1. Make a free account on **[1billion.clowk.in](https://1billion.clowk.in)**: 100 mails a day for free, every day, and your first domain for free.
186
+ 2. Add your domain. The console gives you the DNS records, and checks them for you.
187
+ 3. Make an API key, then `bundle add 1billion`.
188
+
189
+ Your first mail goes out in a few minutes. A question about the SDK? [Open an issue](https://github.com/clowk-in/1billion-ruby/issues).
190
+
191
+ ## Docs
192
+
193
+ - API reference: [openapi.yml](https://1billion.clowk.in/openapi.yml)
194
+ - Changes: [CHANGELOG.md](CHANGELOG.md)
195
+ - Other SDKs: [Go](https://github.com/clowk-in/1billion-go) and
196
+ [JavaScript](https://github.com/clowk-in/1billion-js) (Node.js, Next.js, Bun)
197
+
198
+ ## Contributing
199
+
200
+ Bug reports and pull requests are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) first. For a security
201
+ problem, see [SECURITY.md](SECURITY.md). This project follows a [Code of Conduct](CODE_OF_CONDUCT.md).
202
+
203
+ ## License
204
+
205
+ [MIT](LICENSE)
data/lib/1billion.rb ADDED
@@ -0,0 +1,3 @@
1
+ # The gem is named 1billion; its code lives under OneBillion (a Ruby constant can not start with
2
+ # a digit). Bundler requires this file by the gem name.
3
+ require "onebillion"
@@ -0,0 +1,109 @@
1
+ require "json"
2
+ require "net/http"
3
+ require "securerandom"
4
+ require "uri"
5
+
6
+ module OneBillion
7
+ # The client of the 1billion API. Use it only on a server: an API key must never reach a
8
+ # browser.
9
+ #
10
+ # client = OneBillion::Client.new(api_key: ENV["ONEBILLION_KEY"])
11
+ # client.send_mail(from: "App <hi@app.com>", to: ["ana@example.com"], subject: "Oi", text: "Olá")
12
+ #
13
+ # A 503 or a network error is tried again (3 times in all) with the same Idempotency-Key, so
14
+ # a retry never sends twice. No other error is tried again.
15
+ class Client
16
+ DEFAULT_URL = "https://1billion.clowk.in"
17
+ TRIES = 3
18
+
19
+ # agent: a word added to the User-Agent (the delivery method of ActionMailer adds
20
+ # "actionmailer"), so the console shows where a mail came from.
21
+ def initialize(api_key:, url: DEFAULT_URL, timeout: 10, backoff: 0.5, transport: nil, agent: nil)
22
+ raise ArgumentError, "api_key is required" if api_key.to_s.empty?
23
+
24
+ @api_key = api_key
25
+ @agent = agent
26
+ @url = URI(url)
27
+ @timeout = timeout
28
+ @backoff = backoff
29
+ @transport = transport || method(:http)
30
+ end
31
+
32
+ # POST /send. `text:` and `html:` go in the body; `raw:` sends a finished MIME message.
33
+ # Returns the parsed answer: { "messages" => [{ "id", "to", "status" }] }.
34
+ def send_mail(idempotency_key: nil, text: nil, html: nil, **fields)
35
+ body = fields.compact
36
+ body[:body] = { text: text, html: html }.compact if text || html
37
+
38
+ request(:post, "/send", body, idempotency_key: idempotency_key || SecureRandom.uuid)
39
+ end
40
+
41
+ def message(id) = request(:get, "/messages/#{URI.encode_www_form_component(id)}")
42
+
43
+ def unsuppress(address) = request(:delete, "/suppressions/#{URI.encode_www_form_component(address)}")
44
+
45
+ def validate(address) = request(:post, "/validate", { address: address })
46
+
47
+ def user_agent = ["onebillion-ruby/#{VERSION}", @agent].compact.join(" ")
48
+
49
+ private
50
+
51
+ def request(verb, path, body = nil, idempotency_key: nil)
52
+ headers = {
53
+ "Authorization" => "Bearer #{@api_key}",
54
+ "Content-Type" => "application/json",
55
+ "User-Agent" => user_agent
56
+ }
57
+ headers["Idempotency-Key"] = idempotency_key if idempotency_key
58
+
59
+ tries = 0
60
+
61
+ begin
62
+ tries += 1
63
+ status, text = @transport.call(verb, @url + path, headers, body && JSON.generate(body))
64
+
65
+ answer(status, text)
66
+ rescue Error => error
67
+ retry if retryable?(error) && tries < TRIES && pause(tries)
68
+
69
+ raise
70
+ end
71
+ end
72
+
73
+ def retryable?(error) = error.status.nil? || error.status == 503
74
+
75
+ def pause(tries)
76
+ sleep(@backoff * (2**(tries - 1)))
77
+
78
+ true
79
+ end
80
+
81
+ def answer(status, text)
82
+ body = text.to_s.empty? ? {} : JSON.parse(text)
83
+
84
+ return body if status.between?(200, 299)
85
+
86
+ message = body["error"] || "HTTP #{status}"
87
+
88
+ case status
89
+ when 429 then raise NoCredits.new(message, status: status, body: body)
90
+ when 422 then raise Refused.new(message, status: status, body: body)
91
+ else raise Error.new(message, status: status, body: body)
92
+ end
93
+ rescue JSON::ParserError
94
+ raise Error.new("HTTP #{status}: not JSON", status: status)
95
+ end
96
+
97
+ def http(verb, uri, headers, payload)
98
+ klass = { get: Net::HTTP::Get, post: Net::HTTP::Post, delete: Net::HTTP::Delete }.fetch(verb)
99
+ req = klass.new(uri, headers)
100
+ req.body = payload if payload
101
+
102
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: @timeout, read_timeout: @timeout) { |h| h.request(req) }
103
+
104
+ [response.code.to_i, response.body]
105
+ rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, IOError => error
106
+ raise Error.new(error.message)
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,27 @@
1
+ module OneBillion
2
+ # The ActionMailer delivery method. Your mailers stay as they are:
3
+ #
4
+ # config.action_mailer.delivery_method = :onebillion
5
+ # config.action_mailer.onebillion_settings = { api_key: ENV["ONEBILLION_KEY"] }
6
+ #
7
+ # It sends the finished MIME message (`raw`) to every envelope recipient (to, cc and bcc; Bcc
8
+ # is not in the message). The Message-ID is the Idempotency-Key, so a retried job never sends
9
+ # the mail twice.
10
+ class DeliveryMethod
11
+ attr_reader :settings
12
+
13
+ def initialize(settings = {})
14
+ @settings = settings
15
+ end
16
+
17
+ def deliver!(mail)
18
+ client.send_mail(to: mail.smtp_envelope_to, raw: mail.encoded, idempotency_key: mail.message_id || SecureRandom.uuid)
19
+ end
20
+
21
+ private
22
+
23
+ def client
24
+ @client ||= Client.new(api_key: settings.fetch(:api_key), url: settings.fetch(:url, Client::DEFAULT_URL), agent: "actionmailer")
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,25 @@
1
+ module OneBillion
2
+ # Any answer that is not a success. `status` is the HTTP status (nil for a network error)
3
+ # and `body` the parsed JSON, with `error` and, for a 422 of a check, `check` and `address`.
4
+ class Error < StandardError
5
+ attr_reader :status, :body
6
+
7
+ def initialize(message, status: nil, body: {})
8
+ @status = status
9
+ @body = body
10
+
11
+ super(message)
12
+ end
13
+ end
14
+
15
+ # 429: no credits for these recipients today. `body["retry_after"]` is the seconds until the
16
+ # credits of the next day (00:00 UTC), and `body["buy_url"]` the page to buy a pack.
17
+ class NoCredits < Error; end
18
+
19
+ # 422: a bad message, a domain that is not verified, or a recipient that failed a check.
20
+ class Refused < Error
21
+ def check = body["check"]
22
+
23
+ def address = body["address"]
24
+ end
25
+ end
@@ -0,0 +1,3 @@
1
+ module OneBillion
2
+ VERSION = "0.1.0"
3
+ end
data/lib/onebillion.rb ADDED
@@ -0,0 +1,14 @@
1
+ require_relative "onebillion/version"
2
+ require_relative "onebillion/errors"
3
+ require_relative "onebillion/client"
4
+ require_relative "onebillion/delivery_method"
5
+
6
+ # 1billion: transactional e-mail. See OneBillion::Client and OneBillion::DeliveryMethod.
7
+ module OneBillion
8
+ end
9
+
10
+ if defined?(ActionMailer)
11
+ ActionMailer::Base.add_delivery_method(:onebillion, OneBillion::DeliveryMethod)
12
+ elsif defined?(ActiveSupport)
13
+ ActiveSupport.on_load(:action_mailer) { add_delivery_method(:onebillion, OneBillion::DeliveryMethod) }
14
+ end
metadata ADDED
@@ -0,0 +1,47 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: 1billion
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Thadeu Esteves
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ executables: []
13
+ extensions: []
14
+ extra_rdoc_files: []
15
+ files:
16
+ - LICENSE
17
+ - README.md
18
+ - lib/1billion.rb
19
+ - lib/onebillion.rb
20
+ - lib/onebillion/client.rb
21
+ - lib/onebillion/delivery_method.rb
22
+ - lib/onebillion/errors.rb
23
+ - lib/onebillion/version.rb
24
+ homepage: https://1billion.clowk.in
25
+ licenses:
26
+ - MIT
27
+ metadata:
28
+ source_code_uri: https://github.com/clowk-in/1billion-ruby
29
+ rubygems_mfa_required: 'true'
30
+ rdoc_options: []
31
+ require_paths:
32
+ - lib
33
+ required_ruby_version: !ruby/object:Gem::Requirement
34
+ requirements:
35
+ - - ">="
36
+ - !ruby/object:Gem::Version
37
+ version: '3.1'
38
+ required_rubygems_version: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '0'
43
+ requirements: []
44
+ rubygems_version: 3.6.9
45
+ specification_version: 4
46
+ summary: Send transactional e-mail with 1billion, with an ActionMailer delivery method
47
+ test_files: []