forked from peburrows/goth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoth.ex
286 lines (212 loc) · 8.2 KB
/
goth.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
defmodule Goth do
@moduledoc """
A Goth token server.
"""
use GenServer
require Logger
alias Goth.Token
@registry Goth.Registry
@max_retries 10
@refresh_before_minutes 5
@doc """
Starts the server.
When the server is started, we attempt to fetch the token and store it in
internal cache. If we fail, we'll retry with backoff.
## Options
* `:name` - a unique name to register the server under. It can be any term.
* `:source` - the source to retrieve the token from.
Supported values include:
* `{:service_account, credentials}` - fetch token using service account credentials
* `{:refresh_token, credentials}` - fetch token using refresh token
* `:metadata` - fetching token using Google internal metadata service
If `:source` is not set, Goth will:
* Check application environment. You can set it with: `config :goth, json: File.read!("credentials.json")`.
* Check `GOOGLE_APPLICATION_CREDENTIALS` env variable that contains path to credentials file.
* Check `GOOGLE_APPLICATION_CREDENTIALS_JSON` env variable that contains credentials JSON.
* Check `~/.config/gcloud/application_default_credentials.json` file.
* Check `~/.config/gcloud/configurations/config_default` for project id and email address for SDK users.
* Check Google internal metadata service
* Otherwise, raise an error.
See documentation of the "Source" section in `Goth.Token.fetch/1` documentation
for more information.
* `:refresh_before` - Time in seconds before the token is about to expire
that it is tried to be automatically refreshed. Defaults to
`#{@refresh_before_minutes * 60}` (#{@refresh_before_minutes} minutes).
* `:http_client` - a function that makes the HTTP request. Defaults to using built-in
integration with [Finch](https://github.com/sneako/finch)
See documentation of the `:http_client` option in `Goth.Token.fetch/1` for
more information.
* `:prefetch` - how to prefetch the token when the server starts. The possible options
are `:async` to do it asynchronously or `:sync` to do it synchronously
(that is, the server doesn't start until an attempt to fetch the token was made). Defaults
to `:async`.
* `:max_retries` - the maximum number of retries (default: `#{@max_retries}`)
* `:retry_delay` - a function that receives the retry count (starting at 0) and returns the delay, the
number of milliseconds to sleep before making another attempt.
Defaults to a simple exponential backoff capped at 30s: 1s, 2s, 4s, 8s, 16s, 30s, 30s, ...
## Examples
Generate a token using a service account credentials file:
iex> credentials = "credentials.json" |> File.read!() |> Jason.decode!()
iex> {:ok, _} = Goth.start_link(name: MyApp.Goth, source: {:service_account, credentials, []})
iex> Goth.fetch!(MyApp.Goth)
%Goth.Token{...}
Retrieve the token using a refresh token:
iex> credentials = "credentials.json" |> File.read!() |> Jason.decode!()
iex> {:ok, _} = Goth.start_link(name: MyApp.Goth, source: {:refresh_token, credentials, []})
iex> Goth.fetch!(MyApp.Goth)
%Goth.Token{...}
Retrieve the token using the Google metadata server:
iex> {:ok, _} = Goth.start_link(name: MyApp.Goth, source: {:metadata, []})
iex> Goth.fetch!(MyApp.Goth)
%Goth.Token{...}
"""
@doc since: "1.3.0"
def start_link(opts) do
opts =
opts
|> Keyword.put_new(:refresh_before, @refresh_before_minutes * 60)
|> Keyword.put_new(:http_client, {:finch, []})
|> Keyword.put_new(:source, {:default, []})
|> Keyword.put_new(:retry_delay, &exp_backoff/1)
name = Keyword.fetch!(opts, :name)
GenServer.start_link(__MODULE__, opts, name: registry_name(name))
end
def __finch__(options) do
{method, options} = Keyword.pop!(options, :method)
{url, options} = Keyword.pop!(options, :url)
{headers, options} = Keyword.pop!(options, :headers)
{body, options} = Keyword.pop!(options, :body)
finch_request = Finch.build(method, url, headers, body)
Finch.request(finch_request, Goth.Finch, options)
end
@doc """
Fetches the token from the cache.
If the token is not in the cache, this function blocks for `timeout`
milliseconds (defaults to `5000`) while it is attempted to fetch
it in the background.
To fetch the token bypassing the cache, see `Goth.Token.fetch/1`.
"""
@doc since: "1.3.0"
def fetch(name, timeout \\ 5000) do
read_from_ets(name) || GenServer.call(registry_name(name), :fetch, timeout)
end
@doc """
Fetches the token, erroring if it is missing.
See `fetch/2` for more information.
"""
@doc since: "1.3.0"
def fetch!(name, timeout \\ 5000) do
case fetch(name, timeout) do
{:ok, token} -> token
{:error, exception} -> raise exception
end
end
defstruct [
:name,
:source,
:retry_delay,
:http_client,
:retry_after,
:refresh_before,
max_retries: @max_retries,
retries: 0
]
defp read_from_ets(name) do
now = System.os_time(:second)
case Registry.lookup(@registry, name) do
[{_pid, %Token{expires: expires}}] when expires <= now -> nil
[{_pid, %Token{} = token}] -> {:ok, token}
_ -> nil
end
end
@impl true
def init(opts) when is_list(opts) do
{prefetch, opts} = Keyword.pop(opts, :prefetch, :async)
state = struct!(__MODULE__, opts)
state = Map.update!(state, :http_client, &start_http_client/1)
case prefetch do
:async ->
{:ok, state, {:continue, :async_prefetch}}
:sync ->
prefetch(state)
{:ok, state}
end
end
@impl true
def handle_continue(:async_prefetch, state) do
prefetch(state)
{:noreply, state}
end
defp prefetch(state) do
# given calculating JWT for each request is expensive, we do it once
# on system boot to hopefully fill in the cache.
case Token.fetch(state) do
{:ok, token} ->
store_and_schedule_refresh(state, token)
{:error, _} ->
send(self(), :refresh)
end
end
@impl true
def handle_call(:fetch, _from, state) do
reply = read_from_ets(state.name) || fetch_and_schedule_refresh(state)
{:reply, reply, state}
end
defp fetch_and_schedule_refresh(state) do
with {:ok, token} <- Token.fetch(state) do
store_and_schedule_refresh(state, token)
{:ok, token}
end
end
defp start_http_client(:finch) do
{&__finch__/1, []}
end
defp start_http_client({:finch, opts}) do
{&__finch__/1, opts}
end
defp start_http_client(fun) when is_function(fun, 1) do
{fun, []}
end
defp start_http_client({fun, opts}) when is_function(fun, 1) do
{fun, opts}
end
defp start_http_client({module, _} = config) when is_atom(module) do
Logger.warning("Setting http_client: mod | {mod, opts} is deprecated in favour of http_client: fun | {fun, opts}")
Goth.HTTPClient.init(config)
end
@impl true
def handle_info(:refresh, state) do
case Token.fetch(state) do
{:ok, token} -> do_refresh(token, state)
{:error, exception} -> handle_retry(exception, state)
end
end
defp handle_retry(exception, %{retries: retries, max_retries: max_retries}) when retries >= max_retries - 1 do
raise "too many failed attempts to refresh, last error: #{inspect(exception)}"
end
defp handle_retry(_, state) do
state = %{state | retries: state.retries + 1}
time_in_milliseconds = state.retry_delay.(state.retries)
Process.send_after(self(), :refresh, time_in_milliseconds)
{:noreply, state}
end
defp do_refresh(token, state) do
state = %{state | retries: 0}
store_and_schedule_refresh(state, token)
{:noreply, state}
end
defp store_and_schedule_refresh(state, token) do
put(state.name, token)
time_in_seconds = max(token.expires - System.os_time(:second) - state.refresh_before, 0)
Process.send_after(self(), :refresh, time_in_seconds * 1000)
end
defp exp_backoff(retry_count) do
min(30, round(:math.pow(2, retry_count))) * 1000
end
defp put(name, token) do
Registry.update_value(@registry, name, fn _ -> token end)
end
defp registry_name(name) do
{:via, Registry, {@registry, name}}
end
end