-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupabase_setup.py
executable file
·1581 lines (1479 loc) · 50.6 KB
/
supabase_setup.py
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Supabase Project Setup Tool
This script creates a new Supabase self-hosted deployment with custom port mappings.
"""
import os
import shutil
import socket
import argparse
import subprocess
import random
import string
from pathlib import Path
class SupabaseProjectGenerator:
def __init__(self, project_name, base_port=None):
"""Initialize the generator with project name and optional base port."""
self.project_dir = Path(project_name)
self.project_name = self.project_dir.name # Use only the base name for Compose volume names
self.base_port = base_port
# Prompt for CORS origin
protocol = input("Enter the protocol for your domain (http or https): ").strip()
if not protocol.endswith("://"):
protocol += "://"
domain = input("Enter your domain (e.g., example.com): ").strip()
self.origin = f"{protocol}{domain}"
# Calculate ports
self.ports = self._calculate_ports()
# Create project directory
self._create_project_directory()
# Templates and content
self.templates = {}
self._initialize_templates()
def run(self):
"""Create project subdirectories and write template files."""
# Define subdirectories to create
subdirs = [
"volumes/api",
"volumes/db/data",
"volumes/functions",
"volumes/logs",
"volumes/pooler",
"volumes/storage",
"volumes/analytics",
"volumes/db"
]
# Create subdirectories
for subdir in subdirs:
dir_path = self.project_dir / subdir
if dir_path.exists() and not dir_path.is_dir():
dir_path.unlink() # Remove file if it exists
dir_path.mkdir(parents=True, exist_ok=True)
# Ensure volumes/functions/main is a directory and add a sample function if missing
main_dir = self.project_dir / "volumes/functions/main"
if main_dir.exists() and not main_dir.is_dir():
main_dir.unlink() # Remove file if it exists
main_dir.mkdir(parents=True, exist_ok=True)
sample_function = main_dir / "index.ts"
if not sample_function.exists():
sample_function.write_text("""// Sample Supabase Edge Function
import { serve } from "https://deno.land/[email protected]/http/server.ts";
serve((_req) => new Response("Hello from Edge Functions!"));
""")
# Write template files
(self.project_dir / "docker-compose.yml").write_text(self.templates["docker_compose"])
(self.project_dir / ".env").write_text(self.templates["env"])
(self.project_dir / "volumes/api/kong.yml").write_text(self.templates["kong"])
self._write_vector_config() # Use the dynamic vector config method
(self.project_dir / "volumes/pooler/pooler.exs").write_text(self.templates["pooler"])
(self.project_dir / "volumes/db/_supabase.sql").write_text(self.templates["supabase_sql"])
(self.project_dir / "volumes/db/logs.sql").write_text(self.templates["logs_sql"])
(self.project_dir / "volumes/db/jwt.sql").write_text(self.templates["jwt_sql"])
(self.project_dir / "volumes/db/pooler.sql").write_text(self.templates["pooler_sql"])
(self.project_dir / "volumes/db/realtime.sql").write_text(self.templates["realtime_sql"])
(self.project_dir / "volumes/db/roles.sql").write_text(self.templates["roles_sql"])
(self.project_dir / "volumes/db/webhooks.sql").write_text(self.templates["webhooks_sql"])
(self.project_dir / "volumes/functions/main").write_text(self.templates["function_main"])
(self.project_dir / "reset.sh").write_text(self.templates["reset_script"])
(self.project_dir / "README.md").write_text(self.templates["readme"])
def _write_vector_config(self):
"""Write the vector.yml config with dynamic project/service names."""
vector_template = self.templates["vector"]
project_name = self.project_name
analytics_service = f"{project_name}-analytics"
kong_service = f"{project_name}-kong"
# Replace placeholders
vector_config = (
vector_template
.replace("__PROJECT__", project_name)
.replace("__ANALYTICS_SERVICE__", analytics_service)
.replace("__KONG_SERVICE__", kong_service)
)
# Write to the project directory
vector_path = self.project_dir / "volumes/logs/vector.yml"
vector_path.write_text(vector_config)
def _create_project_directory(self):
"""Create the project directory if it doesn't exist."""
if self.project_dir.exists():
raise FileExistsError(f"Directory {self.project_name} already exists.")
self.project_dir.mkdir(parents=True)
print(f"Created directory: {self.project_name}")
def _is_port_available(self, port):
"""Check if a port is available."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) != 0
def _find_available_port(self, start_port, step=1):
"""Find an available port starting from start_port."""
port = start_port
while not self._is_port_available(port):
port += step
return port
def _calculate_ports(self):
"""Calculate all required ports for the Supabase services."""
if self.base_port is None:
# Find a random available base port between 3000 and 9000
self.base_port = self._find_available_port(random.randint(3000, 9000))
ports = {
"kong_http": self._find_available_port(self.base_port),
"kong_https": self._find_available_port(self.base_port + 443),
"postgres": self._find_available_port(self.base_port + 1000),
"pooler": self._find_available_port(self.base_port + 1001),
"studio": self._find_available_port(self.base_port + 2000),
"analytics": self._find_available_port(self.base_port + 3000)
}
print(f"Using base port: {self.base_port}")
print(f"Kong HTTP port: {ports['kong_http']}")
print(f"Kong HTTPS port: {ports['kong_https']}")
print(f"PostgreSQL port: {ports['postgres']}")
print(f"Pooler port: {ports['pooler']}")
print(f"Studio port: {ports['studio']}")
print(f"Analytics port: {ports['analytics']}")
return ports
def _initialize_templates(self):
"""Initialize template content for various files."""
self._init_docker_compose_template()
self._init_env_template()
self._init_vector_template()
self._init_kong_template()
self._init_pooler_template()
self._init_db_templates()
self._init_function_templates()
self._init_misc_templates()
def _init_docker_compose_template(self):
"""Initialize docker-compose.yml template."""
self.templates["docker_compose"] = f"""
name: {self.project_name}
services:
studio:
container_name: {self.project_name}-studio
image: supabase/studio:latest
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "echo ok"]
interval: 10s
timeout: 5s
retries: 3
start_period: 30s
ports:
- "{self.ports['studio']}:3000"
environment:
STUDIO_PG_META_URL: http://{self.project_name}-meta:8080
POSTGRES_PASSWORD: ${{POSTGRES_PASSWORD}}
DEFAULT_ORGANIZATION_NAME: ${{STUDIO_DEFAULT_ORGANIZATION}}
DEFAULT_PROJECT_NAME: ${{STUDIO_DEFAULT_PROJECT}}
SUPABASE_URL: http://{self.project_name}-kong:8000
SUPABASE_PUBLIC_URL: ${{SUPABASE_PUBLIC_URL}}
SUPABASE_ANON_KEY: ${{ANON_KEY}}
SUPABASE_SERVICE_KEY: ${{SERVICE_ROLE_KEY}}
AUTH_JWT_SECRET: ${{JWT_SECRET}}
LOGFLARE_API_KEY: ${{LOGFLARE_API_KEY}}
LOGFLARE_URL: http://{self.project_name}-analytics:4000
NEXT_PUBLIC_ENABLE_LOGS: true
NEXT_ANALYTICS_BACKEND_PROVIDER: postgres
depends_on:
analytics:
condition: service_healthy
kong:
container_name: {self.project_name}-kong
image: kong:2.8.1
restart: unless-stopped
ports:
- "{self.ports['kong_http']}:8000/tcp"
- "{self.ports['kong_https']}:8443/tcp"
volumes:
- ./volumes/api/kong.yml:/home/kong/temp.yml:ro,z
depends_on:
analytics:
condition: service_healthy
environment:
KONG_DATABASE: "off"
KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml
KONG_DNS_ORDER: LAST,A,CNAME
KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth
KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k
KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k
SUPABASE_ANON_KEY: ${{ANON_KEY}}
SUPABASE_SERVICE_KEY: ${{SERVICE_ROLE_KEY}}
DASHBOARD_USERNAME: ${{DASHBOARD_USERNAME}}
DASHBOARD_PASSWORD: ${{DASHBOARD_PASSWORD}}
entrypoint: bash -c 'eval "echo \\"$$(cat ~/temp.yml)\\"" > ~/kong.yml && /docker-entrypoint.sh kong docker-start'
auth:
container_name: {self.project_name}-auth
image: supabase/gotrue:v2.170.0
restart: unless-stopped
healthcheck:
test:
[
"CMD",
"wget",
"--no-verbose",
"--tries=1",
"--spider",
"http://localhost:9999/health"
]
timeout: 5s
interval: 5s
retries: 3
depends_on:
db:
condition: service_healthy
analytics:
condition: service_healthy
environment:
GOTRUE_API_HOST: 0.0.0.0
GOTRUE_API_PORT: 9999
API_EXTERNAL_URL: ${{API_EXTERNAL_URL}}
GOTRUE_DB_DRIVER: postgres
# Use the internal port for PostgreSQL (5432) for container-to-container communication
GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:${{POSTGRES_PASSWORD}}@${{POSTGRES_HOST}}:5432/${{POSTGRES_DB}}
GOTRUE_SITE_URL: ${{SITE_URL}}
GOTRUE_URI_ALLOW_LIST: ${{ADDITIONAL_REDIRECT_URLS}}
GOTRUE_DISABLE_SIGNUP: ${{DISABLE_SIGNUP}}
GOTRUE_JWT_ADMIN_ROLES: service_role
GOTRUE_JWT_AUD: authenticated
GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated
GOTRUE_JWT_EXP: ${{JWT_EXPIRY}}
GOTRUE_JWT_SECRET: ${{JWT_SECRET}}
GOTRUE_EXTERNAL_EMAIL_ENABLED: ${{ENABLE_EMAIL_SIGNUP}}
GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: ${{ENABLE_ANONYMOUS_USERS}}
GOTRUE_MAILER_AUTOCONFIRM: ${{ENABLE_EMAIL_AUTOCONFIRM}}
GOTRUE_SMTP_ADMIN_EMAIL: ${{SMTP_ADMIN_EMAIL}}
GOTRUE_SMTP_HOST: ${{SMTP_HOST}}
GOTRUE_SMTP_PORT: ${{SMTP_PORT}}
GOTRUE_SMTP_USER: ${{SMTP_USER}}
GOTRUE_SMTP_PASS: ${{SMTP_PASS}}
GOTRUE_SMTP_SENDER_NAME: ${{SMTP_SENDER_NAME}}
GOTRUE_MAILER_URLPATHS_INVITE: ${{MAILER_URLPATHS_INVITE}}
GOTRUE_MAILER_URLPATHS_CONFIRMATION: ${{MAILER_URLPATHS_CONFIRMATION}}
GOTRUE_MAILER_URLPATHS_RECOVERY: ${{MAILER_URLPATHS_RECOVERY}}
GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: ${{MAILER_URLPATHS_EMAIL_CHANGE}}
GOTRUE_EXTERNAL_PHONE_ENABLED: ${{ENABLE_PHONE_SIGNUP}}
GOTRUE_SMS_AUTOCONFIRM: ${{ENABLE_PHONE_AUTOCONFIRM}}
rest:
container_name: {self.project_name}-rest
image: postgrest/postgrest:v12.2.8
restart: unless-stopped
depends_on:
db:
condition: service_healthy
analytics:
condition: service_healthy
environment:
# Use the internal port for PostgreSQL (5432) for container-to-container communication
PGRST_DB_URI: postgres://authenticator:${{POSTGRES_PASSWORD}}@${{POSTGRES_HOST}}:5432/${{POSTGRES_DB}}
PGRST_DB_SCHEMAS: ${{PGRST_DB_SCHEMAS}}
PGRST_DB_ANON_ROLE: anon
PGRST_JWT_SECRET: ${{JWT_SECRET}}
PGRST_DB_USE_LEGACY_GUCS: "false"
PGRST_APP_SETTINGS_JWT_SECRET: ${{JWT_SECRET}}
PGRST_APP_SETTINGS_JWT_EXP: ${{JWT_EXPIRY}}
command:
[
"postgrest"
]
realtime:
container_name: realtime-dev.{self.project_name}-realtime
image: supabase/realtime:v2.34.43
restart: unless-stopped
depends_on:
db:
condition: service_healthy
analytics:
condition: service_healthy
healthcheck:
test:
[
"CMD",
"curl",
"-sSfL",
"--head",
"-o",
"/dev/null",
"-H",
"Authorization: Bearer ${{ANON_KEY}}",
"http://localhost:4000/api/tenants/realtime-dev/health"
]
timeout: 5s
interval: 5s
retries: 3
environment:
PORT: 4000
DB_HOST: ${{POSTGRES_HOST}}
# Use the internal port for PostgreSQL (5432) for container-to-container communication
DB_PORT: 5432
DB_USER: supabase_admin
DB_PASSWORD: ${{POSTGRES_PASSWORD}}
DB_NAME: ${{POSTGRES_DB}}
DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime'
DB_ENC_KEY: supabaserealtime
API_JWT_SECRET: ${{JWT_SECRET}}
SECRET_KEY_BASE: ${{SECRET_KEY_BASE}}
ERL_AFLAGS: -proto_dist inet_tcp
DNS_NODES: "''"
RLIMIT_NOFILE: "10000"
APP_NAME: realtime
SEED_SELF_HOST: true
RUN_JANITOR: true
storage:
container_name: {self.project_name}-storage
image: supabase/storage-api:v1.19.3
restart: unless-stopped
volumes:
- ./volumes/storage:/var/lib/storage:z
healthcheck:
test:
[
"CMD",
"wget",
"--no-verbose",
"--tries=1",
"--spider",
"http://{self.project_name}-storage:5000/status"
]
timeout: 5s
interval: 5s
retries: 3
depends_on:
db:
condition: service_healthy
rest:
condition: service_started
imgproxy:
condition: service_started
environment:
ANON_KEY: ${{ANON_KEY}}
SERVICE_KEY: ${{SERVICE_ROLE_KEY}}
POSTGREST_URL: http://{self.project_name}-rest:3000
PGRST_JWT_SECRET: ${{JWT_SECRET}}
# Use the internal port for PostgreSQL (5432) for container-to-container communication
DATABASE_URL: postgres://supabase_storage_admin:${{POSTGRES_PASSWORD}}@${{POSTGRES_HOST}}:5432/${{POSTGRES_DB}}
FILE_SIZE_LIMIT: 52428800
STORAGE_BACKEND: file
FILE_STORAGE_BACKEND_PATH: /var/lib/storage
TENANT_ID: stub
REGION: stub
GLOBAL_S3_BUCKET: stub
ENABLE_IMAGE_TRANSFORMATION: "true"
IMGPROXY_URL: http://{self.project_name}-imgproxy:5001
imgproxy:
container_name: {self.project_name}-imgproxy
image: darthsim/imgproxy:v3.8.0
restart: unless-stopped
volumes:
- ./volumes/storage:/var/lib/storage:z
healthcheck:
test:
[
"CMD",
"imgproxy",
"health"
]
timeout: 5s
interval: 5s
retries: 3
environment:
IMGPROXY_BIND: ":5001"
IMGPROXY_LOCAL_FILESYSTEM_ROOT: /
IMGPROXY_USE_ETAG: "true"
IMGPROXY_ENABLE_WEBP_DETECTION: ${{IMGPROXY_ENABLE_WEBP_DETECTION}}
meta:
container_name: {self.project_name}-meta
image: supabase/postgres-meta:v0.87.1
restart: unless-stopped
depends_on:
db:
condition: service_healthy
analytics:
condition: service_healthy
environment:
PG_META_PORT: 8080
PG_META_DB_HOST: ${{POSTGRES_HOST}}
# Use the internal port for PostgreSQL (5432) for container-to-container communication
PG_META_DB_PORT: 5432
PG_META_DB_NAME: ${{POSTGRES_DB}}
PG_META_DB_USER: supabase_admin
PG_META_DB_PASSWORD: ${{POSTGRES_PASSWORD}}
functions:
container_name: {self.project_name}-edge-functions
image: supabase/edge-runtime:v1.67.4
restart: unless-stopped
volumes:
- ./volumes/functions:/home/deno/functions:Z
depends_on:
analytics:
condition: service_healthy
environment:
JWT_SECRET: ${{JWT_SECRET}}
SUPABASE_URL: http://{self.project_name}-kong:8000
SUPABASE_ANON_KEY: ${{ANON_KEY}}
SUPABASE_SERVICE_ROLE_KEY: ${{SERVICE_ROLE_KEY}}
# Use the internal port for PostgreSQL (5432) for container-to-container communication
SUPABASE_DB_URL: postgresql://postgres:${{POSTGRES_PASSWORD}}@${{POSTGRES_HOST}}:5432/${{POSTGRES_DB}}
VERIFY_JWT: "${{FUNCTIONS_VERIFY_JWT}}"
command:
[
"start",
"--main-service",
"/home/deno/functions/main"
]
analytics:
container_name: {self.project_name}-analytics
image: supabase/logflare:1.12.0
restart: unless-stopped
ports:
- "{self.ports['analytics']}:4000"
healthcheck:
test:
[
"CMD",
"curl",
"http://localhost:4000/health"
]
timeout: 5s
interval: 5s
retries: 10
depends_on:
db:
condition: service_healthy
environment:
LOGFLARE_NODE_HOST: 127.0.0.1
DB_USERNAME: supabase_admin
DB_DATABASE: _supabase
DB_HOSTNAME: ${{POSTGRES_HOST}}
# Use the internal port for Postgre
# SQL (5432) for container-to-container communication
DB_PORT: 5432
DB_PASSWORD: ${{POSTGRES_PASSWORD}}
DB_SCHEMA: _analytics
LOGFLARE_API_KEY: ${{LOGFLARE_API_KEY}}
LOGFLARE_SINGLE_TENANT: true
LOGFLARE_SUPABASE_MODE: true
LOGFLARE_MIN_CLUSTER_SIZE: 1
# Use the internal port for PostgreSQL (5432) for container-to-container communication
POSTGRES_BACKEND_URL: postgresql://supabase_admin:${{POSTGRES_PASSWORD}}@${{POSTGRES_HOST}}:5432/_supabase
POSTGRES_BACKEND_SCHEMA: _analytics
LOGFLARE_FEATURE_FLAG_OVERRIDE: multibackend=true
db:
container_name: {self.project_name}-db
image: supabase/postgres:15.8.1.060
restart: unless-stopped
volumes:
- ./volumes/db/realtime.sql:/docker-entrypoint-initdb.d/migrations/99-realtime.sql:Z
- ./volumes/db/webhooks.sql:/docker-entrypoint-initdb.d/init-scripts/98-webhooks.sql:Z
- ./volumes/db/roles.sql:/docker-entrypoint-initdb.d/init-scripts/99-roles.sql:Z
- ./volumes/db/jwt.sql:/docker-entrypoint-initdb.d/init-scripts/99-jwt.sql:Z
- ./volumes/db/data:/var/lib/postgresql/data:Z
- ./volumes/db/_supabase.sql:/docker-entrypoint-initdb.d/migrations/97-_supabase.sql:Z
- ./volumes/db/logs.sql:/docker-entrypoint-initdb.d/migrations/99-logs.sql:Z
- ./volumes/db/pooler.sql:/docker-entrypoint-initdb.d/migrations/99-pooler.sql:Z
- {self.project_name}_db-config:/etc/postgresql-custom
healthcheck:
test:
[
"CMD",
"pg_isready",
"-U",
"postgres",
"-d",
"_supabase",
"-h",
"localhost"
]
interval: 5s
timeout: 5s
retries: 10
depends_on:
vector:
condition: service_healthy
ports:
- "{self.ports['postgres']}:5432"
environment:
POSTGRES_HOST: /var/run/postgresql
PGPORT: 5432
POSTGRES_PORT: 5432
PGPASSWORD: ${{POSTGRES_PASSWORD}}
POSTGRES_PASSWORD: ${{POSTGRES_PASSWORD}}
PGDATABASE: ${{POSTGRES_DB}}
POSTGRES_DB: ${{POSTGRES_DB}}
JWT_SECRET: ${{JWT_SECRET}}
JWT_EXP: ${{JWT_EXPIRY}}
command:
[
"postgres",
"-c",
"config_file=/etc/postgresql/postgresql.conf",
"-c",
"log_min_messages=fatal"
]
vector:
container_name: {self.project_name}-vector
image: timberio/vector:0.28.1-alpine
restart: unless-stopped
volumes:
- ./volumes/logs/vector.yml:/etc/vector/vector.yml:ro,z
- /var/run/docker.sock:/var/run/docker.sock:ro,z
healthcheck:
test:
[
"CMD",
"wget",
"--no-verbose",
"--tries=1",
"--spider",
"http://{self.project_name}-vector:9001/health"
]
timeout: 5s
interval: 5s
retries: 3
environment:
LOGFLARE_API_KEY: ${{LOGFLARE_API_KEY}}
command:
[
"--config",
"/etc/vector/vector.yml"
]
security_opt:
- "label=disable"
pooler:
container_name: {self.project_name}-pooler
image: supabase/supavisor:2.4.14
restart: unless-stopped
ports:
- "{self.ports['pooler']}:6543"
volumes:
- ./volumes/pooler/pooler.exs:/etc/pooler/pooler.exs:ro,z
healthcheck:
test:
[
"CMD",
"curl",
"-sSfL",
"--head",
"-o",
"/dev/null",
"http://127.0.0.1:4000/api/health"
]
interval: 10s
timeout: 5s
retries: 5
depends_on:
db:
condition: service_healthy
analytics:
condition: service_healthy
environment:
PORT: 4000
POSTGRES_PORT: 5432
POSTGRES_DB: ${{POSTGRES_DB}}
POSTGRES_PASSWORD: ${{POSTGRES_PASSWORD}}
# Use the internal port for PostgreSQL (5432) for container-to-container communication
DATABASE_URL: ecto://supabase_admin:${{POSTGRES_PASSWORD}}@{self.project_name}-db:5432/_supabase
CLUSTER_POSTGRES: true
SECRET_KEY_BASE: ${{SECRET_KEY_BASE}}
VAULT_ENC_KEY: ${{VAULT_ENC_KEY}}
API_JWT_SECRET: ${{JWT_SECRET}}
METRICS_JWT_SECRET: ${{JWT_SECRET}}
REGION: local
ERL_AFLAGS: -proto_dist inet_tcp
POOLER_TENANT_ID: ${{POOLER_TENANT_ID}}
POOLER_DEFAULT_POOL_SIZE: ${{POOLER_DEFAULT_POOL_SIZE}}
POOLER_MAX_CLIENT_CONN: ${{POOLER_MAX_CLIENT_CONN}}
POOLER_POOL_MODE: transaction
command:
[
"/bin/sh",
"-c",
"/app/bin/migrate && /app/bin/supavisor eval \\"$$(cat /etc/pooler/pooler.exs)\\" && /app/bin/server"
]
volumes:
{self.project_name}_db-config:
networks:
default:
name: {self.project_name}-network
"""
def _init_env_template(self):
"""Initialize .env template."""
# Generate a random password and JWT secret
password = ''.join(random.choices(string.ascii_letters + string.digits, k=32))
jwt_secret = ''.join(random.choices(string.ascii_letters + string.digits, k=48))
secret_key_base = ''.join(random.choices(string.ascii_letters + string.digits, k=64))
vault_enc_key = ''.join(random.choices(string.ascii_letters + string.digits, k=32))
logflare_key = ''.join(random.choices(string.ascii_letters + string.digits, k=32))
self.templates["env"] = f"""############
# Secrets
# YOU MUST CHANGE THESE BEFORE GOING INTO PRODUCTION
############
POSTGRES_PASSWORD={password}
JWT_SECRET={jwt_secret}
ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE
SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q
DASHBOARD_USERNAME=supabase
DASHBOARD_PASSWORD={self.project_name}
SECRET_KEY_BASE={secret_key_base}
VAULT_ENC_KEY={vault_enc_key}
############
# Database - You can change these to any PostgreSQL database that has logical replication enabled.
############
# This is where other containers connect to the DB container internally
POSTGRES_HOST={self.project_name}-db
POSTGRES_DB=postgres
# This port is used for external connections from your host
POSTGRES_PORT={self.ports['postgres']}
# default user is postgres
############
# Supavisor -- Database pooler
############
POOLER_PROXY_PORT_TRANSACTION={self.ports['pooler']}
POOLER_DEFAULT_POOL_SIZE=20
POOLER_MAX_CLIENT_CONN=100
POOLER_TENANT_ID=your-tenant-id
############
# API Proxy - Configuration for the Kong Reverse proxy.
############
KONG_HTTP_PORT={self.ports['kong_http']}
KONG_HTTPS_PORT={self.ports['kong_https']}
############
# API - Configuration for PostgREST.
############
PGRST_DB_SCHEMAS=public,storage,graphql_public
############
# Auth - Configuration for the GoTrue authentication server.
############
## General
SITE_URL=http://localhost:{self.ports['studio']}
ADDITIONAL_REDIRECT_URLS=
JWT_EXPIRY=3600
DISABLE_SIGNUP=false
API_EXTERNAL_URL=http://localhost:{self.ports['kong_http']}
## Mailer Config
MAILER_URLPATHS_CONFIRMATION="/auth/v1/verify"
MAILER_URLPATHS_INVITE="/auth/v1/verify"
MAILER_URLPATHS_RECOVERY="/auth/v1/verify"
MAILER_URLPATHS_EMAIL_CHANGE="/auth/v1/verify"
## Email auth
ENABLE_EMAIL_SIGNUP=true
ENABLE_EMAIL_AUTOCONFIRM=true
SMTP_HOST={self.project_name}-mail
SMTP_PORT=2500
SMTP_USER=fake_mail_user
SMTP_PASS=fake_mail_password
SMTP_SENDER_NAME=fake_sender
ENABLE_ANONYMOUS_USERS=false
## Phone auth
ENABLE_PHONE_SIGNUP=true
ENABLE_PHONE_AUTOCONFIRM=true
############
# Studio - Configuration for the Dashboard
############
STUDIO_DEFAULT_ORGANIZATION="{self.project_name}"
STUDIO_DEFAULT_PROJECT="{self.project_name}"
STUDIO_PORT={self.ports['studio']}
# replace if you intend to use Studio outside of localhost
SUPABASE_PUBLIC_URL=http://localhost:{self.ports['kong_http']}
# Enable webp support
IMGPROXY_ENABLE_WEBP_DETECTION=true
# Add your OpenAI API key to enable SQL Editor Assistant
OPENAI_API_KEY=
############
# Functions - Configuration for Functions
############
# NOTE: VERIFY_JWT applies to all functions. Per-function VERIFY_JWT is not supported yet.
FUNCTIONS_VERIFY_JWT=false
############
# Logs - Configuration for Logflare
# Please refer to https://supabase.com/docs/reference/self-hosting-analytics/introduction
############
LOGFLARE_LOGGER_BACKEND_API_KEY={logflare_key}
# Change vector.toml sinks to reflect this change
LOGFLARE_API_KEY={logflare_key}
# Docker socket location - this value will differ depending on your OS
DOCKER_SOCKET_LOCATION=/var/run/docker.sock
# Google Cloud Project details
GOOGLE_PROJECT_ID=GOOGLE_PROJECT_ID
GOOGLE_PROJECT_NUMBER=GOOGLE_PROJECT_NUMBER"""
def _init_vector_template(self):
"""Initialize vector.yml template."""
try:
# Try to read the template from the file
# Use absolute path if available, otherwise try relative path
vector_path = Path("/home/osobh/projects/multibase/vector.yml")
if not vector_path.exists():
vector_path = Path("projects/multibase/vector.yml")
if vector_path.exists():
self.templates["vector"] = vector_path.read_text()
print(f"Using vector.yml template from {vector_path}")
else:
# Fallback to the default template if file doesn't exist
self.templates["vector"] = """# Default Vector configuration for Supabase
api:
enabled: true
address: 0.0.0.0:9001
# Data sources
sources:
docker_host:
type: docker_logs
exclude_containers:
- __PROJECT__-vector # Exclude vector logs from being ingested by itself
# Data transformations
transforms:
project_logs:
type: remap
inputs:
- docker_host
source: |-
.project = "__PROJECT__"
.event_message = del(.message)
.appname = del(.container_name)
del(.container_created_at)
del(.container_id)
del(.source_type)
del(.stream)
del(.label)
del(.image)
del(.host)
del(.stream)
router:
type: route
inputs:
- project_logs
route:
kong: '.appname == "__PROJECT__-kong"'
auth: '.appname == "__PROJECT__-auth"'
rest: '.appname == "__PROJECT__-rest"'
realtime: '.appname == "__PROJECT__-realtime"'
storage: '.appname == "__PROJECT__-storage"'
functions: '.appname == "__PROJECT__-functions"'
db: '.appname == "__PROJECT__-db"'
# Data destinations
sinks:
console_sink:
type: console
inputs:
- project_logs
encoding:
codec: json
target: stdout
analytics:
type: http
inputs:
- project_logs
encoding:
codec: json
uri: http://__ANALYTICS_SERVICE__:4000/api/logs
method: post
auth:
strategy: bearer
token: "${LOGFLARE_API_KEY}"
request:
headers:
Content-Type: application/json"""
print("Using default vector.yml template with placeholders")
except Exception as e:
print(f"Error loading vector template: {e}")
# Fallback to a minimal template
self.templates["vector"] = """# Default Vector configuration for Supabase
api:
enabled: true
address: 0.0.0.0:9001
# Data sources
sources:
docker_syslog:
type: docker_logs
docker_host: unix:///var/run/docker.sock
# Data transformations
transforms:
parse_logs:
type: remap
inputs:
- docker_syslog
source: |
.parsed = .message
.container_name = .container_name
.timestamp = .timestamp
# Data destinations
sinks:
console:
type: console
inputs:
- parse_logs
encoding:
codec: json
analytics:
type: http
inputs:
- parse_logs
encoding:
codec: json
uri: http://__ANALYTICS_SERVICE__:4000/api/logs
method: post
auth:
strategy: bearer
token: "${LOGFLARE_API_KEY}"
request:
headers:
Content-Type: application/json"""
print("Using minimal vector.yml template with analytics placeholder")
def _init_kong_template(self):
"""Initialize Kong API Gateway configuration."""
anon_key = self._extract_env_value("ANON_KEY")
service_key = self._extract_env_value("SERVICE_ROLE_KEY")
dashboard_username = self._extract_env_value("DASHBOARD_USERNAME")
dashboard_password = self._extract_env_value("DASHBOARD_PASSWORD")
origin = self.origin
self.templates["kong"] = f"""_format_version: '2.1'
_transform: true
consumers:
- username: DASHBOARD
- username: anon
keyauth_credentials:
- key: {anon_key}
- username: service_role
keyauth_credentials:
- key: {service_key}
acls:
- consumer: anon
group: anon
- consumer: service_role
group: admin
basicauth_credentials:
- consumer: DASHBOARD
username: {dashboard_username}
password: {dashboard_password}
services:
- name: auth-v1
url: http://{self.project_name}-auth:9999/verify
routes:
- name: auth-v1-route
paths:
- /auth/v1/verify
plugins:
- name: cors
config:
origins:
- {origin}
methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
headers:
- Accept
- Authorization
- Content-Type
- X-Requested-With
- apikey
- x-supabase-api-version
- x-client-info
- accept-profile
- content-profile
exposed_headers:
- Content-Length
- Content-Range
credentials: true
max_age: 3600
- name: auth-v1-api
url: http://{self.project_name}-auth:9999
routes:
- name: auth-v1-api-route
paths:
- /auth/v1
plugins:
- name: cors
config:
origins:
- {origin}
methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
headers:
- Accept
- Authorization
- Content-Type
- X-Requested-With
- apikey
- x-supabase-api-version
- x-client-info
- accept-profile
- content-profile
exposed_headers:
- Content-Length
- Content-Range
credentials: true
max_age: 3600
- name: auth-v1-admin
url: http://{self.project_name}-auth:9999/admin
routes:
- name: auth-v1-admin-route
paths:
- /auth/v1/admin
plugins:
- name: cors
config:
origins:
- {origin}
methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
headers:
- Accept
- Authorization
- Content-Type
- X-Requested-With
- apikey
- x-supabase-api-version
- x-client-info
- accept-profile
- content-profile
exposed_headers:
- Content-Length
- Content-Range
credentials: true
max_age: 3600
- name: key-auth