Skip to content

Commit f3423ae

Browse files
ruslandogazoldar
andauthored
Add csv importer (#3795)
* add csv importer * make table validation explicit * update some docs * improve docs * add minio container to ci * more tests * eh * continue * add passing test * add failing test * add config test * add minio to Makefile * testcontainers * remove extra whitespace * explain the implementation a bit * account for async deletes in tests * bounces is UInt32 Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com> --------- Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
1 parent 31cf3e5 commit f3423ae

14 files changed

Lines changed: 698 additions & 10 deletions

File tree

‎.github/workflows/elixir.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ jobs:
7474
- name: Check Credo Warnings
7575
run: mix credo diff --from-git-merge-base origin/master
7676
- name: Run tests
77-
run: mix test --include slow --max-failures 1 --warnings-as-errors
77+
run: mix test --include slow --include minio --max-failures 1 --warnings-as-errors
7878
- name: Run tests (small build)
7979
run: MIX_ENV=small_test mix test --include slow --max-failures 1 --warnings-as-errors
8080
- name: Check Dialyzer

‎Makefile‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,9 @@ postgres-prod: ## Start a container with the same version of postgres as the one
3636

3737
postgres-stop: ## Stop and remove the postgres container
3838
docker stop plausible_db && docker rm plausible_db
39+
40+
minio: ## Start a transient container with a recent version of minio (s3)
41+
docker run -d --rm -p 6000:6000 -p 6001:6001 --name plausible_minio minio/minio server /data --address ":6000" --console-address ":6001"
42+
43+
minio-stop: ## Stop and remove the minio container
44+
docker stop plausible_minio

‎config/.env.dev‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,9 @@ GOOGLE_CLIENT_SECRET=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
2020

2121
PROMEX_DISABLED=false
2222
SITE_DEFAULT_INGEST_THRESHOLD=1000000
23+
24+
S3_DISABLED=false
25+
S3_ACCESS_KEY_ID=minioadmin
26+
S3_SECRET_ACCESS_KEY=minioadmin
27+
S3_REGION=us-east-1
28+
S3_ENDPOINT=http://localhost:6000

‎config/.env.test‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,9 @@ IP_GEOLOCATION_DB=test/priv/GeoLite2-City-Test.mmdb
1515
SITE_DEFAULT_INGEST_THRESHOLD=1000000
1616
GOOGLE_CLIENT_ID=fake_client_id
1717
GOOGLE_CLIENT_SECRET=fake_client_secret
18+
19+
S3_DISABLED=false
20+
S3_ACCESS_KEY_ID=minioadmin
21+
S3_SECRET_ACCESS_KEY=minioadmin
22+
S3_REGION=us-east-1
23+
S3_ENDPOINT=http://localhost:6000

‎config/runtime.exs‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,3 +718,61 @@ if not is_selfhost do
718718

719719
config :plausible, Plausible.Site, default_ingest_threshold: site_default_ingest_threshold
720720
end
721+
722+
s3_disabled? =
723+
config_dir
724+
|> get_var_from_path_or_env("S3_DISABLED", "true")
725+
|> String.to_existing_atom()
726+
727+
unless s3_disabled? do
728+
s3_env = [
729+
%{
730+
name: "S3_ACCESS_KEY_ID",
731+
example: "AKIAIOSFODNN7EXAMPLE"
732+
},
733+
%{
734+
name: "S3_SECRET_ACCESS_KEY",
735+
example: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
736+
},
737+
%{
738+
name: "S3_REGION",
739+
example: "us-east-1"
740+
},
741+
%{
742+
name: "S3_ENDPOINT",
743+
example: "https://<ACCOUNT_ID>.r2.cloudflarestorage.com"
744+
}
745+
]
746+
747+
s3_env =
748+
Enum.map(s3_env, fn var ->
749+
Map.put(var, :value, get_var_from_path_or_env(config_dir, var.name))
750+
end)
751+
752+
s3_missing_env = Enum.filter(s3_env, &is_nil(&1.value))
753+
754+
unless s3_missing_env == [] do
755+
raise ArgumentError, """
756+
Missing S3 configuration. Please set #{s3_missing_env |> Enum.map(& &1.name) |> Enum.join(", ")} environment variable(s):
757+
758+
#{s3_missing_env |> Enum.map(fn %{name: name, example: example} -> "\t#{name}=#{example}" end) |> Enum.join("\n")}
759+
"""
760+
end
761+
762+
s3_env_value = fn name ->
763+
s3_env |> Enum.find(&(&1.name == name)) |> Map.fetch!(:value)
764+
end
765+
766+
config :ex_aws,
767+
http_client: Plausible.S3.Client,
768+
access_key_id: s3_env_value.("S3_ACCESS_KEY_ID"),
769+
secret_access_key: s3_env_value.("S3_SECRET_ACCESS_KEY"),
770+
region: s3_env_value.("S3_REGION")
771+
772+
%URI{scheme: s3_scheme, host: s3_host, port: s3_port} = URI.parse(s3_env_value.("S3_ENDPOINT"))
773+
774+
config :ex_aws, :s3,
775+
scheme: s3_scheme <> "://",
776+
host: s3_host,
777+
port: s3_port
778+
end

‎lib/plausible/imported.ex‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@ defmodule Plausible.Imported do
77
* `Plausible.Imported.UniversalAnalytics` - existing mechanism, for legacy Google
88
analytics formerly known as "Google Analytics"
99
* `Plausible.Imported.NoopImporter` - importer stub, used mainly for testing purposes
10-
* `Plausible.Imported.CSVImporter` - a placeholder stub for CSV importer that will
11-
be added soon
10+
* `Plausible.Imported.CSVImporter` - CSV importer from S3
1211
1312
For more information on implementing importers, see `Plausible.Imported.Importer`.
1413
"""

‎lib/plausible/imported/csv_importer.ex‎

Lines changed: 93 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
defmodule Plausible.Imported.CSVImporter do
22
@moduledoc """
3-
CSV importer stub.
3+
CSV importer from S3 that uses ClickHouse [s3 table function.](https://clickhouse.com/docs/en/sql-reference/table-functions/s3)
44
"""
55

66
use Plausible.Imported.Importer
@@ -16,10 +16,99 @@ defmodule Plausible.Imported.CSVImporter do
1616
def email_template(), do: "google_analytics_import.html"
1717

1818
@impl true
19-
def parse_args(%{"s3_path" => s3_path}), do: [s3_path: s3_path]
19+
def parse_args(%{"uploads" => uploads}), do: [uploads: uploads]
2020

2121
@impl true
22-
def import_data(_site_import, _opts) do
23-
:ok
22+
def import_data(site_import, opts) do
23+
%{id: import_id, site_id: site_id} = site_import
24+
uploads = Keyword.fetch!(opts, :uploads)
25+
26+
%{access_key_id: s3_access_key_id, secret_access_key: s3_secret_access_key} =
27+
Plausible.S3.import_clickhouse_credentials()
28+
29+
{:ok, ch} =
30+
Plausible.IngestRepo.config()
31+
|> Keyword.replace!(:pool_size, 1)
32+
|> Ch.start_link()
33+
34+
ranges =
35+
Enum.map(uploads, fn upload ->
36+
%{"filename" => filename, "s3_url" => s3_url} = upload
37+
38+
".csv" = Path.extname(filename)
39+
table = Path.rootname(filename)
40+
ensure_importable_table!(table)
41+
42+
s3_structure = input_structure!(table)
43+
44+
statement =
45+
"""
46+
INSERT INTO {table:Identifier} \
47+
SELECT {site_id:UInt64} AS site_id, *, {import_id:UInt64} AS import_id \
48+
FROM s3({s3_url:String},{s3_access_key_id:String},{s3_secret_access_key:String},{s3_format:String},{s3_structure:String})\
49+
"""
50+
51+
params =
52+
%{
53+
"table" => table,
54+
"site_id" => site_id,
55+
"import_id" => import_id,
56+
"s3_url" => s3_url,
57+
"s3_access_key_id" => s3_access_key_id,
58+
"s3_secret_access_key" => s3_secret_access_key,
59+
"s3_format" => "CSVWithNames",
60+
"s3_structure" => s3_structure
61+
}
62+
63+
Ch.query!(ch, statement, params, timeout: :infinity)
64+
65+
%Ch.Result{rows: [[min_date, max_date]]} =
66+
Ch.query!(
67+
ch,
68+
"SELECT min(date), max(date) FROM {table:Identifier} WHERE site_id = {site_id:UInt64} AND import_id = {import_id:UInt64}",
69+
%{"table" => table, "site_id" => site_id, "import_id" => import_id}
70+
)
71+
72+
Date.range(min_date, max_date)
73+
end)
74+
75+
{:ok,
76+
%{
77+
start_date: Enum.min_by(ranges, & &1.first, Date).first,
78+
end_date: Enum.max_by(ranges, & &1.last, Date).last
79+
}}
80+
rescue
81+
# we are cancelling on any argument or ClickHouse errors
82+
e in [ArgumentError, Ch.Error] ->
83+
{:error, Exception.message(e)}
84+
end
85+
86+
input_structures = %{
87+
"imported_browsers" =>
88+
"date Date, browser String, visitors UInt64, visits UInt64, visit_duration UInt64, bounces UInt32",
89+
"imported_devices" =>
90+
"date Date, device String, visitors UInt64, visits UInt64, visit_duration UInt64, bounces UInt32",
91+
"imported_entry_pages" =>
92+
"date Date, entry_page String, visitors UInt64, entrances UInt64, visit_duration UInt64, bounces UInt32",
93+
"imported_exit_pages" => "date Date, exit_page String, visitors UInt64, exits UInt64",
94+
"imported_locations" =>
95+
"date Date, country String, region String, city UInt64, visitors UInt64, visits UInt64, visit_duration UInt64, bounces UInt32",
96+
"imported_operating_systems" =>
97+
"date Date, operating_system String, visitors UInt64, visits UInt64, visit_duration UInt64, bounces UInt32",
98+
"imported_pages" =>
99+
"date Date, hostname String, page String, visitors UInt64, pageviews UInt64, exits UInt64, time_on_page UInt64",
100+
"imported_sources" =>
101+
"date Date, source String, utm_medium String, utm_campaign String, utm_content String, utm_term String, visitors UInt64, visits UInt64, visit_duration UInt64, bounces UInt32",
102+
"imported_visitors" =>
103+
"date Date, visitors UInt64, pageviews UInt64, bounces UInt64, visits UInt64, visit_duration UInt64"
104+
}
105+
106+
for {table, input_structure} <- input_structures do
107+
defp input_structure!(unquote(table)), do: unquote(input_structure)
108+
defp ensure_importable_table!(unquote(table)), do: :ok
109+
end
110+
111+
defp ensure_importable_table!(table) do
112+
raise ArgumentError, "table #{table} is not supported for data import"
24113
end
25114
end

‎lib/plausible/s3.ex‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
defmodule Plausible.S3 do
2+
@moduledoc """
3+
Helper functions for S3 exports/imports.
4+
"""
5+
6+
@doc """
7+
Returns `access_key_id` and `secret_access_key` to be used by ClickHouse during imports from S3.
8+
"""
9+
@spec import_clickhouse_credentials ::
10+
%{access_key_id: String.t(), secret_access_key: String.t()}
11+
def import_clickhouse_credentials do
12+
%{access_key_id: access_key_id, secret_access_key: secret_access_key} = ExAws.Config.new(:s3)
13+
%{access_key_id: access_key_id, secret_access_key: secret_access_key}
14+
end
15+
end

‎lib/plausible/s3/client.ex‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
defmodule Plausible.S3.Client do
2+
@moduledoc false
3+
@behaviour ExAws.Request.HttpClient
4+
5+
@impl true
6+
def request(method, url, body, headers, opts) do
7+
req = Finch.build(method, url, headers, body)
8+
9+
case Finch.request(req, Plausible.Finch, opts) do
10+
{:ok, %Finch.Response{status: status, headers: headers, body: body}} ->
11+
{:ok, %{status_code: status, headers: headers, body: body}}
12+
13+
{:error, reason} ->
14+
{:error, %{reason: reason}}
15+
end
16+
end
17+
end

‎mix.exs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,11 @@ defmodule Plausible.MixProject do
136136
{:esbuild, "~> 0.7", runtime: Mix.env() in [:dev, :small_dev]},
137137
{:tailwind, "~> 0.2.0", runtime: Mix.env() in [:dev, :small_dev]},
138138
{:ex_json_logger, "~> 1.4.0"},
139-
{:ecto_network, "~> 1.5.0"}
139+
{:ecto_network, "~> 1.5.0"},
140+
{:ex_aws, "~> 2.5"},
141+
{:ex_aws_s3, "~> 2.5"},
142+
{:sweet_xml, "~> 0.7.4"},
143+
{:testcontainers, "~> 1.6", only: [:test, :small_test]}
140144
]
141145
end
142146

0 commit comments

Comments
 (0)