-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathelectric.ex
More file actions
717 lines (586 loc) · 20.1 KB
/
electric.ex
File metadata and controls
717 lines (586 loc) · 20.1 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
defmodule Phoenix.Sync.Electric do
@moduledoc """
A `Plug.Router` and `Phoenix.Router` compatible Plug handler that allows
you to mount the full Electric shape api into your application.
Unlike `Phoenix.Sync.Router.sync/2` this allows your app to serve
shapes defined by `table` parameters, much like the Electric application.
The advantage is that you're free to put your own authentication and
authorization Plugs in front of this endpoint, integrating the auth for
your shapes API with the rest of your app.
## Configuration
Before configuring your router, you must install and configure the
`:phoenix_sync` application.
See the documentation for [embedding electric](readme.html#installation-and-configuration) for
details on embedding Electric into your Elixir application.
## Plug Integration
Mount this Plug into your router using `Plug.Router.forward/2`.
defmodule MyRouter do
use Plug.Router, copy_opts_to_assign: :config
use Phoenix.Sync.Electric
plug :match
plug :dispatch
forward "/shapes",
to: Phoenix.Sync.Electric,
init_opts: [opts_in_assign: :config]
end
You **must** configure your `Plug.Router` with `copy_opts_to_assign` and
pass the key you configure here (in this case `:config`) to the
`Phoenix.Sync.Electric` plug in it's `init_opts`.
In your application, build your Electric configuration using
`Phoenix.Sync.plug_opts()` and pass the result to your router as
`phoenix_sync`:
# in application.ex
def start(_type, _args) do
children = [
{Bandit, plug: {MyRouter, phoenix_sync: Phoenix.Sync.plug_opts()}, port: 4000}
]
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)
end
## Phoenix Integration
Use `Phoenix.Router.forward/2` in your router:
defmodule MyAppWeb.Router do
use Phoenix.Router
pipeline :shapes do
# your authz plugs
end
scope "/shapes" do
pipe_through [:shapes]
forward "/", Phoenix.Sync.Electric
end
end
As for the Plug integration, include the configuration at runtime
within the `Application.start/2` callback.
# in application.ex
def start(_type, _args) do
children = [
# ...
{MyAppWeb.Endpoint, phoenix_sync: Phoenix.Sync.plug_opts()}
]
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)
end
"""
import Phoenix.Sync.Application, only: [fetch_with_error: 2]
require Logger
@behaviour Phoenix.Sync.Adapter
@behaviour Plug
@valid_modes [:http, :embedded, :sandbox, :disabled]
@client_valid_modes @valid_modes -- [:disabled]
@electric_available? Code.ensure_loaded?(Electric.Application)
defmacro __using__(_opts \\ []) do
Phoenix.Sync.Plug.Utils.env!(__CALLER__)
quote do
Phoenix.Sync.Plug.Utils.opts_in_assign!(
[],
__MODULE__,
Phoenix.Sync.Plug.Shapes
)
end
end
@doc false
@impl Plug
def init(opts), do: Map.new(opts)
@doc false
@impl Plug
def call(%{private: %{phoenix_endpoint: endpoint}} = conn, _config) do
api = endpoint.config(:phoenix_sync)
serve_api(conn, api)
end
def call(conn, %{opts_in_assign: key}) do
api =
get_in(conn.assigns, [key, :phoenix_sync]) ||
raise "Unable to retrieve the Electric API configuration from the assigns"
serve_api(conn, api)
end
@doc false
def serve_api(conn, api) do
conn = Plug.Conn.fetch_query_params(conn)
Phoenix.Sync.Adapter.PlugApi.call(api, conn, conn.params)
end
@doc false
def valid_modes, do: @valid_modes
@doc false
@impl Phoenix.Sync.Adapter
def children(env, opts) do
{mode, electric_opts} =
opts
|> set_environment_defaults(env)
|> electric_opts(env)
case mode do
:disabled ->
{:ok, []}
:sandbox ->
if Phoenix.Sync.sandbox_enabled?() do
{:ok, [Phoenix.Sync.Sandbox]}
else
{:error,
"Sandbox mode is only available if `:ecto_sql` and `:electric` are listed as dependencies"}
end
mode when mode in @valid_modes ->
embedded_children(env, mode, electric_opts)
invalid_mode ->
{:error,
"Invalid mode `#{inspect(invalid_mode)}`. Valid modes are: #{Enum.map_join(@valid_modes, " or ", &"`:#{&1}`")}"}
end
end
@doc false
@impl Phoenix.Sync.Adapter
def plug_opts(env, opts) do
{mode, electric_opts} =
opts
|> set_environment_defaults(env)
|> electric_opts(env)
# don't need to validate the mode here -- it will have already been
# validated by children/0 which is run at phoenix_sync startup before the
# plug opts call even comes through
case mode do
:disabled ->
[]
mode when mode in @valid_modes ->
plug_opts(env, mode, electric_opts)
mode ->
raise ArgumentError,
message:
"Invalid `mode` for phoenix_sync: #{inspect(mode)}. Valid modes are: #{Enum.map_join(@valid_modes, " or ", &"`:#{&1}`")}"
end
end
@doc false
@impl Phoenix.Sync.Adapter
def client(env, opts) do
{mode, electric_opts} =
opts |> set_environment_defaults(env) |> electric_opts(env)
case mode do
mode when mode in @client_valid_modes ->
env
|> core_configuration(electric_opts)
|> configure_client(mode)
invalid_mode ->
{:error, "Cannot configure client for mode #{inspect(invalid_mode)}"}
end
end
# if we want to set up per-run configuration, and avoid weird state errors in
# dev and test, then we have to write them to the application config, because
# `children/2`, `client/2` and `plug_opts/2` need to have consistent
# configuration values.
defp set_environment_defaults(opts, :test) do
opts
|> set_persistent_config(:stack_id, fn ->
"electric-stack#{System.monotonic_time()}"
end)
|> set_persistent_config(:replication_stream_id, fn ->
String.replace("phoenix_sync#{System.monotonic_time()}", "-", "_")
end)
|> set_persistent_config(:replication_slot_temporary?, true)
end
defp set_environment_defaults(opts, :dev) do
opts
|> set_environment_defaults(:prod)
|> set_persistent_config(:storage_dir, fn ->
Path.join([System.tmp_dir!(), "phoenix-sync#{System.monotonic_time()}"])
end)
end
defp set_environment_defaults(opts, _env) do
opts
|> set_persistent_config(:stack_id, "electric-embedded")
end
defp set_persistent_config(opts, key, value_fun) when is_function(value_fun) do
Keyword.put_new_lazy(opts, key, fn ->
value = value_fun.()
Application.put_env(:phoenix_sync, key, value)
value
end)
end
defp set_persistent_config(opts, key, value) do
set_persistent_config(opts, key, fn -> value end)
end
@doc false
def electric_available? do
@electric_available?
end
defp electric_opts(opts, env) do
Keyword.pop_lazy(opts, :mode, fn ->
default_mode(env)
end)
end
defp default_mode(:test) do
:disabled
end
if @electric_available? do
defp default_mode(_env) do
Logger.warning([
"missing mode configuration for :phoenix_sync. Electric is installed so assuming `embedded` mode"
])
:embedded
end
else
defp default_mode(_env) do
Logger.warning("No `:mode` configuration for :phoenix_sync, assuming `:disabled`")
:disabled
end
end
defp plug_opts(_env, :http, opts) do
case http_mode_plug_opts(opts) do
{:ok, config} -> config
{:error, reason} -> raise ArgumentError, message: reason
end
end
if @electric_available? do
defp plug_opts(env, :embedded, electric_opts) do
env
|> core_configuration(electric_opts)
|> Electric.Application.api_plug_opts()
|> Keyword.fetch!(:api)
end
if Phoenix.Sync.sandbox_enabled?() do
defp plug_opts(_env, :sandbox, _electric_opts) do
Phoenix.Sync.Sandbox.APIAdapter.new()
end
else
defp plug_opts(_env, :sandbox, _electric_opts) do
raise ArgumentError,
message:
"phoenix_sync configured in `mode: :sandbox` but Ecto.SQL not installed. Please add `:ecto_sql` to your dependencies or use `:http` mode."
end
end
else
defp plug_opts(_env, :embedded, _electric_opts) do
raise ArgumentError,
message:
"phoenix_sync configured in `mode: :embedded` but electric not installed. Please add `:electric` to your dependencies or use `:http` mode."
end
defp plug_opts(_env, :sandbox, _electric_opts) do
raise ArgumentError,
message:
"phoenix_sync configured in `mode: :sandbox` but electric not installed. Please add `:electric` to your dependencies or use `:http` mode."
end
end
defp embedded_children(_env, :disabled, _opts) do
{:ok, []}
end
defp embedded_children(env, mode, opts) do
electric_children(env, mode, opts)
end
defp electric_children(env, mode, opts) do
case validate_database_config(env, mode, opts) do
{:start, db_config_fun, message} ->
start_embedded(env, mode, db_config_fun, message)
:ignore ->
{:ok, []}
{:error, _} = error ->
error
end
end
if @electric_available? do
defp start_embedded(env, mode, db_config_fun, message) do
db_config = db_config_fun.()
electric_config = core_configuration(env, db_config)
Logger.info(message)
http_server =
case mode do
:http -> electric_api_server(electric_config)
_ -> []
end
{:ok,
[
{Electric.StackSupervisor, Electric.Application.configuration(electric_config)}
| http_server
]}
end
defp electric_api_server(opts) do
config = electric_http_config(opts)
cond do
Code.ensure_loaded?(Bandit) ->
Electric.Application.api_server(Bandit, config)
Code.ensure_loaded?(Plug.Cowboy) ->
Electric.Application.api_server(Plug.Cowboy, config)
true ->
raise RuntimeError,
message: "No HTTP server found. Please install either Bandit or Plug.Cowboy"
end
end
defp electric_http_config(opts) do
case Keyword.fetch(opts, :http) do
{:ok, http_opts} ->
opts
|> then(fn o ->
if(port = http_opts[:port], do: Keyword.put(o, :service_port, port), else: o)
end)
:error ->
opts
end
# TODO: remove this once https://github.com/electric-sql/electric/pull/2863
# is released
|> Keyword.put_new(:http_api_num_acceptors, nil)
end
else
defp start_embedded(_env, _mode, _db_config_fun, _message) do
{:error,
"Electric configured to start in embedded mode but :electric dependency not available"}
end
end
defp stack_id(opts) do
Keyword.put_new(opts, :stack_id, "electric-embedded")
end
defp core_configuration(env, opts) do
opts
|> env_defaults(env)
|> stack_id()
|> overrides()
end
defp env_defaults(opts, :dev) do
# can't use new tmp dir for every run in dev because the storage
# path must remain consistent between invocations of children(), plug_opts()
# and client()...
# if we want to use emphemeral dir for dev storage then we have to persist
# the storage_dir into the application config.
opts
|> Keyword.put_new(:send_cache_headers?, false)
end
defp env_defaults(opts, :test) do
stack_id = "electric-stack"
opts = Keyword.put_new(opts, :stack_id, stack_id)
opts
|> Keyword.put_new(
:storage,
{Electric.ShapeCache.InMemoryStorage,
table_base_name: :"electric-storage#{opts[:stack_id]}", stack_id: opts[:stack_id]}
)
|> Keyword.put_new(
:persistent_kv,
{Electric.PersistentKV.Memory, :new!, []}
)
end
defp env_defaults(opts, _) do
opts
end
defp overrides(opts) do
opts
|> Keyword.put_new(:stack_ready_timeout, 5_000)
end
# Returns a function to generate the config so that we can
# centralise the test for the existence of electric.
# Need this because the convert_repo_config/1 function needs Electric
# installed too
defp validate_database_config(_env, mode, opts) do
case Keyword.pop(opts, :repo, nil) do
{nil, opts} ->
case {Keyword.get(opts, :connection_opts),
Keyword.get(opts, :replication_connection_opts)} do
{[_ | _] = connection_opts, _} ->
opts =
opts
|> Keyword.delete(:connection_opts)
|> Keyword.put(:replication_connection_opts, connection_opts)
{:start, fn -> opts end, start_message(connection_opts)}
{nil, [_ | _] = connection_opts} ->
{:start, fn -> opts end, start_message(connection_opts)}
{nil, nil} ->
case mode do
:embedded ->
{:error,
"No database configuration available. Include either a `repo` or a `connection_opts` in the phoenix_sync `electric` config"}
:http ->
:ignore
end
end
{repo, opts} when is_atom(repo) ->
if Code.ensure_loaded?(repo) && function_exported?(repo, :config, 0) do
repo_config = apply(repo, :config, [])
{:start,
fn ->
connection_opts = convert_repo_config(repo_config)
Keyword.put(opts, :replication_connection_opts, connection_opts)
end, "Starting Electric replication stream using #{repo} configuration"}
else
{:error, "#{inspect(repo)} is not a valid Ecto.Repo module"}
end
end
end
defp start_message(connection_opts) do
"Starting Electric replication stream from postgresql://#{connection_opts[:host]}:#{connection_opts[:port] || 5432}/#{connection_opts[:database]}"
end
if @electric_available? do
defp convert_repo_config(repo_config) do
expected_keys = Electric.connection_opts_schema() |> Keyword.keys()
ssl_opts =
case Keyword.get(repo_config, :ssl, nil) do
off when off in [nil, false] -> [sslmode: :disable]
true -> [sslmode: :require]
_opts -> []
end
tcp_opts =
if :inet6 in Keyword.get(repo_config, :socket_options, []),
do: [ipv6: true],
else: []
repo_config
|> Keyword.take(expected_keys)
|> Keyword.merge(ssl_opts)
|> Keyword.merge(tcp_opts)
|> Keyword.put_new(:port, 5432)
end
else
defp convert_repo_config(_repo_config) do
[]
end
end
defp http_mode_plug_opts(electric_config) do
with {:ok, client} <- configure_client(electric_config, :http) do
# don't decode the body - just pass it directly
client = %{client | fetch: {Electric.Client.Fetch.HTTP, [request: [raw: true]]}}
{:ok, %Phoenix.Sync.Electric.ClientAdapter{client: client}}
end
end
if @electric_available? do
defp configure_client(opts, :embedded) do
Electric.Client.embedded(opts)
end
# with a sandbox config, we're basically abandoning the idea of connecting
# to a real instance -- I think that's reasonable. The overhead of a real
# electric consuming a real replication stream is way too high for a simple
# consumer of streams
if Phoenix.Sync.sandbox_enabled?() do
defp configure_client(_opts, :sandbox) do
Phoenix.Sync.Sandbox.client()
end
else
defp configure_client(_opts, :sandbox) do
{:error, "sandbox mode is only available if Ecto.SQL is installed"}
end
end
else
defp configure_client(_opts, :embedded) do
{:error, "electric not installed, unable to created embedded client"}
end
defp configure_client(_opts, :sandbox) do
{:error, "electric not installed, unable to created sandbox client"}
end
end
defp configure_client(electric_config, :http) do
with {:ok, url} <- fetch_with_error(electric_config, :url),
credential_params = electric_config |> Keyword.get(:credentials, []) |> Map.new(),
extra_params = electric_config |> Keyword.get(:params, []) |> Map.new(),
params = Map.merge(extra_params, credential_params) do
Electric.Client.new(
base_url: url,
params: params
)
end
end
@doc false
def api_predefined_shape(conn, api, shape, response_fun) when is_function(response_fun, 2) do
case Phoenix.Sync.Adapter.PlugApi.predefined_shape(api, shape) do
{:ok, shape_api} ->
# response_fun should return conn
response_fun.(conn, shape_api)
# Only the embedded api will ever return an error from predefined_shape/2
# when the stack isn't ready (or the params are invalid, e.g. bad table).
# The client adapter just configures the client with the shape
# parameters, which can't error.
{:error, response} ->
conn
|> Plug.Conn.send_resp(response.status, Enum.into(response.body, []))
end
end
@json Phoenix.Sync.json_library()
@doc false
def map_response_body(body, nil) do
body
end
# empty body is a valid response but not valid JSON
def map_response_body("", _mapper) do
""
end
def map_response_body(body, mapper) when is_binary(body) and is_function(mapper, 1) do
body
|> @json.decode!()
|> map_response_body(mapper)
|> then(fn item -> [@json.encode_to_iodata!(item)] end)
end
def map_response_body(msgs, mapper) when is_list(msgs) and is_function(mapper, 1) do
msgs
|> Enum.flat_map(fn
%{"key" => _key, "headers" => _, "value" => _} = msg ->
mapper.(msg)
control ->
[control]
end)
end
def map_response_body(msgs, _mapper) do
msgs
end
if @electric_available? do
@doc false
# for the embedded api we need to make sure that the response stream is consumed
# in the same process that made the request, in order for cleanups to happen
# so we have to enumerate the body stream immediately before passing the response
# to any other process...
def consume_response_stream(%Electric.Shapes.Api.Response{} = response) do
Map.update!(response, :body, &do_consume_stream(&1))
end
defp do_consume_stream(body) do
Enum.to_list(body)
end
end
end
if Code.ensure_loaded?(Electric.Shapes.Api) do
Code.ensure_loaded(Phoenix.Sync.Electric.ApiAdapter)
defimpl Phoenix.Sync.Adapter.PlugApi, for: Electric.Shapes.Api do
alias Electric.Shapes
alias Phoenix.Sync.PredefinedShape
alias Phoenix.Sync.Electric.ApiAdapter
def predefined_shape(api, %PredefinedShape{} = shape) do
ApiAdapter.new(api, shape)
end
def call(api, %{method: "GET"} = conn, params) do
case Shapes.Api.validate(api, params) do
{:ok, request} ->
conn
|> content_type()
|> Plug.Conn.assign(:request, request)
|> Shapes.Api.serve_shape_log(request)
{:error, response} ->
conn
|> content_type()
|> Shapes.Api.Response.send(response)
|> Plug.Conn.halt()
end
end
def call(api, %{method: "DELETE"} = conn, params) do
case Shapes.Api.validate_for_delete(api, params) do
{:ok, request} ->
conn
|> content_type()
|> Plug.Conn.assign(:request, request)
|> Shapes.Api.delete_shape(request)
{:error, response} ->
conn
|> content_type()
|> Shapes.Api.Response.send(response)
|> Plug.Conn.halt()
end
end
def call(_api, %{method: "OPTIONS"} = conn, _params) do
Shapes.Api.options(conn)
end
def response(api, _conn, params) do
case Shapes.Api.validate(api, params) do
{:ok, request} ->
{
request,
Shapes.Api.serve_shape_log(request) |> Phoenix.Sync.Electric.consume_response_stream()
}
{:error, response} ->
{nil, response}
end
end
def send_response(_api, conn, {request, response}) do
conn
|> content_type()
|> Plug.Conn.assign(:request, request)
|> Plug.Conn.assign(:response, response)
|> Shapes.Api.Response.send(response)
end
defp content_type(conn) do
Plug.Conn.put_resp_content_type(conn, "application/json")
end
end
end