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,84 @@
1
+ # Docker-Only Gateway Installation
2
+
3
+ Version **0.4.0** runs the gateway from one Compose file and registry images. Do not replace a running shared gateway until all participating developers/checkouts have agreed to the interruption.
4
+
5
+ The runtime requires Docker Engine with Linux containers and Docker Compose **2.20.2 or newer** (`start_interval` support). It does not require host Ruby, Bundler, a gem installation, or a gateway source checkout. Consumer `bin/dev` wrappers can still have their own Ruby requirements. The router image targets Linux amd64; Windows/macOS and other architectures have not been verified. SQL Server examples also require an engine-supported platform.
6
+
7
+ ## Download the Compose File
8
+
9
+ Download [`docker-compose.yml` from release 0.4.0](https://github.com/icefoganalytics/local-development-gateway/releases/download/v0.4.0/docker-compose.yml) into a stable, user-owned installation directory outside any disposable worktree. For example:
10
+
11
+ ```sh
12
+ mkdir -p ~/.local/share/local-development-gateway
13
+ cd ~/.local/share/local-development-gateway
14
+ curl --fail --location --output docker-compose.yml \
15
+ https://github.com/icefoganalytics/local-development-gateway/releases/download/v0.4.0/docker-compose.yml
16
+ ```
17
+
18
+ The Compose file pins the router and Traefik to immutable registry digests. Docker downloads the images during installation; no local build or source transfer is needed. Docker socket access is privileged daemon access even when the socket bind mount says `:ro`; use this only on a trusted development machine.
19
+
20
+ Keep a copy of the previous Compose file and the exact previous image references before upgrades.
21
+
22
+ ## Install from One Compose File
23
+
24
+ Run the following from the installation directory, with ports 80, 1433, and 5432 on loopback available:
25
+
26
+ ```sh
27
+ docker compose -p local-gateway -f docker-compose.yml up -d --wait
28
+ docker compose -p local-gateway -f docker-compose.yml ps
29
+ docker compose -p local-gateway -f docker-compose.yml exec -T database-router \
30
+ cat /tmp/local-development-gateway-version
31
+ docker compose -p local-gateway -f docker-compose.yml images
32
+ ```
33
+
34
+ The process record must report `0.4.0`. Inspect the containers' `.Image` IDs and `.Mounts` to confirm the selected images are running and the only host mount is the Docker socket. The HTTP router configuration is carried by Compose command arguments; the database router code is inside its image. Deleting a build checkout therefore cannot break the running service.
35
+
36
+ `up` is an explicit reconciliation operation and can recreate changed services. For routine inspection use `ps`, `images`, and `logs`; do not run `up` as a read-only health check. Existing Ruby `ensure_running` keeps its healthy-reuse behavior and does not silently upgrade active services.
37
+
38
+ ```sh
39
+ docker compose -p local-gateway -f docker-compose.yml logs --follow
40
+ ```
41
+
42
+ Each service checks health every second during its initial ten-second startup period and every thirty seconds afterward. Three consecutive failing steady-state checks mark it unhealthy. This reduces probe frequency, not a guarantee of lower total CPU or RAM under every workload.
43
+
44
+ ## Stop and Upgrade Deliberately
45
+
46
+ The native `docker compose stop` and `down` commands have **no unused-gateway guard**. Do not invoke them from consumer checkout shutdown hooks. Integrate the coordinated [Ruby lifecycle API](#optional-ruby-integration) in the existing wrapper: the first `bin/dev up` starts the gateway, another reuses it, and the last `bin/dev down` stops the routers. Automatic shutdown preserves the gateway network and containers so passive shared databases remain attached. It never stops those databases or removes their volumes.
47
+
48
+ Before a machine-wide shutdown, inspect running **and stopped** attached containers and identify their owners:
49
+
50
+ ```sh
51
+ docker ps -a --filter network=local-gateway \
52
+ --format '{{.ID}} {{.Names}} {{.Label "com.docker.compose.project"}} {{.Status}}'
53
+ docker network inspect local-gateway
54
+ ```
55
+
56
+ For ordinary shutdown, use `local-development-gateway down` from gem 0.4.0 or newer, which refuses to stop while a consumer, pending operation, or named hold remains. Unknown legacy containers remain blockers. A shared database may be explicitly labeled `local-gateway.lifecycle: passive`; pair that with active consumer labels on app/job/test services, even when they only use a project's private network. The four [consumer examples](consumer-developer-examples.md) show this boundary.
57
+
58
+ For explicit machine-wide **uninstallation**, first coordinate with all owners and detach their containers from the gateway network. Only then run `docker compose -p local-gateway -f docker-compose.yml down`. Normal project teardown is not uninstallation.
59
+
60
+ Do not delete consumer database volumes or prune Docker networks to upgrade the gateway. For a router-only update, agree on downtime, obtain/build the selected image, and explicitly recreate only that service:
61
+
62
+ ```sh
63
+ docker compose -p local-gateway -f docker-compose.yml up -d --no-deps --force-recreate --wait database-router
64
+ ```
65
+
66
+ Existing database sessions will disconnect. Verify the process version/image identity, then connect through both database protocols. To roll back, restore the previous Compose file and image selection and explicitly recreate only the affected service. The gateway does not migrate application data.
67
+
68
+ ## Optional Ruby Integration
69
+
70
+ Gem 0.4.0 provides `with_running`, `ensure_running`, `ready?`, `status`, `logs`, `stop_if_unused`, named `hold`/`release` operations, and deterministic private alias generation. It carries an image-based Compose file, not a runtime source/config mount. `status` reports the active version, requested image, immutable running image ID, and legacy mounted assets when present.
71
+
72
+ Add `gem "local-development-gateway", "~> 0.4.0"` to the consumer's existing bundle. Update every cooperating consumer's old gem and retain its existing lifecycle hooks using the coordinated contract. An old client can still recreate the legacy installation and bypass coordination. Do not commit personal checkout paths. See [lifecycle ownership](../architecture/gateway-lifecycle.md) and [the four consumer examples](consumer-developer-examples.md).
73
+
74
+ The routers remain Docker-only. Automatic project lifecycle uses the existing host Ruby wrapper, not a new native service. A machine with only Docker can run the stack explicitly with Compose, but raw Compose commands do not participate in the unused-gateway guard. Docker Engine/Desktop must already be running; Windows/macOS behavior and filesystem locking still require native verification.
75
+
76
+ For DBeaver without an app checkout, run `local-development-gateway hold dbeaver`, then release it with `local-development-gateway release dbeaver`. Holds are durable names, not reference counts: use a distinct name for independently managed sessions. Release triggers guarded cleanup. A stopped gateway does not wake on a browser or database connection.
77
+
78
+ A custom image can be selected with `LOCAL_DEVELOPMENT_GATEWAY_IMAGE`, including a registry digest reference. This does not change the gateway's Compose project, loopback ports, network name, or protocol labels. The router process record reports its actual library version even if an operator supplies an older image.
79
+
80
+ ## Release Gate
81
+
82
+ For each release, build/push the router image for the supported platforms, resolve its registry digest, and select that immutable digest in the released Compose artifact. Publish the matching Compose file and optional gem together; verify a fresh remote pull and installation in a clean Docker environment. Those publication/install checks are not established by a local image build. Do not publish the gem while its default image is unavailable.
83
+
84
+ The shared-database example is a separate opt-in consumer architecture change. Image packaging removes installation coupling; reducing repeated database server processes is the source of the expected material RAM savings.
@@ -0,0 +1,37 @@
1
+ # Effective local development gateway
2
+
3
+ ## Purpose and authority
4
+
5
+ Developers should run the commands they already know in ELCC, WRAP, Travel Authorization, and Traditional Knowledge without managing a second application lifecycle or exposing development services to the LAN. These requirements describe the intended product contract. Source code defines current behavior; release and consumer PR evidence establish what has actually been exercised. A generic example is not proof that a consumer has migrated.
6
+
7
+ ## Required outcomes
8
+
9
+ | Requirement | Acceptance scenario |
10
+ | --- | --- |
11
+ | Familiar automatic lifecycle | With Docker running and the gateway stopped, a participating project's `bin/dev up` starts the gateway, waits for readiness, then starts the project. Another checkout reuses it without interrupting existing routes. |
12
+ | Last-user shutdown | `bin/dev down` removes only that checkout's app resources. The gateway stops after the last active consumer and in-flight lifecycle operation finishes, unless an explicit desktop hold exists. Shared database containers and data remain. |
13
+ | Conservative ownership | Only explicitly marked passive infrastructure is ignored for retention. Unknown legacy consumers keep the gateway alive. Inspection or synchronization failure must not cause speculative shutdown. |
14
+ | Concurrent operations | Overlapping project startup, shutdown, and failed startup cannot cause a competing shutdown to interrupt a live protected wrapper. A dead wrapper must not leave a permanent phantom user. Coordination scope, crash recovery, and surviving-child limitations must be documented. |
15
+ | Desktop access | DBeaver connects using a server hostname, explicit checkout database, and restricted credentials. A named hold supports desktop-only use until deliberately released. |
16
+ | Local-only networking | Host listeners bind only to loopback. Container listeners remain reachable through Docker networking. HTTP, PostgreSQL, and SQL Server routes remain independent and fail closed when their target disappears. |
17
+ | Self-contained installation | One Compose stack runs HTTP and database routers from images, without host source/configuration mounts or host Ruby for the routers. Optional Ruby integration may use the consumer's existing Ruby environment. Docker itself must already be running. |
18
+ | Isolated checkout data | Shared engines belong to one project, never multiple projects. Each checkout has independent development/test databases and restricted identities. Tests, reset, shutdown, and retirement must preserve neighboring data. |
19
+ | Engine-neutral application integration | Application commands and provisioning callers do not contain native permission SQL or choose SQL clients. PostgreSQL and SQL Server adapters own those differences; application migrations remain application-owned. |
20
+ | Four concrete adoption examples | Each of ELCC, WRAP, Travel Authorization, and Traditional Knowledge has a source-backed example covering setup, normal commands, shutdown, database ownership, and remaining compatibility checks. Preserve existing editor hooks and consumer-specific behavior. |
21
+ | Useful resource savings | Measure equivalent real consumer workloads before/after sharing database servers, including total RAM and contention. Packaging changes and synthetic idle savings alone do not prove this requirement. |
22
+ | Recoverable installation and upgrades | Show requested/active version and image identity; coordinate upgrades, preserve old configuration and data, and prove rollback. Publishing, installation, and running behavior are separate gates. |
23
+ | Cross-platform intent | Linux Docker Engine and Windows/macOS Docker Desktop using Linux containers are target environments. Claim support only for exercised OS/architecture combinations; SQL Server engine limitations are independent of gateway compatibility. |
24
+
25
+ ## Safety boundaries and non-goals
26
+
27
+ Docker socket access is privileged, even through a read-only mount. This is trusted local development tooling, not a hostile-container or production security boundary. Do not start Docker Desktop, elevate privileges, migrate consumer data, upgrade database engines, stop unrelated stacks, or prune networks implicitly. Production deployment is outside this contract.
28
+
29
+ Normal lifecycle commands do not upgrade a healthy gateway. All cooperating lifecycle clients on a workstation must use the same coordination contract; old gem clients and raw Compose commands do not gain concurrency protection automatically. Support for independently coordinated users or remote workstations sharing one Docker daemon requires separate proof.
30
+
31
+ ## Knowledge and delivery owners
32
+
33
+ - [Lifecycle ownership and concurrency](../architecture/gateway-lifecycle.md) defines the runtime boundaries.
34
+ - [Consumer developer examples](../guides/consumer-developer-examples.md) explains the four adoption paths.
35
+ - [Migration guide](../guides/docker-first-migration.md) owns data transfer, restricted identities, and rollback.
36
+ - [Installation guide](../guides/docker-installation.md) owns image distribution and installed-version checks.
37
+ - [Issue #42](https://github.com/icefoganalytics/local-development-gateway/issues/42) and its linked PRs own current implementation, verification, release state, and unresolved gates. This document is not a duplicate progress ledger.
@@ -0,0 +1,145 @@
1
+ # Consumer-owned shared database example
2
+
3
+ This synthetic consumer uses a small Ruby Compose launcher, a real Node HTTP application, Knex migrations, and separate development/test connections. SQL Server 2022 is the default; PostgreSQL 17 exercises the same application. It is not a migrated ELCC, WRAP, or Travel application.
4
+
5
+ ## What a consumer maintains
6
+
7
+ `bin/dev` follows the existing consumer pattern: short `up`, `down`, `run`, `test`, `lint`, and `migrate` methods delegate to Compose; other arguments pass through unchanged. Compose owns service connections and test overrides. The wrapper does not choose SQL clients, stream SQL, provision databases, delete data, manage shared servers, or implement benchmark groups.
8
+
9
+ | Responsibility | Owner |
10
+ | --- | --- |
11
+ | Checkout name and ordinary application commands | Existing consumer `bin/dev` |
12
+ | Development/test connections and private server network | Consumer Compose configuration |
13
+ | Application tables and test reset | Existing application migrations and tests |
14
+ | Shared server startup, backup, provisioning, and retirement | Project owner, using the server Compose project |
15
+ | Browser/desktop routing | Machine-wide gateway, independently managed |
16
+
17
+ Sharing removes repeated engine containers and per-checkout server lifecycle, but adds a project-level provisioning and backup responsibility. The project owner calls `bin/provision CHECKOUT_NAME` with `DB_ENGINE=postgres` or `DB_ENGINE=sqlserver`; consumers do not select SQL clients or maintain SQL grants. The command selects an internal Compose adapter. `provisioning/checkout.sh` validates the checkout name and derives both environment identities; each engine adapter receives only a database/login name and password and owns native administration. The SQL files are private adapter details, not application migrations or files to copy into every consumer. This example-level interface is not a separately published provisioning package.
18
+
19
+ ## Prerequisites
20
+
21
+ - Docker Engine with Compose v2 (`up --wait` and `run --build` support), Ruby 2.7+ for the consumer wrapper, and internet access for images/npm.
22
+ - SQL Server requires a supported host architecture and sufficient RAM. Starting it accepts Microsoft's EULA; Developer is not a production license.
23
+ - Use disposable resources only. The checked-in passwords are public examples, not secrets. Docker administrators can obtain server administrator access; this is checkout isolation, not a hostile-administrator security boundary.
24
+
25
+ No gateway, gateway gem, host database client, or host npm installation is required.
26
+
27
+ ## Project-owner setup
28
+
29
+ From `examples/shared-databases`, create two disposable checkouts and start the project-owned server once:
30
+
31
+ ```sh
32
+ example=$PWD
33
+ servers="$example/compose.yml"
34
+ checkouts=$(mktemp -d)
35
+ cp -R "$example" "$checkouts/alpha"
36
+ cp -R "$example" "$checkouts/beta"
37
+ alpha="$checkouts/alpha/bin/dev"
38
+ beta="$checkouts/beta/bin/dev"
39
+
40
+ docker compose -p gateway-example-shared -f "$servers" up -d --wait sqlserver
41
+ bin/provision alpha
42
+ bin/provision beta
43
+ # Reconcile explicit denials after both logins exist.
44
+ bin/provision alpha
45
+ ```
46
+
47
+ Provisioning creates databases/logins, not application tables. It retains existing data/passwords, rejects elevated identities, and restores restrictions. Shared validation runs before either adapter executes SQL, including when its internal Compose service is invoked directly. Only explicitly selected setup services receive administrator credentials. A failed adapter exits nonzero; provisioning is repeatable, not transactional across both databases.
48
+
49
+ ## Normal checkout work
50
+
51
+ ```sh
52
+ COMPOSE_PROJECT_NAME=alpha "$alpha" up
53
+ COMPOSE_PROJECT_NAME=beta "$beta" up
54
+ COMPOSE_PROJECT_NAME=alpha "$alpha" run app node app.mjs note alpha-marker
55
+ COMPOSE_PROJECT_NAME=beta "$beta" run app node app.mjs note beta-marker
56
+ COMPOSE_PROJECT_NAME=alpha "$alpha" test
57
+ COMPOSE_PROJECT_NAME=beta "$beta" test
58
+ COMPOSE_PROJECT_NAME=alpha "$alpha" run app node app.mjs query 'SELECT * FROM notes'
59
+ COMPOSE_PROJECT_NAME=beta "$beta" run app node app.mjs query 'SELECT * FROM notes'
60
+ COMPOSE_PROJECT_NAME=alpha "$alpha" run test_app node app.mjs query 'SELECT * FROM notes'
61
+ COMPOSE_PROJECT_NAME=alpha "$alpha" config
62
+ COMPOSE_PROJECT_NAME=alpha "$alpha" ps
63
+ COMPOSE_PROJECT_NAME=alpha "$alpha" lint
64
+ ```
65
+
66
+ Each development database must contain only its own marker; test notes are empty after the tests. `note` POSTs through the live HTTP process. Startup and tests apply the same versioned migration using their respective restricted logins. Neither can create databases or fall back to administrator credentials. `lint` runs pinned, non-fixing Oxlint in a networkless container without starting databases; warnings fail the command.
67
+
68
+ The explicit Compose name is also the checkout identity. Without one, the wrapper uses `checkout_<12 hexadecimal SHA256 characters of the canonical checkout path>` so same-named folders at different paths remain distinct. Inspect `bin/dev config` and provision that name. Explicit names must match `[a-z][a-z0-9_]{0,31}`; moving a default-named checkout changes its identity. Retain an explicit name when persistence across moves matters.
69
+
70
+ Databases/logins are `app_<checkout>_development` and `app_<checkout>_test`; passwords are `Example-<database>-Only9!`. `consumer.yml` shows the test connection override directly. App HTTP aliases are checkout-qualified, database aliases are server-project-qualified, and no ports are published.
71
+
72
+ ## Isolation and checkout shutdown
73
+
74
+ After the successful queries above, these SQL Server commands must fail with database access denial, not syntax, login, network, or missing-server errors:
75
+
76
+ ```sh
77
+ COMPOSE_PROJECT_NAME=alpha "$alpha" run app node app.mjs query 'USE [app_beta_development]; SELECT DB_NAME();'
78
+ COMPOSE_PROJECT_NAME=beta "$beta" run app node app.mjs query 'USE [app_alpha_development]; SELECT DB_NAME();'
79
+ COMPOSE_PROJECT_NAME=alpha "$alpha" run app node app.mjs query 'USE [app_alpha_test]; SELECT DB_NAME();'
80
+ COMPOSE_PROJECT_NAME=alpha "$alpha" run test_app node app.mjs query 'USE [app_alpha_development]; SELECT DB_NAME();'
81
+
82
+ COMPOSE_PROJECT_NAME=alpha "$alpha" down
83
+ COMPOSE_PROJECT_NAME=beta "$beta" run app node app.mjs note beta-survives-alpha-down
84
+ COMPOSE_PROJECT_NAME=alpha "$alpha" run app node app.mjs query 'SELECT * FROM notes'
85
+ ```
86
+
87
+ Normal `down` stops only alpha's application and removes its private app network. Alpha's data, the shared server, and beta's live application remain available. Repeat provisioning and confirm both development markers remain.
88
+
89
+ SQL Server logins have no server roles. Database ownership remains with `sa`; each login has `db_owner` only in its own database for migrations. Guest CONNECT, TRUSTWORTHY, and cross-database ownership chaining are disabled. Other existing `app_` logins receive explicit CONNECT denials; new logins remain excluded by disabled guest access. PostgreSQL roles have no elevated attributes or inherited memberships; PUBLIC CONNECT/TEMPORARY is revoked and other `app_` grants are removed.
90
+
91
+ ## PostgreSQL counterpart
92
+
93
+ Stop both checkout apps, then export `DB_ENGINE=postgres`. Start `postgres` instead of `sqlserver` in the project-owner startup command. Run the same `bin/provision alpha`, `bin/provision beta`, and `bin/provision alpha` commands; no SQL-client or provisioning-service selection is needed. Repeat the same normal checkout commands and marker checks. Both server services use `gateway-example-shared_default`; only the selected engine needs to run.
94
+
95
+ PostgreSQL cannot `USE` another database. Verify alternate connections with otherwise-valid source credentials:
96
+
97
+ ```sh
98
+ for pair in \
99
+ app_alpha_development:app_beta_development \
100
+ app_beta_development:app_alpha_development \
101
+ app_alpha_development:app_alpha_test \
102
+ app_alpha_test:app_alpha_development
103
+ do
104
+ source=${pair%:*}
105
+ target=${pair#*:}
106
+ docker compose -p gateway-example-shared -f "$servers" exec -T \
107
+ -e "PGPASSWORD=Example-$source-Only9!" postgres \
108
+ psql -X -h gateway-example-shared-postgres -U "$source" -d "$target" \
109
+ -v ON_ERROR_STOP=1 -c 'SELECT current_database(), current_user;'
110
+ done
111
+ ```
112
+
113
+ Each must fail with `permission denied for database`. Application tests also exercise test-to-development denial through Knex.
114
+
115
+ ## Explicit data retirement and project shutdown
116
+
117
+ Deleting databases is not an application `down` operation. After stopping alpha's app and disconnecting its clients, the project owner can delete **only these disposable alpha databases**:
118
+
119
+ ```sh
120
+ # SQL Server:
121
+ docker compose -p gateway-example-shared -f "$servers" exec -T \
122
+ -e SQLCMDPASSWORD=Example-Sql-Admin9! sqlserver \
123
+ /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -d master -C -b \
124
+ -Q 'DROP DATABASE [app_alpha_development]; DROP DATABASE [app_alpha_test];'
125
+
126
+ # PostgreSQL alternative:
127
+ docker compose -p gateway-example-shared -f "$servers" exec -T \
128
+ -e PGPASSWORD=Example-Postgres-Admin9! postgres \
129
+ psql -X -h localhost -U example_admin -d postgres -v ON_ERROR_STOP=1 \
130
+ -c 'DROP DATABASE app_alpha_development;' -c 'DROP DATABASE app_alpha_test;'
131
+ ```
132
+
133
+ Connected clients can cause deletion to fail; do not force other sessions closed. Confirm beta's markers survive, then reprovision alpha and run its normal `up` and `test` commands to prove fresh app-owned migrations.
134
+
135
+ After stopping **all** checkout apps, `docker compose -p gateway-example-shared -f "$servers" down` stops project servers while preserving volumes. Adding `--volumes` destroys **every checkout's data on both engines** and is appropriate only when retiring this disposable project. Never invoke it from checkout teardown or prune unrelated networks.
136
+
137
+ ## Optional routing and measurement
138
+
139
+ If the gateway and external `local-gateway` network already exist, the project owner may add `-f gateway.yml` to server startup. Desktop hostnames are `sqlserver.gateway-example-shared.localhost` and `postgres.gateway-example-shared.localhost`. Routing selects a server, not a logical database. This overlay labels the servers as passive: they do not keep the candidate gateway running after its final consumer stops. Acquire a named hold with `local-development-gateway hold dbeaver` for desktop-only use and release it afterward with `local-development-gateway release dbeaver`.
140
+
141
+ This database-focused example remains usable without a gateway. For automatic project `up`/last-`down` gateway lifecycle, apply the small existing-wrapper integrations in the [four consumer developer examples](../../docs/guides/consumer-developer-examples.md), including their active app/job/test labels. Do not label active apps passive.
142
+
143
+ For a separate-server comparison, use ordinary Compose `-p` to create an independent server project per checkout and set `DB_SERVER_PROJECT` on the corresponding application's commands. No benchmark mode exists in `bin/dev`. Compare identical images, databases, data, workload, and sampling intervals, running only one topology during measurement. The historical 48.2% synthetic idle RAM saving is not evidence of application adoption, capacity, or lower maintenance burden. Server restarts and contention now affect all project checkouts; sharing does not fix network exhaustion (#41).
144
+
145
+ For a real consumer, retain its existing wrapper, application, migration runner, and tests. Change its Compose connections and network, remove checkout-owned engine lifecycle and application administrator fallback, and establish project-owned provisioning/backup. Preserve its editor bridge and other unrelated hooks. Do not copy this synthetic application or replace an existing wrapper with this example.
@@ -0,0 +1,10 @@
1
+ {
2
+ "lint": {
3
+ "commands": {
4
+ "javascript": {
5
+ "tool": "oxlint",
6
+ "command": ["ruby", "../bin/dev", "lint"]
7
+ }
8
+ }
9
+ }
10
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "ignorePatterns": ["node_modules/**"]
3
+ }
@@ -0,0 +1,12 @@
1
+ FROM node:22-bookworm-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY package.json package-lock.json ./
6
+ RUN npm ci --ignore-scripts && npm cache clean --force
7
+
8
+ COPY *.mjs .oxlintrc.json ./
9
+ COPY migrations ./migrations
10
+
11
+ USER node
12
+ CMD ["node", "app.mjs"]
@@ -0,0 +1,91 @@
1
+ import { createServer } from "node:http"
2
+ import { once } from "node:events"
3
+
4
+ import { connect, migrate } from "./database.mjs"
5
+
6
+ const command = process.argv[2] ?? "serve"
7
+
8
+ if (command === "note") {
9
+ const response = await fetch(`http://${process.env.APP_HOST}:3000/notes`, {
10
+ method: "POST",
11
+ body: process.argv[3],
12
+ })
13
+
14
+ if (!response.ok) {
15
+ const message = await response.text()
16
+ throw new Error(message)
17
+ }
18
+
19
+ console.log(await response.text())
20
+ } else {
21
+ const database = connect()
22
+ let isServing = false
23
+
24
+ try {
25
+ if (command === "query") {
26
+ const result = await database.raw(process.argv[3])
27
+ console.log(JSON.stringify(result))
28
+ } else if (command === "migrate") {
29
+ await migrate(database)
30
+ } else if (command === "serve") {
31
+ await migrate(database)
32
+
33
+ const server = createServer(async (request, response) => {
34
+ try {
35
+ if (request.url !== "/notes") {
36
+ response.writeHead(404).end()
37
+ return
38
+ }
39
+
40
+ if (request.method === "POST") {
41
+ let body = ""
42
+
43
+ for await (const chunk of request) {
44
+ body += chunk
45
+
46
+ if (body.length > 200) {
47
+ break
48
+ }
49
+ }
50
+
51
+ if (!body.trim() || body.length > 200) {
52
+ response.writeHead(400).end("Note must contain 1–200 characters")
53
+ return
54
+ }
55
+
56
+ await database("notes").insert({ body })
57
+ } else if (request.method !== "GET") {
58
+ response.writeHead(405).end()
59
+ return
60
+ }
61
+
62
+ const notes = await database("notes").select("id", "body").orderBy("id")
63
+
64
+ response.setHeader("Content-Type", "application/json")
65
+ response.end(JSON.stringify(notes))
66
+ } catch (error) {
67
+ console.error(error)
68
+ response.writeHead(500).end("Database operation failed")
69
+ }
70
+ })
71
+
72
+ server.listen(3000, "0.0.0.0")
73
+ await once(server, "listening")
74
+ isServing = true
75
+
76
+ for (const signal of ["SIGINT", "SIGTERM"]) {
77
+ process.once(signal, () => {
78
+ server.close(async () => {
79
+ await database.destroy()
80
+ })
81
+ })
82
+ }
83
+ } else {
84
+ throw new Error(`Unknown application command: ${command}`)
85
+ }
86
+ } finally {
87
+ if (!isServing) {
88
+ await database.destroy()
89
+ }
90
+ }
91
+ }
@@ -0,0 +1,67 @@
1
+ import assert from "node:assert/strict"
2
+ import { after, before, beforeEach, test } from "node:test"
3
+
4
+ import { connect, migrate } from "./database.mjs"
5
+
6
+ // Never let a test cleanup command use development or administrator credentials.
7
+ assert.match(process.env.DB_NAME, /^app_[a-z][a-z0-9_]{0,31}_test$/)
8
+ assert.equal(process.env.DB_USER, process.env.DB_NAME)
9
+ const database = connect()
10
+
11
+ before(async () => {
12
+ await migrate(database)
13
+ })
14
+
15
+ beforeEach(async () => {
16
+ await database("notes").del()
17
+ })
18
+
19
+ after(async () => {
20
+ try {
21
+ await database("notes").del()
22
+ } finally {
23
+ await database.destroy()
24
+ }
25
+ })
26
+
27
+ test("when using checkout test credentials, persists and reads a note", async () => {
28
+ // Arrange
29
+ await database("notes").insert({ body: "consumer test" })
30
+
31
+ // Act
32
+ const notes = await database("notes").select("body")
33
+
34
+ // Assert
35
+ assert.deepEqual(notes, [
36
+ {
37
+ body: "consumer test",
38
+ },
39
+ ])
40
+ })
41
+
42
+ test("when test credentials access development, denies the connection", async () => {
43
+ // Arrange
44
+ const developmentName = process.env.DB_NAME.replace(/_test$/, "_development")
45
+ const isPostgres = process.env.DB_ENGINE === "postgres"
46
+ let development
47
+ if (isPostgres) {
48
+ development = connect(developmentName)
49
+ } else {
50
+ development = connect()
51
+ }
52
+
53
+ try {
54
+ const query = isPostgres ? "SELECT 1" : `USE [${developmentName}]; SELECT DB_NAME();`
55
+
56
+ // Act
57
+ const result = development.raw(query)
58
+
59
+ // Assert
60
+ await assert.rejects(result, (error) => {
61
+ assert.match(error.message, /permission denied for database|Cannot open database|not able to access the database/i)
62
+ return true
63
+ })
64
+ } finally {
65
+ await development.destroy()
66
+ }
67
+ })
@@ -0,0 +1,31 @@
1
+ import { fileURLToPath } from "node:url"
2
+
3
+ import knex from "knex"
4
+
5
+ export function connect(database = process.env.DB_NAME) {
6
+ const isPostgres = process.env.DB_ENGINE === "postgres"
7
+ const connection = {
8
+ host: process.env.DB_HOST,
9
+ user: process.env.DB_USER,
10
+ password: process.env.DB_PASSWORD,
11
+ database,
12
+ }
13
+
14
+ if (!isPostgres) {
15
+ connection.options = { encrypt: true, trustServerCertificate: true }
16
+ }
17
+
18
+ return knex({
19
+ client: isPostgres ? "pg" : "mssql",
20
+ connection,
21
+ pool: { min: 0, max: 2 },
22
+ acquireConnectionTimeout: 10000,
23
+ })
24
+ }
25
+
26
+ // The consumer owns schema changes, not server/database/login provisioning.
27
+ // Knex records completed migrations and serializes concurrent app/test startup.
28
+ export async function migrate(database) {
29
+ const directory = fileURLToPath(new URL("./migrations", import.meta.url))
30
+ await database.migrate.latest({ directory })
31
+ }
@@ -0,0 +1,10 @@
1
+ exports.up = async (database) => {
2
+ await database.schema.createTable("notes", (table) => {
3
+ table.increments("id").primary()
4
+ table.string("body", 200).notNullable()
5
+ })
6
+ }
7
+
8
+ exports.down = async (database) => {
9
+ await database.schema.dropTable("notes")
10
+ }