local-development-gateway 0.3.3 → 0.4.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.
Files changed (36) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +26 -28
  3. data/docker-compose.yml +19 -20
  4. data/docs/README.md +16 -0
  5. data/docs/architecture/gateway-lifecycle.md +39 -0
  6. data/docs/guides/consumer-developer-examples.md +369 -0
  7. data/docs/guides/docker-first-migration.md +180 -0
  8. data/docs/guides/docker-installation.md +84 -0
  9. data/docs/requirements/effective-gateway.md +37 -0
  10. data/examples/shared-databases/README.md +145 -0
  11. data/examples/shared-databases/app/.omp-verifier.json +10 -0
  12. data/examples/shared-databases/app/.oxlintrc.json +3 -0
  13. data/examples/shared-databases/app/Dockerfile +12 -0
  14. data/examples/shared-databases/app/app.mjs +91 -0
  15. data/examples/shared-databases/app/app.test.mjs +67 -0
  16. data/examples/shared-databases/app/database.mjs +31 -0
  17. data/examples/shared-databases/app/migrations/001_notes.cjs +10 -0
  18. data/examples/shared-databases/app/package-lock.json +1705 -0
  19. data/examples/shared-databases/app/package.json +18 -0
  20. data/examples/shared-databases/bin/dev +63 -0
  21. data/examples/shared-databases/bin/provision +24 -0
  22. data/examples/shared-databases/compose.yml +73 -0
  23. data/examples/shared-databases/consumer.yml +64 -0
  24. data/examples/shared-databases/gateway.yml +24 -0
  25. data/examples/shared-databases/provisioning/checkout.sh +12 -0
  26. data/examples/shared-databases/provisioning/postgres/database.sql +16 -0
  27. data/examples/shared-databases/provisioning/postgres/provision.sh +10 -0
  28. data/examples/shared-databases/provisioning/postgres/role.sql +11 -0
  29. data/examples/shared-databases/provisioning/sqlserver/database.sql +34 -0
  30. data/examples/shared-databases/provisioning/sqlserver/login.sql +18 -0
  31. data/examples/shared-databases/provisioning/sqlserver/provision.sh +10 -0
  32. data/lib/local_development_gateway/lifecycle.rb +133 -0
  33. data/lib/local_development_gateway/version.rb +1 -1
  34. data/lib/local_development_gateway.rb +150 -27
  35. metadata +31 -3
  36. data/config/traefik.yml +0 -11
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "shared-database-consumer-example",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "start": "node app.mjs",
7
+ "test": "node --test app.test.mjs",
8
+ "lint": "oxlint --deny-warnings ."
9
+ },
10
+ "dependencies": {
11
+ "knex": "3.3.0",
12
+ "pg": "8.16.3",
13
+ "tedious": "19.2.2"
14
+ },
15
+ "devDependencies": {
16
+ "oxlint": "1.94.0"
17
+ }
18
+ }
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env ruby
2
+ # Consumer-side Ruby convenience wrapper; the gateway does not require Ruby.
3
+ require "digest"
4
+
5
+ class Dev
6
+ ROOT = File.realpath("..", __dir__)
7
+
8
+ def call(command = "--help", *args)
9
+ case command
10
+ when "up", "down", "run", "test", "lint", "migrate"
11
+ public_send(command, *args)
12
+ else
13
+ compose(command, *args)
14
+ end
15
+ end
16
+
17
+ def up(*args)
18
+ compose(*%w[up -d --build --wait], *args)
19
+ end
20
+
21
+ def down(*args)
22
+ compose("down", *args)
23
+ end
24
+
25
+ def run(*args)
26
+ compose(*%w[run --rm --build --no-deps -T], *args)
27
+ end
28
+
29
+ def test(*args)
30
+ run(*%w[test_app npm test], *args)
31
+ end
32
+
33
+ def lint(*args)
34
+ run(*%w[lint npm run lint --], *args)
35
+ end
36
+
37
+ def migrate(*args)
38
+ run(*%w[app node app.mjs migrate], *args)
39
+ end
40
+
41
+ private
42
+
43
+ def compose(*args)
44
+ exec(dynamic_environment_variables, "docker", "compose", *args, chdir: ROOT)
45
+ end
46
+
47
+ def dynamic_environment_variables
48
+ path_hash = Digest::SHA256.hexdigest(ROOT)[0, 12]
49
+ checkout = ENV.fetch("COMPOSE_PROJECT_NAME", "checkout_#{path_hash}")
50
+
51
+ unless /\A[a-z][a-z0-9_]{0,31}\z/.match?(checkout)
52
+ abort "COMPOSE_PROJECT_NAME must match [a-z][a-z0-9_]{0,31}; use a unique name per checkout"
53
+ end
54
+
55
+ {
56
+ "COMPOSE_FILE" => ENV.fetch("COMPOSE_FILE", "consumer.yml"),
57
+ "COMPOSE_PROJECT_NAME" => checkout,
58
+ "CHECKOUT_NAME" => checkout
59
+ }
60
+ end
61
+ end
62
+
63
+ Dev.new.call(*ARGV)
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env ruby
2
+ # Project-owner operation, separate from normal checkout commands.
3
+ root = File.realpath("..", __dir__)
4
+ engine = ENV.fetch("DB_ENGINE", "sqlserver")
5
+
6
+ unless %w[postgres sqlserver].include?(engine)
7
+ abort "DB_ENGINE must be postgres or sqlserver"
8
+ end
9
+
10
+ abort "Usage: bin/provision CHECKOUT_NAME" unless ARGV.length == 1
11
+
12
+ exec(
13
+ { "CHECKOUT_NAME" => ARGV.fetch(0) },
14
+ "docker",
15
+ "compose",
16
+ "--project-name",
17
+ ENV.fetch("DB_SERVER_PROJECT", "gateway-example-shared"),
18
+ "run",
19
+ "--rm",
20
+ "--no-deps",
21
+ "-T",
22
+ "provision-#{engine}",
23
+ chdir: root
24
+ )
@@ -0,0 +1,73 @@
1
+ name: gateway-example-shared
2
+
3
+ services:
4
+ postgres:
5
+ image: postgres:17-alpine
6
+ environment:
7
+ POSTGRES_USER: example_admin
8
+ POSTGRES_PASSWORD: Example-Postgres-Admin9!
9
+ POSTGRES_DB: postgres
10
+ volumes:
11
+ - postgres-data:/var/lib/postgresql/data
12
+ networks:
13
+ default:
14
+ aliases:
15
+ - ${COMPOSE_PROJECT_NAME}-postgres
16
+ healthcheck:
17
+ test:
18
+ - CMD-SHELL
19
+ - pg_isready -U example_admin -d postgres
20
+ interval: 10s
21
+ timeout: 3s
22
+ retries: 30
23
+ start_period: 5s
24
+
25
+ sqlserver:
26
+ image: mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04
27
+ environment:
28
+ ACCEPT_EULA: 'Y'
29
+ MSSQL_PID: Developer
30
+ MSSQL_SA_PASSWORD: Example-Sql-Admin9!
31
+ volumes:
32
+ - sqlserver-data:/var/opt/mssql
33
+ networks:
34
+ default:
35
+ aliases:
36
+ - ${COMPOSE_PROJECT_NAME}-sqlserver
37
+ healthcheck:
38
+ test:
39
+ - CMD-SHELL
40
+ - /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "$$MSSQL_SA_PASSWORD" -C -b -Q "SELECT 1"
41
+ interval: 10s
42
+ timeout: 5s
43
+ retries: 30
44
+ start_period: 20s
45
+
46
+ provision-postgres:
47
+ image: postgres:17-alpine
48
+ profiles: [setup]
49
+ environment:
50
+ CHECKOUT_NAME: ${CHECKOUT_NAME:-}
51
+ PGHOST: postgres
52
+ PGUSER: example_admin
53
+ PGPASSWORD: Example-Postgres-Admin9!
54
+ PGDATABASE: postgres
55
+ volumes:
56
+ - ./provisioning/checkout.sh:/setup/checkout.sh:ro
57
+ - ./provisioning/postgres:/adapter:ro
58
+ entrypoint: [bash, /setup/checkout.sh]
59
+
60
+ provision-sqlserver:
61
+ image: mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04
62
+ profiles: [setup]
63
+ environment:
64
+ CHECKOUT_NAME: ${CHECKOUT_NAME:-}
65
+ SQLCMDPASSWORD: Example-Sql-Admin9!
66
+ volumes:
67
+ - ./provisioning/checkout.sh:/setup/checkout.sh:ro
68
+ - ./provisioning/sqlserver:/adapter:ro
69
+ entrypoint: [bash, /setup/checkout.sh]
70
+
71
+ volumes:
72
+ postgres-data: {}
73
+ sqlserver-data: {}
@@ -0,0 +1,64 @@
1
+ x-application: &application
2
+ build: ./app
3
+ environment: &development
4
+ DB_ENGINE: ${DB_ENGINE:-sqlserver}
5
+ APP_HOST: app-${CHECKOUT_NAME:?use bin/dev}
6
+ DB_HOST: ${DB_SERVER_PROJECT:-gateway-example-shared}-${DB_ENGINE:-sqlserver}
7
+ DB_NAME: app_${CHECKOUT_NAME:?use bin/dev}_development
8
+ DB_USER: app_${CHECKOUT_NAME:?use bin/dev}_development
9
+ DB_PASSWORD: Example-app_${CHECKOUT_NAME:?use bin/dev}_development-Only9!
10
+ networks:
11
+ - default
12
+ - database
13
+
14
+ services:
15
+ app:
16
+ <<: *application
17
+ networks:
18
+ default:
19
+ aliases:
20
+ - app-${CHECKOUT_NAME:?use bin/dev}
21
+ database: {}
22
+ healthcheck:
23
+ test:
24
+ - CMD
25
+ - node
26
+ - -e
27
+ - |
28
+ fetch("http://localhost:3000/notes")
29
+ .then((response) => {
30
+ if (!response.ok) {
31
+ process.exit(1)
32
+ }
33
+
34
+ process.exit(0)
35
+ })
36
+ .catch((error) => {
37
+ console.error(error)
38
+ process.exit(1)
39
+ })
40
+ interval: 2s
41
+ timeout: 3s
42
+ retries: 30
43
+ start_period: 10s
44
+
45
+ test_app:
46
+ <<: *application
47
+ profiles: [test]
48
+ command: [npm, test]
49
+ environment:
50
+ <<: *development
51
+ DB_NAME: app_${CHECKOUT_NAME:?use bin/dev}_test
52
+ DB_USER: app_${CHECKOUT_NAME:?use bin/dev}_test
53
+ DB_PASSWORD: Example-app_${CHECKOUT_NAME:?use bin/dev}_test-Only9!
54
+
55
+ lint:
56
+ build: ./app
57
+ profiles: [checks]
58
+ network_mode: none
59
+ command: [npm, run, lint]
60
+
61
+ networks:
62
+ database:
63
+ external: true
64
+ name: ${DB_SERVER_PROJECT:-gateway-example-shared}_default
@@ -0,0 +1,24 @@
1
+ # Optional: requires an already-running gateway; never starts or restarts it.
2
+ services:
3
+ postgres:
4
+ networks:
5
+ default: {}
6
+ local-gateway: {}
7
+ labels:
8
+ local-gateway.lifecycle: passive
9
+ local-gateway.tcp.driver: postgresql
10
+ local-gateway.tcp.hostname: postgres.${COMPOSE_PROJECT_NAME}.localhost
11
+ local-gateway.tcp.port: '5432'
12
+ sqlserver:
13
+ networks:
14
+ default: {}
15
+ local-gateway: {}
16
+ labels:
17
+ local-gateway.lifecycle: passive
18
+ local-gateway.tcp.driver: sql_server
19
+ local-gateway.tcp.hostname: sqlserver.${COMPOSE_PROJECT_NAME}.localhost
20
+ local-gateway.tcp.port: '1433'
21
+ networks:
22
+ local-gateway:
23
+ external: true
24
+ name: local-gateway
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ if [[ ! "${CHECKOUT_NAME:-}" =~ ^[a-z][a-z0-9_]{0,31}$ ]]; then
5
+ echo "Set CHECKOUT_NAME to the checkout's Compose project name" >&2
6
+ exit 1
7
+ fi
8
+
9
+ for environment in development test; do
10
+ name="app_${CHECKOUT_NAME}_$environment"
11
+ bash /adapter/provision.sh "$name" "Example-$name-Only9!"
12
+ done
@@ -0,0 +1,16 @@
1
+ SELECT format('CREATE DATABASE %I OWNER %I', :'database', :'database')
2
+ WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = :'database')
3
+ \gexec
4
+ -- Existing data stays in place; unexpected ownership is an error, not a takeover.
5
+ SELECT 1 / CASE WHEN EXISTS (
6
+ SELECT FROM pg_database JOIN pg_roles ON pg_roles.oid = datdba
7
+ WHERE datname = :'database' AND rolname = :'database'
8
+ ) THEN 1 ELSE 0 END AS expected_owner;
9
+ REVOKE CONNECT, TEMPORARY ON DATABASE :"database" FROM PUBLIC;
10
+ GRANT CONNECT, TEMPORARY ON DATABASE :"database" TO :"database";
11
+ -- Remove any stale grants to the other disposable identities.
12
+ SELECT format('REVOKE ALL ON DATABASE %I FROM %I', :'database', rolname)
13
+ FROM pg_roles
14
+ WHERE rolname LIKE 'app\_%' ESCAPE '\'
15
+ AND rolname <> :'database'
16
+ \gexec
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ psql -X -v ON_ERROR_STOP=1 \
5
+ -v "role=$1" -v "password=$2" \
6
+ -f /adapter/role.sql
7
+
8
+ psql -X -v ON_ERROR_STOP=1 \
9
+ -v "database=$1" \
10
+ -f /adapter/database.sql
@@ -0,0 +1,11 @@
1
+ -- Never ALTER PASSWORD on an existing role.
2
+ SELECT format('CREATE ROLE %I LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS', :'role', :'password')
3
+ WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = :'role')
4
+ \gexec
5
+ -- Fail rather than reuse an identity with elevated rights or inherited roles.
6
+ SELECT 1 / CASE WHEN EXISTS (
7
+ SELECT FROM pg_roles
8
+ WHERE rolname = :'role' AND rolcanlogin
9
+ AND NOT (rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication OR rolbypassrls)
10
+ AND NOT EXISTS (SELECT FROM pg_auth_members WHERE member = pg_roles.oid)
11
+ ) THEN 1 ELSE 0 END AS restricted_role;
@@ -0,0 +1,34 @@
1
+ IF DB_ID(N'$(database)') IS NULL
2
+ CREATE DATABASE [$(database)];
3
+ GO
4
+ ALTER AUTHORIZATION ON DATABASE::[$(database)] TO sa;
5
+ ALTER DATABASE [$(database)] SET TRUSTWORTHY OFF;
6
+ ALTER DATABASE [$(database)] SET DB_CHAINING OFF;
7
+ GO
8
+ USE [$(database)];
9
+ REVOKE CONNECT FROM guest;
10
+ IF USER_ID(N'$(database)') IS NULL
11
+ CREATE USER [$(database)] FOR LOGIN [$(database)];
12
+ ALTER ROLE db_owner ADD MEMBER [$(database)];
13
+ GRANT CONNECT TO [$(database)];
14
+ GO
15
+ -- Explicit denials defend against accidental PUBLIC grants; guest is disabled.
16
+ DECLARE @other sysname, @sql nvarchar(max);
17
+ DECLARE other_logins CURSOR LOCAL FAST_FORWARD FOR
18
+ SELECT name FROM master.sys.server_principals
19
+ WHERE name LIKE N'app[_]%' AND type = 'S'
20
+ AND name <> N'$(database)';
21
+ OPEN other_logins;
22
+ FETCH NEXT FROM other_logins INTO @other;
23
+ WHILE @@FETCH_STATUS = 0
24
+ BEGIN
25
+ SET @sql = N'';
26
+ IF USER_ID(@other) IS NULL
27
+ SET @sql = N'CREATE USER ' + QUOTENAME(@other) + N' FOR LOGIN ' + QUOTENAME(@other) + N'; ';
28
+ SET @sql += N'DENY CONNECT TO ' + QUOTENAME(@other) + N';';
29
+ EXEC sys.sp_executesql @sql;
30
+ FETCH NEXT FROM other_logins INTO @other;
31
+ END;
32
+ CLOSE other_logins;
33
+ DEALLOCATE other_logins;
34
+ GO
@@ -0,0 +1,18 @@
1
+ -- Variables are supplied only after the provisioning service validates CHECKOUT_NAME.
2
+ IF SUSER_ID(N'$(database)') IS NULL
3
+ CREATE LOGIN [$(database)] WITH PASSWORD = '$(password)', CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF;
4
+ GO
5
+ -- Never reset an existing password or accept server-role membership.
6
+ IF EXISTS (
7
+ SELECT 1 FROM sys.server_role_members
8
+ WHERE member_principal_id = SUSER_ID(N'$(database)')
9
+ )
10
+ THROW 51000, 'Example login has unexpected server-role membership.', 1;
11
+ IF EXISTS (
12
+ SELECT 1 FROM sys.server_permissions
13
+ WHERE grantee_principal_id = SUSER_ID(N'$(database)')
14
+ AND state IN ('G', 'W') AND permission_name <> N'CONNECT SQL'
15
+ )
16
+ THROW 51001, 'Example login has unexpected server-level grants.', 1;
17
+ DENY VIEW ANY DATABASE TO [$(database)];
18
+ GO
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ /opt/mssql-tools18/bin/sqlcmd -S sqlserver -U sa -d master -C -b \
5
+ -v "database=$1" "password=$2" \
6
+ -i /adapter/login.sql
7
+
8
+ /opt/mssql-tools18/bin/sqlcmd -S sqlserver -U sa -d master -C -b \
9
+ -v "database=$1" \
10
+ -i /adapter/database.sql
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "securerandom"
6
+
7
+ module LocalDevelopmentGateway
8
+ # Coordinates this user's clients of one Docker daemon. Operation locks live
9
+ # beyond the coordinator lock, so project commands never serialize each other.
10
+ class Lifecycle
11
+ def initialize(
12
+ runner:,
13
+ directory: File.join(
14
+ Dir.home,
15
+ ".local",
16
+ "state",
17
+ "local-development-gateway"
18
+ )
19
+ )
20
+ @runner = runner
21
+ @directory = directory
22
+ end
23
+
24
+ def synchronize
25
+ daemon_id = @runner.call("info", "--format", "{{.ID}}").strip
26
+ raise Error, "Docker daemon identity is unavailable" if daemon_id.empty?
27
+
28
+ private_directory(@directory)
29
+ directory = File.join(@directory, Digest::SHA256.hexdigest(daemon_id))
30
+ private_directory(directory)
31
+ open_file(File.join(directory, "coordinator")) do |lock|
32
+ unless lock.flock(File::LOCK_EX)
33
+ raise Error, "Lifecycle coordination lock unavailable"
34
+ end
35
+
36
+ yield directory
37
+ end
38
+ rescue SystemCallError, IOError, NotImplementedError => error
39
+ raise Error, "Lifecycle coordination unavailable: #{error.message}"
40
+ end
41
+
42
+ def register_operation(directory)
43
+ locked = false
44
+ path = File.join(directory, "operation-#{SecureRandom.hex(16)}")
45
+ file = open_file(path, exclusive: true)
46
+ locked = file.flock(File::LOCK_EX | File::LOCK_NB)
47
+ raise Error, "Lifecycle operation lock unavailable" unless locked
48
+
49
+ file
50
+ ensure
51
+ file.close if file && !locked
52
+ end
53
+
54
+ def release_operation(operation)
55
+ File.unlink(operation.path)
56
+ ensure
57
+ operation.close
58
+ end
59
+
60
+ def retained?(directory)
61
+ pending = false
62
+ Dir
63
+ .glob(File.join(directory, "operation-*"))
64
+ .each do |path|
65
+ open_file(path) do |file|
66
+ if file.flock(File::LOCK_EX | File::LOCK_NB)
67
+ File.unlink(path)
68
+ else
69
+ pending = true
70
+ end
71
+ end
72
+ end
73
+ pending || !Dir.glob(File.join(directory, "hold-*")).empty?
74
+ end
75
+
76
+ def hold(directory, name)
77
+ open_file(hold_path(directory, name)) { |_file| nil }
78
+ :held
79
+ end
80
+
81
+ def release(directory, name)
82
+ path = hold_path(directory, name)
83
+ File.unlink(path)
84
+ rescue Errno::ENOENT
85
+ nil
86
+ end
87
+
88
+ def validate_name(name)
89
+ unless name.is_a?(String) &&
90
+ /\A[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}\z/.match?(name)
91
+ raise Error,
92
+ "Hold name must start with a letter or digit and contain " \
93
+ "1–64 letters, digits, dots, underscores or hyphens"
94
+ end
95
+ end
96
+
97
+ private
98
+
99
+ def hold_path(directory, name)
100
+ validate_name(name)
101
+ File.join(directory, "hold-#{name}")
102
+ end
103
+
104
+ def private_directory(path)
105
+ FileUtils.mkdir_p(path, mode: 0o700)
106
+ stat = File.lstat(path)
107
+ unless stat.directory? && stat.uid == Process.uid &&
108
+ (stat.mode & 0o077).zero?
109
+ raise Error,
110
+ "Lifecycle directory must be private and owned by this user: #{path}"
111
+ end
112
+ end
113
+
114
+ def open_file(path, exclusive: false)
115
+ flags = File::RDWR | File::CREAT | File::NOFOLLOW
116
+ flags |= File::EXCL if exclusive
117
+ file = File.open(path, flags, 0o600)
118
+ file.close_on_exec = true
119
+ stat = file.stat
120
+ unless stat.file? && stat.uid == Process.uid && (stat.mode & 0o077).zero?
121
+ file.close
122
+ raise Error, "Unsafe lifecycle state file: #{path}"
123
+ end
124
+ return file unless block_given?
125
+
126
+ begin
127
+ yield file
128
+ ensure
129
+ file.close unless file.closed?
130
+ end
131
+ end
132
+ end
133
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module LocalDevelopmentGateway
4
- VERSION = "0.3.3"
4
+ VERSION = "0.4.0"
5
5
  end