From d711c95343e47cdc756932272c9009a8ce120860 Mon Sep 17 00:00:00 2001 From: Patty Chow <91703531+patty-chow@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:23:37 -0700 Subject: [PATCH 1/2] Make attendee workshop subscription-free with two self-hosted sites --- .azure/deployment-plan.md | 185 ++++++++----------- .env.example | 14 +- .github/workflows/verify.yml | 33 ++++ README.md | 293 +++++++++++++++-------------- compose.presenter.yaml | 9 + compose.yaml | 24 ++- docs/instructor.md | 226 +++++++++++------------ docs/lab.md | 236 +++++++++++++----------- docs/legacy-azure-provisioning.md | 234 +++++++++++++++++++++++ docs/local.md | 63 ++++--- docs/organizer.md | 297 +++++++----------------------- docs/presenter.md | 165 +++++++++++++++++ package.json | 3 +- scripts/database.mjs | 20 +- scripts/setup.mjs | 93 +++++++--- scripts/workspace-start.mjs | 13 +- src/catalog.js | 33 +++- src/config.js | 117 ++++++------ src/connections.js | 2 +- src/public/index.html | 20 +- src/server.js | 9 +- test/database.integration.js | 43 ++++- test/domain.test.js | 8 +- test/http.test.js | 45 +++++ test/two-site.test.js | 145 +++++++++++++++ test/workspace.test.js | 5 +- 26 files changed, 1470 insertions(+), 865 deletions(-) create mode 100644 .github/workflows/verify.yml create mode 100644 compose.presenter.yaml create mode 100644 docs/legacy-azure-provisioning.md create mode 100644 docs/presenter.md create mode 100644 test/two-site.test.js diff --git a/.azure/deployment-plan.md b/.azure/deployment-plan.md index dc3ecaf..b7c6cfe 100644 --- a/.azure/deployment-plan.md +++ b/.azure/deployment-plan.md @@ -1,110 +1,75 @@ -# Azure deployment plan - -**Status: Ready for Validation - Codespaces-first; live organizer checks pending.** - -## Direction - -Attendees use a browser and a GitHub account. Node.js, Docker, and the development -DocumentDB run inside their Codespace. A physical-laptop database and offline -operation are no longer workshop requirements. Local Docker remains optional. - -The teaching comparison is a self-hosted development database versus managed -Azure DocumentDB. Both may physically run in the cloud; do not describe the -Codespaces path as offline or as running on the attendee's laptop. - -## Role separation - -| Environment | Tools and purpose | Azure access | -| --- | --- | --- | -| Attendee (default) | Node.js, Docker, DocumentDB, TODOs/reference app | Organizer-issued database credentials only | -| Organizer (alternate) | Attendee tools plus Azure CLI and Bicep | Explicit Entra sign-in and approved deployment scope | - -The organizer configuration installs tools but does not sign in or provision -anything on startup. A configuration name is not an authorization boundary: -Azure RBAC, identity, and network controls still enforce access. Never share the -organizer's Azure login cache or authenticated Codespace with attendees. - -## Preparation work - -- Make the browser-first entry point and attendee prerequisites the default. -- Share a bounded development-database startup command between both configurations. -- Preinstall Azure CLI and Bicep in the organizer configuration. -- Provide a Linux/Codespaces helper that prepares private, owner-only deployment - inputs outside Git, without performing Azure operations. -- Document explicit validation, deployment, observation, and ownership-checked - cleanup commands in the organizer runbook. -- Preserve the same data layer, explicit copying, existing favorites, and the - optional laptop-local path. - -## Infrastructure recipe - -Use standalone Bicep through Azure CLI from the organizer Codespace. No `azd` -project, CI workflow, standing worker, or new IAM role assignment is introduced. - -The current templates model a two-attendee rehearsal: a fresh group and two -isolated M30 clusters in East US, one shard and 128 GiB per cluster, native -authentication, no HA or replicas, and public access initially disabled. This -is a rehearsal inventory, not a classroom-wide sizing recommendation. - -Only observed single IPv4 client addresses are allowed. Do not create an -all-address firewall range or the special Azure-service bypass rule. Re-observe -Codespaces egress after a restart. - -## Credentials and execution boundary - -The parameter-preparation helper generates credentials in private storage in the -organizer environment. It does not deploy, grant approval, or verify cloud state. -The parameter file is sensitive even though Bicep marks its password object -secure. Keep it out of Git, terminal output, screenshots, and attendee workspaces. - -Before any live run, confirm the actual subscription, region, permissions, -resource inventory, execution limits, provider-specific usage policy, expiry, -and cleanup authority outside this public repository. Keep ownership records -before writes and verify real provider results afterward. - -The organizer runbook is supervised, not an unattended scheduler. Stopping a -Codespace does not stop or delete Azure resources. An expiry tag is not an -automatic cleanup mechanism. - -## Existing rehearsal evidence - -- A real two-core Codespace ran the published app and its development database. - Completed exercises, 216 schedule entries, favorites, duplicate prevention, - overlaps, and calendar export were exercised. -- The corrected exercise-aware tests passed locally and in Codespaces. -- Azure template validation and what-if passed, but the first real request - rejected the documented `networkBypassMode` property. The templates now omit it. -- The corrected two-cluster deployment reached `Succeeded` and both clusters - reached `Ready` with public access disabled. Managed CRUD, copy-back, and - cross-attendee authentication were not completed within that rehearsal. -- The temporary Codespace, clusters, and empty group were deleted and temporary - credentials removed. - -## Remaining validation - -- [ ] Fresh startup of both revised dev-container configurations. -- [ ] Organizer Azure sign-in under the target tenant's MFA/conditional-access policy. -- [ ] Approved scope, quotas, policy checks, validation, and what-if for a new run. -- [ ] Managed database connection, seed, copy-out, copy-back, and credential isolation. -- [ ] Narrow-IP refresh after stop/resume and verified resource cleanup. -- [ ] Calendar-app import and the full 105-minute attendee rehearsal. - -Static checks or a previously healthy Codespace do not establish these outcomes. - -## Local validation proof - -- Twenty-five focused checks passed in a non-root Linux container, including - owner-only organizer-file permissions, refusal to overwrite a prior run, and - refusal to write organizer state inside the repository. -- Windows checks passed with the POSIX-only permission test explicitly skipped. -- The rehearsal Bicep compiled successfully. -- The Azure CLI feature's `installBicep` option and pinned feature release were - checked against the official published manifest. The pinned Bicep release - includes public Linux x64 and arm64 assets. -- Shared startup is bounded and seeds only the development target. Neither - configuration signs in to Azure or provisions cloud resources on startup. -- No managed identities or new Azure IAM role assignments are introduced. - -The new organizer profile has not yet completed a fresh Codespaces build or a -managed-data-plane rehearsal. This is preparation evidence, not a `Validated` -Azure deployment or permission to start a new live run. +# Workshop delivery plan + +**Direction: subscription-free attendee lab; existing-resource presenter capstone.** +No new Azure deployment is required for the selected workshop. The organizer has +an existing Azure DocumentDB instance available for a presenter-only demonstration. +Availability is not a claim that the application round trip has been rehearsed. + +## Mandatory attendee path + +- Browser + GitHub account + available Codespaces usage/connectivity. +- Two independent OSS DocumentDB containers, credentials and named volumes: + Site A / Site B. The old `documentdb-data` volume remains Site A. +- Same two MongoDB-driver TODOs/reference, explicit connection switching, + selected-favorite copying, repeatable retry, return trip, calendar export. +- Site simulation, not actual on-prem/cloud topology, replication or failover. +- No Azure credentials, Azure management login, new subscriptions or Kubernetes. +- Base Compose excludes cloud settings even from a legacy `.env`; bounded startup + waits for and seeds both local sites, stopping on failure. +- Setup preserves existing notebook configuration and appends only absent Site B + fields. Partial credentials or incompatible catalog remnants fail for review. + +## Presenter-only cloud path + +Use [docs/presenter.md](../docs/presenter.md), a physical laptop running the app +and local DocumentDB, and one existing approved managed Azure DocumentDB endpoint. +A dedicated authorized demo database prevents mixing workshop and shared app data. +`compose.presenter.yaml` explicitly selects local/cloud targets instead of Site A/B. +It neither provisions nor automatically seeds Azure. Attendees receive no credentials. + +The proof is selected same-driver operations and explicit application-level +copy-out/back, not streaming replication or full MongoDB/operational parity. +Codespaces-to-Azure must be described as self-hosted-to-managed, not on-prem. +Have a rehearsed recording; cloud/network problems must not block attendee completion. + +Keep validated cloud TLS, private credential handling and approved narrow network +access. Do not disable certificates, open all-address firewall ranges, or share +an authenticated organizer environment. Existing resources can still incur costs; +cleanup follows their owner's policy, not generic cluster/group deletion. + +## Retained optional infrastructure + +The Organizer dev-container, Azure CLI/Bicep tooling, private parameter helper, +and two-M30-cluster rehearsal templates remain for **separately authorized future +provisioning only**. See [the legacy runbook](../docs/legacy-azure-provisioning.md). +They are not an attendee dependency, classroom-capacity plan, or authorization +to deploy. Native-user cluster-wide permissions are why a shared managed cluster +with database-per-attendee credentials was not chosen for this workshop. + +Earlier evidence: a real single-development-database Codespace app/API rehearsal +passed; the previous corrected Azure two-cluster control-plane deployment reached +Ready with public access disabled and was cleaned up. Managed CRUD/copy-back/ +cross-attendee authentication did **not** finish in that run. Do not carry that +control-plane result forward as a managed data-plane or revised two-site proof. + +## Verification gates + +Automated gates in this revision: + +- Offline Linux tests, including owner-only organizer files and setup preservation. +- Two actual independent local database services, temporary per-run test databases, + copy-out/back/retry, partial outcomes, timestamp retention, index/migration, HTTP. +- Complete-reference recovery and expected 216-entry catalog. +- No cloud endpoint used by attendee startup or database integration tests. + +Still requiring environment-specific acceptance (not replaced by local/CI checks): + +- [ ] Fresh revised attendee/organizer Codespaces builds and cold startup timing. +- [ ] Measured two-site resource needs on representative accounts/machines. +- [ ] Presenter actual laptop → approved managed Azure seed, copy-out, retry, copy-back. +- [ ] Approved real-network access and private credential delivery to the presenter. +- [ ] Verified backup recording and calendar-application import. +- [ ] Full 105-minute timed rehearsal, pairing fallback, export and safe stopping. + +No unattended cleanup worker, cloud IAM grants, Kubernetes dependency, background +sync, Azure app hosting or new cloud resources are introduced by this plan. diff --git a/.env.example b/.env.example index 94e1a8a..907d098 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +1,19 @@ -# Run the setup command to generate a private .env with local-only credentials. -DOCUMENTDB_USERNAME= -DOCUMENTDB_PASSWORD= +# Run setup; it generates private, independent local credentials. +DOCUMENTDB_USERNAME= +DOCUMENTDB_PASSWORD= +SITE_B_USERNAME= +SITE_B_PASSWORD= WORKSHOP_MODE=starter WORKSHOP_LOCATION=laptop WORKSHOP_PUBLIC_HOST= WORKSHOP_PORT=3000 +# The attendee Compose file always starts at local (Site A). +# ACTIVE_TARGET is used only by the explicit presenter override. ACTIVE_TARGET=local LOCAL_DATABASE_NAME=ato_workshop -# Leave these empty until an organizer supplies an approved sandbox. +SITE_B_DATABASE_NAME=ato_workshop +# Presenter only. Default attendee Compose does NOT pass these into the app. +# Use an existing, approved Azure instance; no new subscription is required by attendees. CLOUD_DOCUMENTDB_URI= CLOUD_DATABASE_NAME= # Optional anonymous registry approved by your organization; never embed tokens. diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml new file mode 100644 index 0000000..52d03ee --- /dev/null +++ b/.github/workflows/verify.yml @@ -0,0 +1,33 @@ +name: Verify workshop +on: + pull_request: + push: + branches: [main] +permissions: + contents: read +jobs: + two-site-workshop: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + COMPOSE_PROJECT_NAME: ato-ci + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '24' + cache: npm + - run: npm ci --ignore-scripts --no-audit --no-fund + - run: npm test + - name: Start and seed only the two self-hosted sites + run: npm run workspace:start + - name: Exercise two independent database servers + run: docker compose -f compose.yaml exec -T app npm run test:database + - name: Verify complete-reference recovery + run: | + docker compose -f compose.yaml -f compose.complete.yaml up -d --wait --wait-timeout 240 app + curl --fail --silent http://localhost:3000/api/state > /tmp/planner-state.json + node --input-type=module -e 'import fs from "node:fs"; const s=JSON.parse(fs.readFileSync("/tmp/planner-state.json")); if(s.target!=="local" || s.sessions.length!==216) process.exit(1)' + - name: Stop this ephemeral CI project only + if: always() + run: docker compose -f compose.yaml down --volumes diff --git a/README.md b/README.md index 31abd2f..215b175 100644 --- a/README.md +++ b/README.md @@ -4,206 +4,221 @@ A 105-minute DocumentDB workshop for All Things Open 2026. Build a personal conference planner: browse sessions, save favorites, flag overlaps, and download a calendar. Then discover why changing a database connection does not move data. -**Codespaces-first:** attendees need a browser, a GitHub account, and available -Codespaces usage. No Docker, Node.js, Git, or Azure CLI installation is required -on their laptops. Docker and the development database run inside Codespaces. - -The app includes a snapshot of the -[official ATO schedule](https://2026.allthingsopen.org/schedule), captured on -October 12, 2026. It contains 216 distinct scheduled entries across October 18-20. -A live Codespaces app/API rehearsal passed. The revised organizer configuration -and the full managed-Azure round trip still need a fresh end-to-end rehearsal. -Opening either configuration does not provision Azure resources. - -The web schedule is the primary data source; the supplied October 9 Monday and -Tuesday PDFs were cross-checked, not silently merged. See the -[source notes](docs/instructor.md#schedule-data) for duplicates, unresolved -disagreements, unavailable details, and the excluded invalid break time. +**No attendee Azure subscription, cloud database credentials, or Kubernetes setup.** +Attendees use two independent self-hosted DocumentDB instances: **Site A / Site B**. +They share application code, not storage, credentials, or favorites. In Codespaces, +both instances run inside the same development environment: this is a **two-site +simulation**, not an on-prem deployment, live hybrid cloud, replication, or failover. +The presenter separately demonstrates the same application against a real local +laptop database and an existing, authorized Azure DocumentDB instance. + +**Codespaces-first:** bring a browser, a GitHub account, and available Codespaces +usage. No Docker, Node.js, Git, Azure CLI, or Kubernetes installation is required +on attendees' laptops. Codespaces still requires internet access and available +usage; it is not a promise of free or offline hosting. + +The app includes the [official ATO schedule](https://2026.allthingsopen.org/schedule) +snapshot captured October 12, 2026: **216 distinct scheduled entries, October 18–20**. +The earlier single-development-database app/API was rehearsed in Codespaces. +The revised two-site cold Codespaces startup, timed classroom delivery, calendar-app +import, and presenter Azure round trip still require their own acceptance rehearsal. +Automated local/CI checks are not proof of those environments. + +The web schedule is primary; October 9 Monday/Tuesday PDFs were cross-checked, +not silently merged. See [source notes](docs/instructor.md#schedule-data) for +cross-listings, unresolved disagreements, and the excluded invalid break time. ## Start in Codespaces 1. [Open the workshop in Codespaces](https://codespaces.new/documentdb/ato-2026-workshop). - Choose **ATO 2026 - Attendee** if prompted for a dev-container configuration. -2. Wait for setup to finish. It installs dependencies, generates private - development credentials, starts DocumentDB and the app, and seeds the catalog. - The terminal reports when the development database and catalog are ready. -3. Open port **3000** from the **Ports** tab. Keep its visibility **Private**. -4. Follow the [attendee guide](docs/lab.md). The starter's `TODO_LIST_SESSIONS` - prompt is intentional until you complete the first exercise. + Choose **ATO 2026 - Attendee** if prompted. +2. Wait for setup to finish. It installs dependencies, generates independent + private development credentials, starts both databases and the app, waits for + each database, and seeds the same catalog in both. It does not copy favorites. +3. When the terminal says **Site A and Site B are ready and both catalogs are + seeded**, open port **3000** in the **Ports** tab. Keep visibility **Private**. +4. Follow the [attendee guide](docs/lab.md). `TODO_LIST_SESSIONS` is intentional + until you finish the first exercise; it is not a database connection failure. Every workshop terminal command runs **inside Codespaces**, unless explicitly -following the optional laptop-local appendix. The browser editor is your editor. +following the optional [laptop-local appendix](docs/local.md). -The Codespace needs connectivity and available GitHub usage; a GitHub account -alone does not guarantee access or free usage. If account policy or quota blocks -startup, ask a helper for a pairing or follow-along path. Do not publish ports or -share login sessions to get around access controls. +If account policy or quota blocks startup, ask a helper for the agreed pairing or +follow-along path. Do not share logins or publish ports to bypass access controls. +Two databases need more memory/storage than the earlier single-site version; +preflight cold creation on the chosen Codespaces machine before class. Helpers +should triage at minute 12, not spend the workshop installing Docker on laptops. -The source calls its development target `local`: that means local to the -development environment, not physically on your laptop. The second target, -`cloud`, is managed Azure DocumentDB. This is not an offline workshop. - -Setup never overwrites an existing `.env`. If startup fails, inspect the terminal -error, resolve it, and retry: +Retry a failed setup after reading and resolving the error: ```sh npm run workspace:start ``` -This starts and seeds only the development database; it does not sign in to Azure -or provision cloud resources. +This command selects the attendee Compose file explicitly, starts at Site A, +waits for **both** local services, and seeds only `local` and `site-b`. +A failed step stops startup; readiness is not reported after a failed second site. +The default Compose file does not pass Azure connection values to the app, even +if they remain in an older `.env`. No Azure login, provisioning, or seed occurs. + +### Existing notebook or older practice version? + +Keep the same checkout directory and Compose project name to retain the existing +`documentdb-data` volume: it is still **Site A**. Site B gets a new, separate +`documentdb-site-b-data` volume. Changing directories/project names selects other +volumes; it does not move your notebook. + +Setup preserves every existing `.env` value and appends only missing Site B +settings. It never rotates Site A credentials. Partial/empty Site B credentials +require manual review rather than generating a password for a possibly existing +volume. Do not delete `.env` or volumes as a repair step. -### Already ran the practice version? +Seeding the real snapshot into a practice database returns `CATALOG_MISMATCH`. +Choose a fresh name in your private `.env`, for example +`LOCAL_DATABASE_NAME=ato_workshop_2026` (and `SITE_B_DATABASE_NAME` if Site B also +contains an older catalog). Recreate the app, then seed both targets: -Seeding this snapshot into a practice database intentionally returns -`CATALOG_MISMATCH`. Do not delete the volume or overwrite its catalog to get past it. -To keep that practice notebook intact, choose a fresh local database name in your -private `.env`, for example `LOCAL_DATABASE_NAME=ato_workshop_2026`, recreate the -app with your usual Compose command, and seed `local` again. The old database -and its favorites remain in the volume. Reverting the name selects the old data. +```sh +docker compose -f compose.yaml up -d --wait --wait-timeout 240 app +docker compose -f compose.yaml exec app npm run seed -- --target local +docker compose -f compose.yaml exec app npm run seed -- --target site-b +``` -Practice favorites are fictional sessions and cannot be mapped automatically -onto real conference sessions. No existing database or favorite is migrated by -updating this repository. +The old database/favorites remain in their volume; reverting the name selects +them again. Use the complete-reference override too if that is your active mode. +Fictional practice favorites cannot automatically map to real conference sessions. +An interrupted seed of the same catalog can be retried; incompatible partial +catalogs are rejected rather than silently hidden or overwritten. ## Complete reference and recovery -The two implementations use the same application, fixture, configuration, and -database volume: +The starter and reference use the same app, catalog, configuration, and volumes: -| Version | File | Purpose | -| --- | --- | --- | -| TODO starter | [exercises/starter/repository.js](exercises/starter/repository.js) | Two focused database exercises | -| Complete reference | [examples/complete/repository.js](examples/complete/repository.js) | Working implementation and recovery path | +- [TODO starter](exercises/starter/repository.js): two focused driver exercises. +- [Complete reference](examples/complete/repository.js): working recovery path. -In the Codespaces terminal, run the complete reference without editing or -replacing your exercise: +Run the reference **without replacing your exercise or resetting favorites**: ```sh docker compose -f compose.yaml -f compose.complete.yaml up -d --wait --wait-timeout 240 app ``` -To return to the starter: +Return to the starter (unless you deliberately set `WORKSHOP_MODE` in `.env`): ```sh -docker compose up -d --wait --wait-timeout 240 app +docker compose -f compose.yaml up -d --wait --wait-timeout 240 app ``` -Refresh the browser after a restart. The API's request token changes when the -server restarts. Changes to the repository exercise file restart the Node server -automatically. If Docker file notifications are unavailable, use: +Refresh the browser after every app restart: its request token changes. Node +watches the exercise file. If Docker file notifications are unavailable: ```sh -docker compose restart app +docker compose -f compose.yaml restart app ``` -## Attendee and organizer environments - -| Configuration | Purpose | Azure identity | -| --- | --- | --- | -| **ATO 2026 - Attendee** (default) | Complete the TODOs, compare databases, copy favorites, export a calendar | No Azure-management login; use assigned database credentials | -| **ATO 2026 - Organizer** | The same development environment, plus preinstalled Azure CLI and Bicep | Explicit sign-in by an authorized organizer | - -See [deploying from an organizer Codespace](docs/organizer.md). Do not share an -authenticated organizer Codespace, Azure login cache, or administrator credentials -with attendees. Selecting a configuration installs tools; it grants no Azure -permissions. +The attendee app always restarts at **Site A**. Switching the live connection is +explicit and never falls back silently after a failure. `WORKSHOP_MODE` selects +starter/reference; the separate `WORKSHOP_SCENARIO` selects attendee/presenter. +The base Compose file fixes the scenario to `attendee`. -Optional GitHub CLI diagnostics use the SSH feature. Browser-only attendees do -not need a local GitHub CLI or SSH setup. +## What the two sites teach -## Optional laptop-local path +```text +Browser -> Node app -> Site A (OSS DocumentDB, own credentials + volume) + -> Site B (OSS DocumentDB, own credentials + volume) + One active target at a time; explicit copying only -Already have Docker and prefer your own machine? The -[laptop-local appendix](docs/local.md) uses the same application and Compose -files. It is not an attendee prerequisite and is not part of the timed setup. - -## How the data works - -- `sessions` holds a seeded catalog with stable identifiers and UTC times. -- `favorites` holds a selected session ID and its initial save timestamp. -- `workshop_meta` identifies the catalog version and whether it is practice data. -- The browser talks to the Node API, never directly to a database. -- Connection changes do not seed, copy, replace, or delete favorites. -- Explicit copying only inserts missing selected favorites. Repeating it does - not duplicate favorites or overwrite their original save timestamps. -- Copy results distinguish copied, already present, invalid, failed, and - unattempted records. Retrying is safe after resolving a partial failure. -- Copying does not synchronize removals or resolve arbitrary document conflicts. - -Both database targets need the same catalog before a copy. The seed command is -explicit, preserves favorites and migrated documents, and refuses a known -different catalog. Loading a new conference schedule is a reviewed data change, -not an automatic startup refresh. - -Calendar export is a snapshot, not a calendar subscription. It retains the -published block times; individual keynotes or lightning talks within a shared -block do not have invented per-talk timings. Overlap warnings are checks, not -proof that two talks in the same program compete. Favorites do not reserve seats -or confer access to events requiring separate registration. +Presenter capstone, separately: +Laptop app + local DocumentDB <-> existing managed Azure DocumentDB + Explicit favorite copying, not replication +``` -The original practice catalog is retained only as a deterministic test fixture. -Actual schedule changes still require a reviewed update: +The standard MongoDB Node.js driver talks to DocumentDB's MongoDB-compatible API. +The repository methods do not branch by deployment. The self-hosted DocumentDB +engine is built on PostgreSQL; Azure supplies a managed operational environment. +The exercise proves the specific driver operations tested here, not universal +MongoDB feature parity or identical operational behavior. + +- `sessions`: seeded catalog with stable identifiers and UTC times. +- `favorites`: selected session ID and its initial save timestamp. +- `workshop_meta`: catalog ownership/readiness and practice/official metadata. +- Switching connections does not seed, copy, replace, or delete favorites. +- Explicit copying inserts only missing selected favorites; retries do not create + duplicates or overwrite their initial timestamps. +- Per-record results distinguish copied, already present, invalid, failed, and + unattempted. Partial success is not a transaction rollback. +- Removals do not synchronize; this is not replication, general conflict + resolution, or automatic failover. + +Both sites need the same catalog. Seeding preserves favorites and migrations and +rejects a different catalog. A schedule update is a reviewed data change, not a +startup scrape. Reproduce the checked-in catalog/audit offline with: ```sh npm run import:schedule ``` -This offline command reproduces the catalog and -[audit report](data/schedule-import-report.json) from the captured -[public metadata](data/schedule-source.json). It neither scrapes the network nor -changes a database. Capture and review a new source snapshot deliberately before -using it for an update. +The [captured source](data/schedule-source.json) and +[audit report](data/schedule-import-report.json) preserve provenance. A replacement +snapshot requires reviewed migration or fresh databases. -## Managed Azure DocumentDB, later +Calendar export is a snapshot, not a subscription. Published blocks may contain +sequential keynotes/lightning talks; no per-talk timing is invented. Overlap +warnings need interpretation. Favorites neither reserve seats nor grant entry to +separately registered events. -An organizer must provide an approved, isolated sandbox and its database -credentials. Leave the cloud fields in `.env` blank until then. Never commit the -file, paste connection strings into screenshots, or put credentials in the UI. +## Presenter-only real Azure capstone -See [organizer guidance](docs/instructor.md#azure-readiness) before enabling cloud -access. The managed database must validate TLS; the development container's -self-signed certificate exception is not used for the cloud target. +Follow [the presenter runbook](docs/presenter.md). Use one existing approved Azure +DocumentDB instance and a dedicated approved demo database. Attendees never need +its credentials. An existing resource avoids new provisioning, not access policy +or charges. Managed TLS validation remains enabled. -The primary app stays in Codespaces. Azure app hosting, background sync, personal -Azure-account creation, and an attendee login system are not workshop requirements. +Use **actual laptop-local** DocumentDB for an on-prem/cloud analogy. A Codespace +connected to Azure is self-hosted-to-managed, not an on-prem demonstration. +Keep a rehearsed recording as backup; the attendee lab and calendar outcome +remain complete if cloud networking fails. Kubernetes is optional future reading, +not a dependency or a substitute for cloud resource access. -## Stop without losing your planner +The [organizer guide](docs/organizer.md) describes classroom preparation. +The alternate Organizer Codespace includes Azure CLI/Bicep for separately +approved legacy provisioning only; it grants no permissions and still starts +only the attendee simulation. Do not share an authenticated organizer environment. -Export your calendar and preserve your code changes, then stop your Codespace -from [Your codespaces](https://github.com/codespaces). Stopping compute does not -necessarily end storage charges. Deletion or retention expiry removes its -development database and unpreserved work; this is not permanent hosting. +## Stop without losing your planner -Do not delete Docker volumes or replace `.env` as a recovery step. That can lose -favorites or leave credentials out of sync with the database. +Export your calendar and preserve code, then stop your Codespace from +[Your codespaces](https://github.com/codespaces). Stopping compute may not stop +storage charges. Deletion or retention expiry removes local databases and +unpreserved work: Codespaces is not permanent hosting. -Stopping or deleting a Codespace does **not** delete Azure resources. The organizer -must follow the separately approved cleanup procedure in the -[organizer runbook](docs/organizer.md#cleanup-and-shutdown). +Laptop users can `docker compose -f compose.yaml stop`. Do not delete volumes or +replace `.env` for normal stopping. Deleting/stopping a Codespace does **not** +stop or delete Azure resources. The presenter follows the approved ownership and +cleanup policy for the existing Azure resource; never delete a shared cluster. ## Contributor checks -In either Codespaces configuration, or for contributors with Node.js 24.13 or newer: +With Node.js 24.13 or newer (already available inside Codespaces): ```sh -npm ci +npm ci --ignore-scripts npm test ``` -With the development Compose stack running: +With the two-site Compose stack running: ```sh -docker compose exec app npm run test:database +docker compose -f compose.yaml exec app npm run test:database ``` -Database checks use uniquely named temporary databases on the **local** endpoint -and remove only those databases. They explicitly ignore cloud configuration. -They exercise independence, additive round trips, duplicate prevention, partial -results, indexes, migrations, and the API. They are not an Azure compatibility -claim. +Integration checks use uniquely named temporary databases on **two different +local server services**, never the configured cloud endpoint. They remove only +their own temporary databases. Checks cover independent favorites, additive +round trips, timestamp/duplicate preservation, partial results, indexes, +migrations, and HTTP target switching. CI runs these checks on Linux; this is +not a live Azure or fresh Codespaces claim. -See the [attendee guide](docs/lab.md), [instructor guide](docs/instructor.md), -[organizer runbook](docs/organizer.md), and [Azure plan](.azure/deployment-plan.md). -Code is available under the -[MIT license](LICENSE). +See the [lab](docs/lab.md), [instructor guide](docs/instructor.md), +[presenter runbook](docs/presenter.md), and [delivery plan](.azure/deployment-plan.md). +Code is available under the [MIT license](LICENSE). diff --git a/compose.presenter.yaml b/compose.presenter.yaml new file mode 100644 index 0000000..dec34a3 --- /dev/null +++ b/compose.presenter.yaml @@ -0,0 +1,9 @@ +# Opt-in presenter data plane only. Does not provision, seed, or authenticate to Azure. +# Attendee default is compose.yaml; this override keeps Site B out of the UI. +services: + app: + environment: + WORKSHOP_SCENARIO: presenter + ACTIVE_TARGET: ${ACTIVE_TARGET:-local} + CLOUD_DOCUMENTDB_URI: ${CLOUD_DOCUMENTDB_URI:-} + CLOUD_DATABASE_NAME: ${CLOUD_DATABASE_NAME:-} diff --git a/compose.yaml b/compose.yaml index 66b1baf..62c42de 100644 --- a/compose.yaml +++ b/compose.yaml @@ -8,6 +8,15 @@ services: - documentdb-data:/data stop_grace_period: 30s + documentdb-site-b: + image: ghcr.io/documentdb/documentdb/documentdb-local:pg17-0.117.0@sha256:a22772de11861a97d395eecdbe6fbaedd245498b015e748ca409f526430ca781 + environment: + USERNAME: ${SITE_B_USERNAME:?Run the setup command first} + PASSWORD: ${SITE_B_PASSWORD:?Run the setup command first} + volumes: + - documentdb-site-b-data:/data + stop_grace_period: 30s + app: build: context: . @@ -17,17 +26,25 @@ services: depends_on: documentdb: condition: service_started + documentdb-site-b: + condition: service_started environment: DOCUMENTDB_USERNAME: ${DOCUMENTDB_USERNAME:?Run the setup command first} DOCUMENTDB_PASSWORD: ${DOCUMENTDB_PASSWORD:?Run the setup command first} LOCAL_DOCUMENTDB_HOST: documentdb LOCAL_DATABASE_NAME: ${LOCAL_DATABASE_NAME:-ato_workshop} - CLOUD_DOCUMENTDB_URI: ${CLOUD_DOCUMENTDB_URI:-} - CLOUD_DATABASE_NAME: ${CLOUD_DATABASE_NAME:-} + SITE_B_USERNAME: ${SITE_B_USERNAME:?Run the setup command first} + SITE_B_PASSWORD: ${SITE_B_PASSWORD:?Run the setup command first} + SITE_B_DOCUMENTDB_HOST: documentdb-site-b + SITE_B_DATABASE_NAME: ${SITE_B_DATABASE_NAME:-ato_workshop} + # Attendee startup cannot inherit a legacy Azure URI or scenario. + CLOUD_DOCUMENTDB_URI: "" + CLOUD_DATABASE_NAME: "" + WORKSHOP_SCENARIO: attendee WORKSHOP_MODE: ${WORKSHOP_MODE:-starter} WORKSHOP_LOCATION: ${WORKSHOP_LOCATION:-laptop} WORKSHOP_PUBLIC_HOST: ${WORKSHOP_PUBLIC_HOST:-} - ACTIVE_TARGET: ${ACTIVE_TARGET:-local} + ACTIVE_TARGET: local HOST: 0.0.0.0 PORT: "3000" ports: @@ -45,4 +62,5 @@ services: start_period: 30s volumes: + documentdb-site-b-data: documentdb-data: diff --git a/docs/instructor.md b/docs/instructor.md index c83104b..85cd558 100644 --- a/docs/instructor.md +++ b/docs/instructor.md @@ -1,59 +1,72 @@ # Instructor and helper guide Audience: developers comfortable with APIs, new to DocumentDB and hybrid apps. -Use short explanations and observable checkpoints. One or two helpers support -setup while the presenter keeps the main group moving. +One or two helpers handle setup while the presenter keeps the group moving. +The protected attendee outcome is a useful planner and a completed copy/return +trip across two independent OSS DocumentDB instances—without Azure access. ## The 105-minute journey | Minutes | Activity | | --- | --- | -| 0-5 | Introduce the planner; launch the attendee Codespace | -| 5-20 | Finish browser sign-in and automated setup; open the private app port | -| 20-35 | Complete the two repository TODOs and save favorites | -| 35-43 | Explore scheduling conflicts and development-database persistence | -| 43-53 | Switch the same application to Azure; diagnose missing favorites | -| 53-68 | Copy selected favorites; demonstrate an idempotent retry | -| 68-80 | Create a cloud favorite, copy it back, and preserve development choices | -| 80-90 | Demonstrate repeatable indexes and a document migration | -| 90-98 | Export calendars, explain hosted-access expiry, and stop safely | -| 98-100 | Point to the upstream project, docs, and contribution routes | -| 100-105 | Questions and recovery buffer | - -The protected outcome is the same data-access code against self-hosted development -DocumentDB and managed Azure DocumentDB. "Local" means local to the development -environment; with Codespaces, both environments are physically cloud-hosted. -Shorten the index/migration extension before sacrificing the central -connection-versus-data lesson, return trip, or cleanup explanation. - -Align attendee communications with this delivery choice: browser, GitHub account, -and available Codespaces usage; no laptop Docker installation. Explain the -development-local meaning of "local" at the start rather than promising offline -laptop operation. - -## Setup risks - -Attendees need a browser, GitHub account, connectivity, and available Codespaces -usage. No local Docker, Node.js, Git, or Azure CLI installation is required. -At about minute 12, triage blocked sign-in, organization policy, or usage limits -with a helper; target a working environment by minute 20. - -Do not promise startup timings without measuring cold creation on representative -accounts and networks. Optional local Docker is only for people who already have -it working; it is not the default path or an installation exercise. - -Codespaces needs a GitHub account, available usage, and network access. Confirm -the funding/access arrangement and a pairing or instructor-follow-along option -for people blocked from Codespaces. Do not publish app or database ports to bypass -access controls. - -The browser editor supports the TODOs. The complete reference provides a recovery -path without replacing an attendee's exercise file or changing their database. - -Optional GitHub CLI diagnostics require both the `codespace` OAuth scope and an -SSH server in the dev container. Those are instructor-tooling requirements, not -extra steps for browser-only attendees. The completed-exercise test contract -accepts either an explicit unfinished TODO or the correct implementation. +| 0–20 | One-minute finished-planner demo, architecture, Codespaces setup; triage at minute 12 | +| 20–50 | Two repository TODOs, favorites, overlaps, persistence | +| 50–70 | Site A/B switch, missing favorites, explicit copy, retry, return trip | +| 70–85 | Presenter-only actual laptop-to-Azure demonstration or rehearsed recording | +| 85–95 | Repeatable indexes and migration extension | +| 95–105 | Calendar export, safe stopping, upstream pointers, questions | + +This is a planned allocation, not a measured rehearsal. Setup delays consume the +index/migration extension first. Protect the return trip, calendar export, and +cleanup. Keep cloud troubleshooting off the critical attendee path. + +## Opening explanation + +Show the finished planner for one minute. Draw browser → Node app → DocumentDB. +The MongoDB Node.js driver sends operations to DocumentDB's MongoDB-compatible +API; the self-hosted engine is built on PostgreSQL. Both repository methods stay +the same when the deployment changes. This verifies selected operations, not +universal MongoDB parity or identical managed/self-hosted operations. + +Say: **“Same code, separate data.”** Attendees have two independent containers, +credentials, and storage volumes, **not** two databases sharing one server. +In Codespaces both are hosted inside one development environment, not physically +on-prem. Site A/B are a simulation of site boundaries; copying selected favorites +is application logic, not streaming replication, automatic failover, or a generic +synchronization engine. The presenter demonstrates the actual laptop/cloud boundary. + +## Setup risks and recovery + +Attendees need a browser, GitHub account, internet, and available Codespaces usage. +Confirm machine capacity, quota/funding and conference-network access in advance. +Two database containers increase cold-start/storage/memory demand. Do not promise +startup times without measuring representative fresh accounts/machines. + +At minute 12, helpers triage blocked sign-in, policy, quota and startup. Target a +working environment by minute 20. Use the agreed pairing/follow-along option; +never share logins or publish app/database ports. Optional laptop Docker is only +for people who already have it working—not an installation exercise. + +`npm run workspace:start` safely adds missing Site B configuration, explicitly +uses the attendee Compose file, waits for each database, and seeds both catalogs. +It does not authenticate to or seed Azure. A failed Site B wait/seed is a failed +setup, not silent success with one working site. An older Azure URI in `.env` +is not passed into the attendee app. Keep secrets out of logs/screenshots. + +Both dev-container configurations start this simulation; the Organizer profile's +Azure tooling is optional and does not confer permissions. The browser editor +supports the TODOs. The complete-reference override preserves exercises and data. +Optional GitHub CLI/SSH diagnostics are helper tools, not attendee prerequisites. + +## Observable checkpoints + +- Both sites ready and seeded; the intentional TODO explains the empty planner. +- TODO 1: 216 entries. TODO 2: save two favorites and retain them across app restart. +- Switch A → B: same catalog, no automatic favorite movement; A remains intact. +- Copy A → B; switch back to A before repeating that same direction; Already present. +- New favorite at B; copy B → A; original A choices survive. +- Removal is local to its site, not propagated to copies. +- Export from the intended site, preserve code, stop without deleting volumes. ## Schedule data @@ -128,89 +141,68 @@ Seed the same snapshot in both targets, but never pre-copy attendee favorites. Otherwise the missing-favorites exercise either hides its own lesson or becomes confused with a missing catalog. -## Azure readiness +## Presenter Azure readiness -Use the separate **ATO 2026 - Organizer** configuration and -[organizer runbook](organizer.md) to provision from Codespaces. Attendee startup -does not request Azure-management credentials. Never share the authenticated -organizer environment with students. +Follow the dedicated [presenter runbook](presenter.md). The organizer already has +an existing authorized Azure DocumentDB instance: no classroom cluster fleet or +new test subscriptions are required. Attendees never receive those credentials. +Use an approved dedicated demo database; no generic deletion of shared resources. -Arrange organizer-provided workshop accounts before attendee delivery. Establish -account/subscription scope, permitted regions and tiers, quotas, attendee access -policy, expiry, and cleanup authority. +Use actual laptop-local DocumentDB for the live hybrid story. A Codespaces source +must instead be labeled self-hosted-to-managed. Rehearse the same catalog, local +favorites, empty managed favorites, explicit copy/retry, and return trip before +class. The repo's earlier managed round trip remains unverified until that proof +is recorded. Have a checked recording; if live connectivity fails, switch to it +rather than spend attendee time debugging access. -A separately approved Azure subscription may be used for rehearsal before event -accounts are available. Confirm the target before any provider access or database -operation. Rehearsal success does not prove that event accounts have the same -policies, quotas, or permissions. +Validated cloud TLS stays enabled. Observe current source IP/DNS and use approved +narrow network rules; never broaden to all addresses or disable certificates. +Editing `.env` does not rotate database users and requires recreating the app. +Presenter commands select `compose.presenter.yaml` explicitly; normal attendee +startup selects only `compose.yaml` and will return to Site A/B. -Attendees should receive prepared, isolated data-plane access; they do not need -Azure portal accounts for this lab. Establish a permitted network route from -laptops and Codespaces, including DNS/SRV lookup and validated TLS. Do not solve -conference-network problems by allowing the whole internet or sharing admin -credentials. - -A Codespace's outbound IP changed during the live rehearsal after stop/resume. -Re-observe it and update only its exact firewall entry before cloud access; -do not assume a previously allowlisted address is still correct. - -Do not assume that a database per attendee on one cluster is isolated. Current -native secondary-user permissions are cluster-wide. Use separately assigned -clusters for the direct-credential model and verify denied cross-attendee access -with two test identities. The two-cluster control-plane rehearsal succeeded; -managed data-plane isolation and the classroom-scale rollout remain unverified -and need their own approved scope. - -Record the approved scope, runtime bounds, exact workshop resource ownership, -credential delivery/revocation, and cleanup owner before provisioning. If cleanup -fails, stop new provisioning and escalate visibly. Management access expiring -does not prove resource deletion. - -Follow the organizer's approved resource policy, service quotas, subscription -policies, time/retry bounds, and cleanup requirements. Codespaces billing is -separate. +The operator is optional further reading, not a workshop dependency. OSS operator +cross-cluster replication/promotion is a different demonstration from this app's +favorite copying to managed Azure. Do not imply those engines automatically +replicate together. No extra cloud resources are authorized by this guide. ## Troubleshooting without losing the lesson | Observation | Response | | --- | --- | -| Codespaces sign-in, policy, or quota blocks startup | Use the agreed pairing/follow-along path; do not spend the lab installing laptop tooling | -| Container startup fails inside Codespaces | Read the setup error, fix it, and retry `npm run workspace:start`; never hide failure by changing targets | -| App says `TODO_LIST_SESSIONS` or `TODO_SAVE_FAVORITE` | Work the corresponding exercise, or use the complete-reference override | -| App says `DATABASE_UNAVAILABLE` | Confirm readiness and the intended target; inspect local logs privately | -| App says `CATALOG_NOT_SEEDED` | Run seed against that explicit, approved target | -| Cloud favorites are empty | Check whether the connection succeeded; data movement is a separate operation | -| Copy says `CATALOG_MISMATCH` | Compare the catalog versions; do not bypass the check | -| Copy is incomplete | Read per-record outcomes; retry after resolving the failure | -| Edits are not reflected | Save, restart the app if file watching is unavailable, then refresh | -| Credentials changed in `.env` but auth fails | Recreate the app to load config; changing `.env` does not rotate existing database users | -| Calendar export is blocked by orphaned favorites | Diagnose catalog drift instead of silently discarding favorite records | - -Avoid `docker compose config` without its quiet flag: expanded configuration can -print credentials. Avoid database reset, volume pruning, global container cleanup, -or replacing the attendee's starter file as a generic fix. +| Codespaces sign-in/policy/quota blocked | Pairing/follow-along; no last-minute laptop installation | +| Site A or B startup/seed fails | Read the bounded setup error; fix and retry `npm run workspace:start` | +| `TODO_LIST_SESSIONS` / `TODO_SAVE_FAVORITE` | Complete the exercise or use reference override | +| `DATABASE_UNAVAILABLE` | Confirm intended site, readiness and private logs; never silently use the other site | +| `CATALOG_NOT_SEEDED` | Seed that explicit local target, or retry interrupted same-catalog seed | +| `CATALOG_MISMATCH` | Preserve the old notebook, choose a fresh database name, or review migration | +| Site B favorites empty after switch | Expected: switching isn't copying | +| Incomplete copy | Read per-record outcomes, resolve failure, retry same direction | +| Browser fails after restart | Refresh to obtain the new request token; attendee restarts at Site A | +| Changed credentials fail | Recreate app for config changes; `.env` edits do not rotate an existing volume's users | +| Azure inaccessible | Presenter recording; attendee planner remains usable | +| Orphaned favorites block export | Diagnose catalog drift instead of silently dropping favorites | + +Avoid `docker compose config` without `--quiet`: expanded output can disclose +credentials. Never reset databases, prune volumes, replace `.env`, or overwrite +attendee exercises as generic recovery. Keep the same Compose project name to +retain Site A's existing volume. ## Rehearsal checklist -- Fresh attendee Codespace and organizer configuration, not just warm containers. -- Working starter/reference switching without loss of favorites. -- Both targets seeded with the same catalog. -- Same repository methods against real local and managed DocumentDB. -- Independent favorites before explicit copying. -- Retry-safe copying in both directions, including partial outcomes. -- Local choices preserved on the return trip. -- Conflict boundary cases and usable calendar import. -- Honest development-versus-managed labels; no physical-laptop/offline claim. -- Codespaces private port, cold startup, and available usage. -- Two-identity isolation and approved network access. -- Explicit shutdown, credential expiry, and verified cloud cleanup. -- A full timed rehearsal, with buffer rather than a new last-minute feature. +- Fresh attendee Codespace with both instances and measured resource/startup cost. +- Setup upgrade from a legacy `.env` without changing old credentials/data. +- Starter/reference switching and restart persistence at both sites. +- Same catalog, independent favorites before copying, safe repeat/return trip. +- Second-site outage: clear error, no fallback; recovery retains both notebooks. +- Usable calendar import, honest simulation labels, private forwarded port. +- Actual presenter laptop/Azure round trip, narrow access, validated TLS, recording. +- Safe stopping, code/data retention explanation, existing-resource cleanup owner. +- Full 105-minute rehearsal with time to export; no last-minute feature expansion. ## Contribution pointers Use [DocumentDB](https://documentdb.io/), [the upstream repository](https://github.com/documentdb/documentdb), and -[the project documentation](https://documentdb.io/docs/). Explain where attendees -can reproduce an issue, propose a docs improvement, or contribute to the project. -Keep roadmap remarks tied to current official sources rather than promising -unannounced capabilities. +[documentation](https://documentdb.io/docs/). Show how to reproduce an issue, +improve docs, or contribute. Keep roadmap claims tied to current official sources. diff --git a/docs/lab.md b/docs/lab.md index e5120ea..84f1c1a 100644 --- a/docs/lab.md +++ b/docs/lab.md @@ -1,171 +1,183 @@ # Your conference planner -You are building against a real DocumentDB database, using the standard MongoDB -Node.js driver. Your application code will stay the same when its database moves. -Its data will not move unless you explicitly copy it. +Build against real self-hosted DocumentDB using the standard MongoDB Node.js +driver. Your application code stays the same when you switch databases. +**Its data does not move unless you explicitly copy it.** -You only need a browser, a GitHub account, and available Codespaces usage. -Docker, Node.js, the editor, and the development database run in your Codespace. -Do not install Docker on your laptop for this workshop. +You need a browser, a GitHub account, and available Codespaces usage. No Azure +subscription, cloud database credentials, Docker installation on your laptop, +or Kubernetes knowledge is needed. Both independent databases run inside your +Codespace. **Site A / Site B simulate two sites; they are not two clouds, an +on-prem deployment, replication, or automatic failover.** -The repository contains the October 12 snapshot of the published ATO schedule. -It is not a live feed. Times are published program blocks; several keynotes or -lightning talks may run in sequence inside the same block. Some Monday events -require separate registration; saving a favorite does not book a place. +The catalog is the October 12 snapshot of ATO's published schedule, not a live +feed. Times are published blocks; keynotes/lightning talks may be sequential +inside a shared block. Some Monday events require separate registration. +Saving a favorite does not reserve admission. -If you already ran the older practice version, follow the -[non-destructive switch instructions](../README.md#already-ran-the-practice-version) -before seeding the real schedule. +Already used the practice version? Follow the +[non-destructive notebook instructions](../README.md#existing-notebook-or-older-practice-version) +before seeding. Never delete volumes to get past a catalog mismatch. -## 1. Get to a working environment +## 1. Start both sites -Follow [Start in Codespaces](../README.md#start-in-codespaces) and select -**ATO 2026 - Attendee**. Wait for the development-database ready message, then -open private port 3000 from the Ports tab. +Follow [Start in Codespaces](../README.md#start-in-codespaces), choosing +**ATO 2026 - Attendee**. Wait for **both** sites to be ready and seeded, then open +private port **3000**. Run the commands below in the Codespaces terminal. -Use your own GitHub account for Codespaces. Check that you have usage available. -If account policy or quota blocks access, tell a helper early so they can arrange -pairing or a follow-along path. Do not share account logins or start a last-minute -Docker installation. +If account policy or quota blocks startup, tell a helper early for pairing or +follow-along. Do not share logins, expose public ports, or install Docker during +the timed lab. Retry a diagnosed setup failure with `npm run workspace:start`. -Run every command below in the Codespaces terminal. The internal target name -`local` means the development DocumentDB inside that Codespace; `cloud` means -managed Azure DocumentDB. - -Open the planner. Check the active-database label and implementation label. -`TODO_LIST_SESSIONS` is an exercise prompt, not a failed database connection. -`DATABASE_UNAVAILABLE` means the chosen database is not ready or reachable. +Check the active label: **Site A — self-hosted**. The implementation label should +say **TODO starter**. `TODO_LIST_SESSIONS` is intentional; `DATABASE_UNAVAILABLE` +is not. The internal CLI name `local` means Site A; `site-b` means Site B. +Neither means managed Azure. Both sites have separate credentials and volumes. ## 2. Read the catalog -Open [the starter repository](../exercises/starter/repository.js). +Open [exercises/starter/repository.js](../exercises/starter/repository.js). Complete `listSessions(db, catalogVersion)`: -- Use the `sessions` collection. +- Use `sessions`. - Filter on the supplied `catalogVersion`. - Sort by `startsAt`, then `_id`, ascending. - Return the cursor's array. -Do not change the connection code. Node watches this exercise file; refresh the -browser after saving. You should see 216 published schedule entries. - -Need a recovery point? Use the [complete reference](../README.md#complete-reference-and-recovery). -Switching implementations does not replace your exercise or reset your data. +Do not change connection code. Save and refresh the browser: expect **216 entries**. +The same repository function will run against both sites. -## 3. Save a favorite +Need recovery without replacing your exercise? -Complete `saveFavorite(db, sessionId)`: - -- Use the session identifier as the favorite's `_id`. -- Use `updateOne` with `upsert: true`. -- Set `savedAt` with `$setOnInsert` so retrying preserves the original timestamp. -- Return the driver's update result. +```sh +docker compose -f compose.yaml -f compose.complete.yaml up -d --wait --wait-timeout 240 app +``` -Save two genuinely parallel Monday sessions, such as "Local to Cloud and Back: -Building Hybrid Applications on Open Source" and "From Zero to Secure Agent: -Building and Hardening AI Agents with Open Source Tools." Both are listed at -9:00-10:45 a.m. Eastern in different rooms. Their cards and your favorites list -should flag the overlap. Back-to-back sessions are not a conflict. +Refresh. This selects the complete reference but retains your code and both +notebooks. Return to the starter with: -Two talks sharing a keynote or lightning-talk block can be consecutive, so use -the published program to interpret those overlap warnings. +```sh +docker compose -f compose.yaml up -d --wait --wait-timeout 240 app +``` -Restart the app, then refresh. Your favorites should still be there. +## 3. Save favorites and prove persistence -The development database is independent of Azure DocumentDB, but it is still -hosted in Codespaces. Stay connected to the internet; disconnecting your laptop -is not part of this workshop. +Complete `saveFavorite(db, sessionId)`: -## 4. Connect the same code to Azure +- Use the session ID as the favorite's `_id`. +- Use `updateOne` with `upsert: true`. +- Set `savedAt` with `$setOnInsert` so retries preserve the initial timestamp. +- Return the driver's update result. -This section requires organizer-issued sandbox access. It is not runnable until -the organizer confirms the target is authorized. +Save two genuinely parallel Monday sessions, for example: -Put the supplied connection URI and database name in the two cloud fields of -your private `.env`. Keep real values out of source code, screenshots, and chat. -Use the assigned database only. Do not change TLS validation settings. +- “Local to Cloud and Back: Building Hybrid Applications on Open Source” +- “From Zero to Secure Agent: Building and Hardening AI Agents with Open Source Tools” -Recreate the app so it reads the updated configuration, using the same starter -or complete-reference Compose command you have been using. +Both are listed Monday, 9:00–10:45 a.m. Eastern, in different rooms. Their cards +and favorites should flag an overlap. Back-to-back sessions do not conflict. +Interpret shared keynote/lightning-talk blocks using the official program. -Seed **the catalog only** in your assigned cloud database: +Restart the app and refresh: ```sh -docker compose exec app npm run seed -- --target cloud +docker compose -f compose.yaml restart app ``` -Select **Azure DocumentDB** and choose **Switch connection**. -The session catalog should remain familiar, but your development favorites are absent. +Your Site A favorites remain. The browser is not their storage. A restart returns +the attendee app to Site A and changes its request token; refresh after restarting. +Stay connected to Codespaces: laptop-offline operation is not part of this lab. + +## 4. Switch the connection, not the data + +Select **Site B — self-hosted**, then **Switch connection**. +The same 216-entry catalog is there, but Site A's favorites are absent. -Before trying to "fix" the code, explain: +Before “fixing” any code, explain: - Which database is active? -- Did the switch fail, or is the selected database simply holding different data? +- Did the connection fail, or does this database simply contain different data? - Where are the original favorites? -Switch back to the development target and confirm the originals are still there. -No data-access code needed a cloud-specific rewrite. +Switch back to **Site A** and confirm the originals remain. No repository-method +rewrite was required. Setup seeded catalogs, not favorites. -If connectivity fails, distinguish configuration, authentication, certificate, -and network access. The API does not fall back to another environment silently. -Use the active-target label and sanitized error code; ask a helper to inspect -credentials privately. Never fix an Azure certificate problem by disabling TLS. +If switching fails, the API does not silently fall back. Check the active label, +sanitized error, and helper guidance. Do not delete data to repair connectivity. -## 5. Copy selected favorites +## 5. Copy selected favorites and retry -While connected to the development database, select favorite checkboxes in the -side panel. Choose **Copy selected favorites**. Review the source, destination, -and records in the confirmation dialog, then confirm. +While **Site A** is active: -Switch to Azure and see the copied favorites. Repeat the same copy once: -the records should report **Already present**, not create duplicates. +1. Select favorite checkboxes in the side panel. +2. Choose **Copy selected favorites**. +3. Verify the confirmation says **Site A → Site B**, inspect the selection, confirm. +4. Switch to **Site B** and see the copied favorites. +5. **Switch back to Site A**, select the same favorites, and repeat **Site A → Site B**. + Expect **Already present**, not new duplicates. -The tool reports every selected record. If a copy is incomplete, review the -failed or unattempted records. Retry only after resolving the cause; do not assume -the entire request was rolled back. +The source is always the active site; switching before copying changes direction. +Read the confirmation instead of assuming the destination. + +Partial results are per record: copied, already present, invalid, failed, or +unattempted. A failed batch is not automatically rolled back. Resolve the cause +and retry safely; initial save timestamps and existing choices are preserved. ## 6. Bring one back -Save another favorite while the cloud target is active. Select that favorite, -review the copy back to the development target, and confirm. +Switch to **Site B**. Save a different session. Select that new favorite and +confirm **Site B → Site A**. Switch back to **Site A**: the original choices remain +and the new one is added. Any resulting overlap is flagged. + +Removing a favorite from one site does not remove its copy at the other. This +is explicit additive copying, not bidirectional synchronization or conflict +resolution. The two containers simulate deployment boundaries; they do not prove +multi-cloud networking or disaster recovery. + +## 7. Watch the real hybrid capstone + +The presenter repeats the same mechanics on their screen using an actual +laptop-local DocumentDB and an existing managed Azure DocumentDB instance. +You do **not** enter Azure credentials or follow cloud commands. -Switch back. Your original choices remain, and the new choice is added. -Any new overlap is flagged. +Predict what should happen before the presenter switches or copies. The lesson +is the same: **same code, separate data**. Azure supplies a managed environment; +application-level favorite copying is not database replication. -Removing a favorite from one database does not remove it from the other. This is -deliberate copying, not a complete bidirectional synchronization system. +If cloud networking is unavailable, the presenter uses a rehearsed recording. +Your planner and remaining exercises still work. Codespaces itself still needs +internet access. A presenter using Codespaces rather than a laptop must describe +that as self-hosted-to-managed, not on-prem-to-cloud. -## 7. Make changes repeatable +## 8. Make changes repeatable -The instructor will demonstrate the same commands against each authorized target: +If time permits, follow the instructor against Site A: ```sh -docker compose exec app npm run indexes -- --target local -docker compose exec app npm run migrate -- --target local -docker compose exec app npm run check -- --target local +docker compose -f compose.yaml exec app npm run indexes -- --target local +docker compose -f compose.yaml exec app npm run migrate -- --target local +docker compose -f compose.yaml exec app npm run check -- --target local ``` -The index exercise makes an index definition repeatable; it does not prove that -a particular engine will use it for sorting. The migration adds `attendanceMode` to -version-1 documents. Run it again: it should report zero newly migrated records. -Apply the corresponding command to `cloud` only when that target is approved. +Run the migration again: expect **zero newly migrated records**. It adds +`attendanceMode` to version-1 documents. Re-seeding does not undo it. Use +`--target site-b` for the same operations on Site B. -Compare index names and document versions rather than claiming a tiny dataset -must exhibit a visible speedup. Re-seeding does not undo the migration. +The index exercise makes the definition repeatable; it does not guarantee an +engine uses it for sorting or that a tiny dataset visibly speeds up. Compare +index names and document versions. Skip this extension before sacrificing the +return trip, calendar export, or cleanup. -## 8. Take your selections with you +## 9. Take your selections with you -Choose **Download calendar (.ics)** and import the downloaded snapshot manually -into your calendar. Conflicting selections are exported too: warnings inform you, -not silently choose which sessions you attend. +On the site containing your final choices, choose **Download calendar (.ics)**. +Import the snapshot manually into your calendar. Conflicting selections are +exported too; warnings inform you rather than silently choosing for you. -The file uses real session titles and dates from the captured schedule, not -practice labels. Check the official schedule for subsequent changes and for the -sequence of talks inside shared program blocks. +The export contains real titles/dates from the captured schedule. Check the +[official schedule](https://2026.allthingsopen.org/schedule) for changes and +within-block talk ordering. The file is independent of Codespaces and Azure. -Export before the end of temporary Azure access or Codespaces retention. Your -downloaded calendar is independent of both services. Preserve code changes before -deleting a Codespace; its development database is not permanent hosting. Follow -the stop instructions in the -[README](../README.md#stop-without-losing-your-planner); do not delete volumes as -part of normal stopping. +Export and preserve code before stopping/deleting the Codespace. Follow +[stop instructions](../README.md#stop-without-losing-your-planner). Do not delete +volumes or `.env` as normal cleanup; retention expiry still removes hosted data. diff --git a/docs/legacy-azure-provisioning.md b/docs/legacy-azure-provisioning.md new file mode 100644 index 0000000..3ff4b99 --- /dev/null +++ b/docs/legacy-azure-provisioning.md @@ -0,0 +1,234 @@ +> **Optional legacy provisioning only.** Not part of attendee setup or the current +> presenter path, which uses an existing approved Azure instance. No new resources +> are needed for the workshop. This runbook requires separate provisioning authority. +> Start with [organizer guidance](organizer.md) and the [presenter runbook](presenter.md). + +# Deploy from an organizer Codespace + +This is a supervised organizer runbook, not an attendee prerequisite or an +unattended cleanup worker. It uses Azure CLI and the existing Bicep templates; +no Azure tooling needs to be installed on your laptop. + +The templates currently model two isolated rehearsal participants in East US. +Plan classroom capacity separately once attendance and account policies are +known. A configuration or generated parameter file is not authorization to deploy. + +## 1. Open the organizer environment + +In the repository's **Code > Codespaces** menu, create a Codespace with advanced +options and select **ATO 2026 - Organizer** as the dev-container configuration. +Attendees should select **ATO 2026 - Attendee** instead. + +The organizer environment includes the development app/database, Azure CLI, and +Bicep. Startup verifies tooling and starts only the development environment: + +```sh +npm run organizer:check +``` + +Nothing signs in to Azure or provisions resources automatically. Do not share this +authenticated Codespace or its Azure login cache with attendees. Selecting the +organizer configuration grants tools, not Azure permissions. + +## 2. Establish the approved scope + +Before creating anything, record the authorized subscription, region, two-cluster +inventory, operation/time/retry bounds, expiry, network clients, usage policy, and +cleanup owner in approved private storage. Set a bounded Codespaces machine, +runtime, retention, and spending allowance too. + +Sign in as the approved Azure operator: + +```sh +az login --use-device-code +``` + +Complete the browser sign-in and any MFA yourself. GitHub authentication does not +grant Azure access. If tenant policy blocks authentication from Codespaces, stop; +do not copy a laptop's login cache or work around conditional access. + +Set the approved subscription explicitly and verify it: + +```sh +export SUBSCRIPTION_ID="" +az account show --subscription "$SUBSCRIPTION_ID" \ + --query "{id:id,name:name,tenantId:tenantId}" --output json +``` + +The subscription-scoped template creates a new resource group. Its operator needs +permission for that deployment scope, not merely permission to query a database. +Do not grant new roles or policy exemptions as an automatic fallback. + +## 3. Prepare private inputs + +Observe each client IP from the environment that will connect. For example, run +the following inside the organizer Codespace, and have the participant environment +observe its own address: + +```sh +curl -4 --fail --silent --show-error --max-time 20 https://api.ipify.org +``` + +An IP check made on your laptop is not the Codespace's address. A stopped/resumed +Codespace can get a new address. Never replace a narrow rule with an all-address +range to avoid checking. + +Prepare a new private run, supplying the addresses and UTC expiry approved above: + +```sh +npm run organizer:prepare -- \ + --subscription "$SUBSCRIPTION_ID" \ + --location eastus \ + --client-ip "" \ + --client-ip "" \ + --expires-at "" +``` + +If there is only one distinct client, omit the second `--client-ip`. The helper +creates a fresh owner-only directory under the organizer's home, outside Git. +It writes: + +- `manifest.json`: proposed IDs, names, ownership correlation, clients, and expiry. +- `parameters.json`: deployment inputs, including independently generated + administrator passwords. This file is sensitive; never print or publish it. + +The helper makes **no Azure calls**. `actionsExecuted: false` is intentional. +Preserve the manifest in approved durable private storage outside the Codespace +before deployment; its local disk is not an independent recovery service. + +Set the private path printed by the helper, then load only non-secret context: + +```sh +export RUN_DIR="" +export RESOURCE_GROUP="$(node -p 'require(process.env.RUN_DIR + "/manifest.json").resourceGroupName')" +export DEPLOYMENT_NAME="$(node -p 'require(process.env.RUN_DIR + "/manifest.json").deploymentName')" +export RUN_ID="$(node -p 'require(process.env.RUN_DIR + "/manifest.json").runId')" +``` + +Keep `SUBSCRIPTION_ID` consistent with the manifest. Do not regenerate passwords +by rerunning preparation when a deployment outcome is uncertain. + +## 4. Validate, preview, and deploy + +Verify that the generated resource group does not already exist: + +```sh +az group exists --name "$RESOURCE_GROUP" \ + --subscription "$SUBSCRIPTION_ID" --output tsv +``` + +Continue only after a successful response of `false`. Authentication and permission +errors are not evidence of absence. Inspect inherited policy, regional availability, +and quota before executing the approved plan. + +Build and validate using the sensitive parameter **file path**, not inline passwords: + +```sh +az bicep build --file infra/rehearsal.bicep --outfile "$RUN_DIR/template.json" + +az deployment sub validate \ + --name "$DEPLOYMENT_NAME" --location eastus \ + --subscription "$SUBSCRIPTION_ID" \ + --template-file "$RUN_DIR/template.json" \ + --parameters "@$RUN_DIR/parameters.json" + +az deployment sub what-if \ + --name "$DEPLOYMENT_NAME" --location eastus \ + --subscription "$SUBSCRIPTION_ID" \ + --template-file "$RUN_DIR/template.json" \ + --parameters "@$RUN_DIR/parameters.json" +``` + +Review the exact inventory: the fresh group, two named clusters, and only the +supplied single-IP rules. No unrelated modifications or deletions are acceptable. +Use the normal preparation/validation approval process before the actual write: + +```sh +az deployment sub create \ + --name "$DEPLOYMENT_NAME" --location eastus \ + --subscription "$SUBSCRIPTION_ID" \ + --template-file "$RUN_DIR/template.json" \ + --parameters "@$RUN_DIR/parameters.json" \ + --query "{id:id,state:properties.provisioningState,timestamp:properties.timestamp}" \ + --output json > "$RUN_DIR/deployment-result.json" +``` + +Check the real result and both cluster states. A submitted request, an intent +manifest, or a successful what-if is not proof of a usable database. Keep the +receipt in the approved private recovery record. If a write times out, reconcile +the exact IDs before retrying; do not launch duplicate creates. + +Initial public access is **disabled**. Before enabling it, verify ownership and +the exact firewall rules, and re-observe the clients' current IPs. Review a new +what-if with `enablePublicAccess=true`; only then apply that same approved change. +Do not add an Azure-service bypass rule or disable TLS validation. + +Prepare participant-only database credentials and verify isolation using the +service's supported user-management procedure. Do not distribute the administrator +password object or the organizer's Azure session. Native permissions are currently +cluster-wide, so database names alone do not isolate participants. + +## 5. Rehearse the application + +Use the organizer's development app to verify the managed connection before +attendee delivery. Then follow the [lab](lab.md): seed the same catalog, switch +targets without moving favorites, copy selected favorites, retry safely, and +copy a new cloud favorite back. + +Opening a Codespace from the repository does not demonstrate this managed +data-plane journey. Neither the new organizer profile nor this complete procedure +has had a fresh end-to-end live rehearsal yet. + +## Cleanup and shutdown + +Keep the approved execution window and stop path visible. An expiry tag does not +delete Azure resources; an idle/stopped/deleted Codespace can no longer run your +cleanup commands. + +Before deleting each cluster, read its **exact ID from the manifest** and verify +the real resource's subscription, location, and `ato-rehearsal-run` tag: + +```sh +export CLUSTER_ID="" +az resource show --ids "$CLUSTER_ID" --subscription "$SUBSCRIPTION_ID" \ + --api-version 2026-06-01 \ + --query "{id:id,type:type,location:location,run:tags.\"ato-rehearsal-run\"}" \ + --output json +``` + +Only after ownership and cleanup authority are confirmed: + +```sh +az resource delete --ids "$CLUSTER_ID" \ + --subscription "$SUBSCRIPTION_ID" --api-version 2026-06-01 +``` + +Repeat for the other recorded cluster. Wait for authoritative absence of both +IDs; an authentication failure or accepted delete request is not absence. + +Verify the group still belongs to the run and its resource inventory is empty +before deleting that exact group. If unexpected resources are present, stop and +escalate rather than deleting them. + +```sh +az resource list --resource-group "$RESOURCE_GROUP" \ + --subscription "$SUBSCRIPTION_ID" --output table + +# Run only after the ownership and empty-inventory checks above. +az group delete --name "$RESOURCE_GROUP" \ + --subscription "$SUBSCRIPTION_ID" --yes +``` + +Verify group absence. Remove the temporary parameter file only after cleanup is +confirmed; retain the non-secret ownership/cleanup record as required. Deleting +deployment history alone does not delete the resources. + +Export any work you need before stopping/deleting the Codespace. Do not report +success while resources or cleanup status remain unresolved. + +## References + +- [Azure CLI sign-in](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively) +- [Deploy Bicep with Azure CLI](https://learn.microsoft.com/azure/azure-resource-manager/bicep/deploy-cli) +- [Azure CLI dev-container feature](https://github.com/devcontainers/features/tree/main/src/azure-cli) +- [DocumentDB native-user limitations](https://learn.microsoft.com/azure/documentdb/limitations#native-documentdb-secondary-users) diff --git a/docs/local.md b/docs/local.md index f4162aa..a517aab 100644 --- a/docs/local.md +++ b/docs/local.md @@ -1,42 +1,53 @@ # Optional laptop-local setup -The workshop is browser-first. Use this appendix only if you already have Docker -working and prefer a physical-laptop environment; do not spend the timed workshop -installing or repairing Docker. +The attendee workshop is browser-first. Use this appendix only if Docker already +works on your laptop; do not spend the timed workshop installing/repairing it. +You need Docker with Linux containers, Docker Compose, a browser and text editor. +No host Node.js, Azure CLI or Kubernetes installation is required. -You need Docker with Linux containers, Docker Compose, a browser, and a text -editor. No host Node.js installation is required. Download/extract the repository -ZIP or clone it, then open a terminal in the project directory. +Download/extract or clone the repository and open a terminal in its directory. +Use a consistent directory and Compose project name to keep the same volumes. ```sh docker compose -f compose.setup.yaml run --rm setup -docker compose up --build -d --wait --wait-timeout 240 -docker compose exec app npm run seed -- --target local +docker compose -f compose.yaml up --build -d --wait --wait-timeout 240 +docker compose -f compose.yaml exec app npm run wait:database -- --target local +docker compose -f compose.yaml exec app npm run wait:database -- --target site-b +docker compose -f compose.yaml exec app npm run seed -- --target local +docker compose -f compose.yaml exec app npm run seed -- --target site-b ``` -Open **http://localhost:3000**. The starter intentionally reports -`TODO_LIST_SESSIONS` until you finish the first exercise. Continue with the -[attendee guide](lab.md), interpreting its development target as your local -container instead of a container inside Codespaces. +Stop at any failing command, diagnose it, then retry; do not skip readiness or +pretend the second site is available. These commands access only local sites. -Setup creates private local credentials in `.env` and never replaces an existing -file. The database has no published host port; the app is bound to loopback. -Do not expose either publicly. +Open **http://localhost:3000**. The starter reports `TODO_LIST_SESSIONS` until +the first exercise is complete. Follow the [lab](lab.md); here both independent +sites run on your physical laptop rather than inside Codespaces. It is still a +two-site simulation, not two physical sites or cloud providers. -On a network requiring an approved anonymous npm mirror, put its URL in -`NPM_REGISTRY` in your private `.env`. Never include a token/password in a build -argument or disable TLS verification. +Setup creates independent private credentials. For an old `.env`, it preserves +all old values and appends only missing Site B settings. It refuses partial/empty +Site B credentials rather than guessing about an existing volume. Neither database +publishes a host port; the app binds to loopback. Do not expose them publicly. -Your development data persists in the named Docker volume. The -[practice-to-official catalog instructions](../README.md#already-ran-the-practice-version) -preserve an older notebook. Changing code variants does not reset the volume. +On a network requiring an approved anonymous npm mirror, set `NPM_REGISTRY` in +your private `.env`. Never put tokens/passwords in build arguments or disable TLS. -To stop without deleting your notebook: +Site A retains the original `documentdb-data` volume; Site B has its own +`documentdb-site-b-data` volume. The +[existing-notebook instructions](../README.md#existing-notebook-or-older-practice-version) +preserve older practice data. Switching starter/reference does not reset either. + +To stop without deleting notebooks: ```sh -docker compose stop +docker compose -f compose.yaml stop ``` -Once setup and image downloads finish, the app and development database can run -without internet access. Azure connectivity still needs a network connection. -This optional behavior is not an offline promise for the Codespaces-first workshop. +After dependencies/images are downloaded and startup completes, the self-hosted +app/databases can operate without internet. Official schedule links still need +connectivity. This is not an offline promise for Codespaces. + +For the **presenter-only** actual laptop/Azure capstone, follow the +[separate runbook](presenter.md) and explicit presenter override. The normal +attendee commands do not enable Azure even when cloud settings exist in `.env`. diff --git a/docs/organizer.md b/docs/organizer.md index 403bd57..2ca60d3 100644 --- a/docs/organizer.md +++ b/docs/organizer.md @@ -1,229 +1,68 @@ -# Deploy from an organizer Codespace - -This is a supervised organizer runbook, not an attendee prerequisite or an -unattended cleanup worker. It uses Azure CLI and the existing Bicep templates; -no Azure tooling needs to be installed on your laptop. - -The templates currently model two isolated rehearsal participants in East US. -Plan classroom capacity separately once attendance and account policies are -known. A configuration or generated parameter file is not authorization to deploy. - -## 1. Open the organizer environment - -In the repository's **Code > Codespaces** menu, create a Codespace with advanced -options and select **ATO 2026 - Organizer** as the dev-container configuration. -Attendees should select **ATO 2026 - Attendee** instead. - -The organizer environment includes the development app/database, Azure CLI, and -Bicep. Startup verifies tooling and starts only the development environment: - -```sh -npm run organizer:check -``` - -Nothing signs in to Azure or provisions resources automatically. Do not share this -authenticated Codespace or its Azure login cache with attendees. Selecting the -organizer configuration grants tools, not Azure permissions. - -## 2. Establish the approved scope - -Before creating anything, record the authorized subscription, region, two-cluster -inventory, operation/time/retry bounds, expiry, network clients, usage policy, and -cleanup owner in approved private storage. Set a bounded Codespaces machine, -runtime, retention, and spending allowance too. - -Sign in as the approved Azure operator: - -```sh -az login --use-device-code -``` - -Complete the browser sign-in and any MFA yourself. GitHub authentication does not -grant Azure access. If tenant policy blocks authentication from Codespaces, stop; -do not copy a laptop's login cache or work around conditional access. - -Set the approved subscription explicitly and verify it: - -```sh -export SUBSCRIPTION_ID="" -az account show --subscription "$SUBSCRIPTION_ID" \ - --query "{id:id,name:name,tenantId:tenantId}" --output json -``` - -The subscription-scoped template creates a new resource group. Its operator needs -permission for that deployment scope, not merely permission to query a database. -Do not grant new roles or policy exemptions as an automatic fallback. - -## 3. Prepare private inputs - -Observe each client IP from the environment that will connect. For example, run -the following inside the organizer Codespace, and have the participant environment -observe its own address: - -```sh -curl -4 --fail --silent --show-error --max-time 20 https://api.ipify.org -``` - -An IP check made on your laptop is not the Codespace's address. A stopped/resumed -Codespace can get a new address. Never replace a narrow rule with an all-address -range to avoid checking. - -Prepare a new private run, supplying the addresses and UTC expiry approved above: - -```sh -npm run organizer:prepare -- \ - --subscription "$SUBSCRIPTION_ID" \ - --location eastus \ - --client-ip "" \ - --client-ip "" \ - --expires-at "" -``` - -If there is only one distinct client, omit the second `--client-ip`. The helper -creates a fresh owner-only directory under the organizer's home, outside Git. -It writes: - -- `manifest.json`: proposed IDs, names, ownership correlation, clients, and expiry. -- `parameters.json`: deployment inputs, including independently generated - administrator passwords. This file is sensitive; never print or publish it. - -The helper makes **no Azure calls**. `actionsExecuted: false` is intentional. -Preserve the manifest in approved durable private storage outside the Codespace -before deployment; its local disk is not an independent recovery service. - -Set the private path printed by the helper, then load only non-secret context: - -```sh -export RUN_DIR="" -export RESOURCE_GROUP="$(node -p 'require(process.env.RUN_DIR + "/manifest.json").resourceGroupName')" -export DEPLOYMENT_NAME="$(node -p 'require(process.env.RUN_DIR + "/manifest.json").deploymentName')" -export RUN_ID="$(node -p 'require(process.env.RUN_DIR + "/manifest.json").runId')" -``` - -Keep `SUBSCRIPTION_ID` consistent with the manifest. Do not regenerate passwords -by rerunning preparation when a deployment outcome is uncertain. - -## 4. Validate, preview, and deploy - -Verify that the generated resource group does not already exist: - -```sh -az group exists --name "$RESOURCE_GROUP" \ - --subscription "$SUBSCRIPTION_ID" --output tsv -``` - -Continue only after a successful response of `false`. Authentication and permission -errors are not evidence of absence. Inspect inherited policy, regional availability, -and quota before executing the approved plan. - -Build and validate using the sensitive parameter **file path**, not inline passwords: - -```sh -az bicep build --file infra/rehearsal.bicep --outfile "$RUN_DIR/template.json" - -az deployment sub validate \ - --name "$DEPLOYMENT_NAME" --location eastus \ - --subscription "$SUBSCRIPTION_ID" \ - --template-file "$RUN_DIR/template.json" \ - --parameters "@$RUN_DIR/parameters.json" - -az deployment sub what-if \ - --name "$DEPLOYMENT_NAME" --location eastus \ - --subscription "$SUBSCRIPTION_ID" \ - --template-file "$RUN_DIR/template.json" \ - --parameters "@$RUN_DIR/parameters.json" -``` - -Review the exact inventory: the fresh group, two named clusters, and only the -supplied single-IP rules. No unrelated modifications or deletions are acceptable. -Use the normal preparation/validation approval process before the actual write: - -```sh -az deployment sub create \ - --name "$DEPLOYMENT_NAME" --location eastus \ - --subscription "$SUBSCRIPTION_ID" \ - --template-file "$RUN_DIR/template.json" \ - --parameters "@$RUN_DIR/parameters.json" \ - --query "{id:id,state:properties.provisioningState,timestamp:properties.timestamp}" \ - --output json > "$RUN_DIR/deployment-result.json" -``` - -Check the real result and both cluster states. A submitted request, an intent -manifest, or a successful what-if is not proof of a usable database. Keep the -receipt in the approved private recovery record. If a write times out, reconcile -the exact IDs before retrying; do not launch duplicate creates. - -Initial public access is **disabled**. Before enabling it, verify ownership and -the exact firewall rules, and re-observe the clients' current IPs. Review a new -what-if with `enablePublicAccess=true`; only then apply that same approved change. -Do not add an Azure-service bypass rule or disable TLS validation. - -Prepare participant-only database credentials and verify isolation using the -service's supported user-management procedure. Do not distribute the administrator -password object or the organizer's Azure session. Native permissions are currently -cluster-wide, so database names alone do not isolate participants. - -## 5. Rehearse the application - -Use the organizer's development app to verify the managed connection before -attendee delivery. Then follow the [lab](lab.md): seed the same catalog, switch -targets without moving favorites, copy selected favorites, retry safely, and -copy a new cloud favorite back. - -Opening a Codespace from the repository does not demonstrate this managed -data-plane journey. Neither the new organizer profile nor this complete procedure -has had a fresh end-to-end live rehearsal yet. - -## Cleanup and shutdown - -Keep the approved execution window and stop path visible. An expiry tag does not -delete Azure resources; an idle/stopped/deleted Codespace can no longer run your -cleanup commands. - -Before deleting each cluster, read its **exact ID from the manifest** and verify -the real resource's subscription, location, and `ato-rehearsal-run` tag: - -```sh -export CLUSTER_ID="" -az resource show --ids "$CLUSTER_ID" --subscription "$SUBSCRIPTION_ID" \ - --api-version 2026-06-01 \ - --query "{id:id,type:type,location:location,run:tags.\"ato-rehearsal-run\"}" \ - --output json -``` - -Only after ownership and cleanup authority are confirmed: - -```sh -az resource delete --ids "$CLUSTER_ID" \ - --subscription "$SUBSCRIPTION_ID" --api-version 2026-06-01 -``` - -Repeat for the other recorded cluster. Wait for authoritative absence of both -IDs; an authentication failure or accepted delete request is not absence. - -Verify the group still belongs to the run and its resource inventory is empty -before deleting that exact group. If unexpected resources are present, stop and -escalate rather than deleting them. - -```sh -az resource list --resource-group "$RESOURCE_GROUP" \ - --subscription "$SUBSCRIPTION_ID" --output table - -# Run only after the ownership and empty-inventory checks above. -az group delete --name "$RESOURCE_GROUP" \ - --subscription "$SUBSCRIPTION_ID" --yes -``` - -Verify group absence. Remove the temporary parameter file only after cleanup is -confirmed; retain the non-secret ownership/cleanup record as required. Deleting -deployment history alone does not delete the resources. - -Export any work you need before stopping/deleting the Codespace. Do not report -success while resources or cleanup status remain unresolved. - -## References - -- [Azure CLI sign-in](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively) -- [Deploy Bicep with Azure CLI](https://learn.microsoft.com/azure/azure-resource-manager/bicep/deploy-cli) -- [Azure CLI dev-container feature](https://github.com/devcontainers/features/tree/main/src/azure-cli) -- [DocumentDB native-user limitations](https://learn.microsoft.com/azure/documentdb/limitations#native-documentdb-secondary-users) +# Organizer preparation: subscription-free attendees + +The default workshop uses two independent local OSS DocumentDB instances in each +attendee's Codespace. **Do not provision an Azure cluster per attendee.** Attendees +need no Azure subscription, cloud database credentials, Azure CLI, or Kubernetes. +The presenter uses one existing, authorized Azure instance for an optional capstone. + +## Before the event + +1. Confirm GitHub/Codespaces account access, available usage, machine capacity, + conference connectivity, storage retention and the pairing/follow-along plan. +2. Measure a fresh **ATO 2026 - Attendee** Codespace with both database services. + A previous warm single-database rehearsal is not a two-site cold-start result. +3. Rehearse TODOs/reference recovery, app restart persistence, both copy directions, + duplicate-safe retry, second-site failure/recovery and a real calendar-app import. +4. Follow the [presenter runbook](presenter.md) on the actual presenter laptop, + with a dedicated approved database on the existing Azure resource. Rehearse + network/TLS access and record a working round trip as the backup. +5. Time the [105-minute instructor plan](instructor.md); shorten the index/migration + extension first. Preserve return-trip, export and safe stopping time. + +## Credentials and environment boundaries + +Default setup generates separate Site A/B credentials and preserves the existing +Site A volume. It only appends missing Site B fields to an old `.env`; partial +credentials require manual review. The attendee Compose file excludes cloud values, +even if legacy settings remain in `.env`, and starts at Site A. + +The optional **ATO 2026 - Organizer** dev-container configuration retains Azure +CLI/Bicep for separately approved operations. Both configurations start the +attendee simulation only. Selecting Organizer installs tools; it neither signs +in nor grants access, and is unnecessary for the existing-instance presenter path. +Do not share an authenticated organizer Codespace or Azure login cache. + +Never distribute a shared cluster's administrator credentials. Database names +alone are not an attendee isolation boundary under cluster-wide native roles. +Avoid this classroom risk altogether: students keep their own self-hosted sites, +and the presenter keeps the managed credentials private. + +## Stop and retain work safely + +Students export calendars and preserve code before stopping Codespaces. Stopping +compute may not end storage charges. Deletion/retention expiry removes both local +notebooks; changing a Compose project name selects different volumes rather than +migrating data. Never prune volumes or replace `.env` as generic troubleshooting. + +The existing Azure resource has its own owner and approved cleanup policy. +Stopping a Codespace/local app does not stop cloud billing or delete Azure data. +Only clean up the dedicated demo data/access when authorized; never delete the +shared cluster or resource group as workshop cleanup. + +## Optional legacy provisioning + +The old two-cluster Bicep templates and private input helper remain available for +separately approved infrastructure rehearsals. They are **not required by this +workshop**, do not model classroom-wide capacity, and confer no deployment authority. +If a future run explicitly needs new resources, use the +[legacy provisioning runbook](legacy-azure-provisioning.md), including ownership +records, validation, narrow network controls and verified cleanup. Do not run it +merely to deliver the current attendee lab or existing-instance presenter demo. + +## Evidence and remaining acceptance + +Automated tests cover configuration/scenario separation, legacy `.env` preservation, +catalog ownership, bounded two-site startup, and real two-server data flows in CI. +They do not replace fresh Codespaces, conference network, live Azure, calendar-app, +or timed-classroom rehearsal. Record those results only after executing them. +See the [delivery plan](../.azure/deployment-plan.md). diff --git a/docs/presenter.md b/docs/presenter.md new file mode 100644 index 0000000..fb6984c --- /dev/null +++ b/docs/presenter.md @@ -0,0 +1,165 @@ +# Presenter-only: actual laptop to managed Azure + +This optional 15-minute capstone uses **one existing, authorized Azure DocumentDB +instance**. It does not provision a cluster, create cloud subscriptions, install +Kubernetes, or grant permissions. Attendees never receive the connection string +and do not execute this runbook. Their Site A/B lab works independently. + +**Acceptance status:** the repository's earlier managed data-plane round trip +was not completed. Rehearse this revised path on the actual laptop and approved +Azure endpoint; local tests and successful infrastructure deployment are not proof. +Keep a verified recording for conference-network failure. Do not claim a live +cloud result from a recording or the two-container simulation. + +## 1. Approve the scope and prepare privately + +- Confirm the existing cluster, dedicated demo database name, data-plane user, + permitted writes, network clients, timeframe and cleanup owner. +- Never seed into a shared application database. Use a fresh approved demo + database to make “no favorites yet” true; don't erase existing favorites. +- Use the service's approved connection URI with validated TLS. Keep it in your + private `.env`, never in source code, terminal history, chat, screenshots, or + slides. No administrator credential distribution or Azure login sharing. +- Verify DNS/SRV, current laptop egress IP and the existing approved firewall + route. An old IP entry may be stale. Follow the resource owner's access process; + do not open the whole internet or disable TLS to make the demonstration work. +- Azure usage/retention policies still apply to an existing resource. Stopping the + local app does not stop charges or delete anything in Azure. + +For a genuine laptop/cloud demonstration, use Docker already working **on your +laptop** and the [local appendix](local.md). A Codespace is not on-prem: if you use +one, clearly describe self-hosted-to-managed portability instead of hybrid on-prem. + +Prefer a separate presenter checkout/Compose project from your attendee notebook, +so rehearsal does not mix personal favorites. A new project gets new local volumes; +it does not migrate an existing notebook. Record the project name and keep using it. +Do not switch names as a recovery shortcut. + +## 2. Prepare local databases, then opt in to the presenter scenario + +In the presenter checkout, generate private local credentials (no host Node needed): + +```sh +docker compose -f compose.setup.yaml run --rm setup +``` + +Edit `.env` privately: + +```dotenv +WORKSHOP_LOCATION=laptop +ACTIVE_TARGET=local +CLOUD_DOCUMENTDB_URI= +CLOUD_DATABASE_NAME= +``` + +Do not put those placeholders into a real runnable configuration. Do not change +`DOCUMENTDB_PASSWORD` for an existing local volume: `.env` editing is not password +rotation. Setup adds missing Site B settings without replacing the old notebook. + +Start the complete reference with the explicit presenter override: + +```sh +docker compose -f compose.yaml -f compose.presenter.yaml -f compose.complete.yaml up --build -d --wait --wait-timeout 240 +``` + +This changes the app's target pair to **local / cloud**. Site B is not in the UI; +the unused local Site B container may still be running because the shared Compose +stack preserves the attendee environment. It does not copy or synchronize anything. +The app starts at `ACTIVE_TARGET` (keep `local` for the rehearsal). + +Opening presenter mode does not seed Azure. The app normally touches Azure only +when you explicitly switch/copy or run a target-specific command. Keep +`ACTIVE_TARGET=local` to avoid cloud health checks on app startup. + +Wait for and seed the local catalog: + +```sh +docker compose -f compose.yaml -f compose.presenter.yaml -f compose.complete.yaml exec app npm run wait:database -- --target local +docker compose -f compose.yaml -f compose.presenter.yaml -f compose.complete.yaml exec app npm run seed -- --target local +``` + +After verifying the URI/database are the approved target, explicitly seed **the +catalog only** into Azure: + +```sh +docker compose -f compose.yaml -f compose.presenter.yaml -f compose.complete.yaml exec app npm run seed -- --target cloud +docker compose -f compose.yaml -f compose.presenter.yaml -f compose.complete.yaml exec app npm run check -- --target cloud +``` + +Expect the same catalog and **zero favorites in a fresh demo database**. A catalog +mismatch is a stop-and-review condition, not permission to delete or overwrite. +If you reuse a previously demonstrated database, favorites will still be there; +choose a new approved database for the missing-favorites lesson. + +Open **http://localhost:3000** (or the privately configured `WORKSHOP_PORT`). +Verify **Complete reference**, **DocumentDB on this laptop**, and exactly the +local/Azure target pair. Do not show `.env` or raw connection errors on screen. + +## 3. Rehearse the 15-minute story + +1. **0–2 min: identify the boundary.** Laptop runs app + self-hosted DocumentDB; + the other target is managed Azure. Same MongoDB-driver repository methods. +2. **2–5 min: switch without moving data.** Save two local favorites. Switch to + **Azure DocumentDB (presenter)**: same catalog, no copied favorites. Ask where + the originals are; switch back and show them intact. +3. **5–9 min: copy explicitly.** With laptop target active, select favorites and + confirm laptop → Azure. Switch to verify. **Switch back to laptop before + repeating the same copy direction**: expect Already present. +4. **9–12 min: bring one back.** Save a new favorite in Azure. Select it and confirm + Azure → laptop. Switch back: original choices survive and the new one is added. +5. **12–15 min: explain and return to attendees.** Application compatibility does + not move data. This app copies selected records; it is not streaming replication, + sync, conflict resolution, failover or proof of every MongoDB feature. Let + attendees finish their own calendar export. + +If any cloud operation fails, show the active-target label and sanitized error, +then move to the checked recording. Do not debug firewall rules or credentials +on the projector. Recordings must demonstrate the actual topology and be labeled +as recordings. The hands-on Site A/B lesson remains complete. + +## 4. Configuration changes and switching modes + +After editing cloud fields, **recreate**, not merely restart, the presenter app: + +```sh +docker compose -f compose.yaml -f compose.presenter.yaml -f compose.complete.yaml up -d --wait --wait-timeout 240 app +``` + +Refresh the browser for the new request token. To demonstrate completed attendee +exercise code rather than the reference, omit `-f compose.complete.yaml` while +retaining `-f compose.presenter.yaml`. + +To return to the complete-reference **Site A / Site B simulation**: + +```sh +docker compose -f compose.yaml -f compose.complete.yaml up -d --wait --wait-timeout 240 app +docker compose -f compose.yaml exec app npm run wait:database -- --target site-b +docker compose -f compose.yaml exec app npm run seed -- --target site-b +``` + +Or run `npm run workspace:start` from an environment with Node installed: it +selects attendee mode explicitly and seeds both sites. Default attendee Compose +does not pass cloud settings into the app. Neither mode switch moves favorites. + +## 5. Shutdown and data ownership + +Export the intended notebook first. Stop only this local Compose project: + +```sh +docker compose -f compose.yaml -f compose.presenter.yaml -f compose.complete.yaml stop +``` + +Keep local volumes and private configuration for rehearsal continuity. Do not use +volume deletion or `.env` replacement as normal stopping. Revoke demo access or +remove the dedicated demo database only under the resource owner's approved +policy. **Do not delete the existing shared Azure cluster/resource group.** +No cloud deletion command is included here; this runbook does not create resources. + +## Optional Kubernetes follow-up + +The [DocumentDB operator](https://github.com/documentdb/documentdb-kubernetes-operator) +has local Kubernetes and AKS/EKS/GKE deployment paths, plus multi-cloud replication +and promotion documentation. This is a separate operations demonstration with +its own version, networking, storage, permissions and failure-mode rehearsal. +It does not remove cloud-account costs or establish automatic replication between +OSS DocumentDB and managed Azure DocumentDB. Keep it off this workshop's critical path. diff --git a/package.json b/package.json index 5bea5b7..a328f0c 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "check": "node scripts/database.mjs check", "import:schedule": "node scripts/import-schedule.mjs", "test": "node --test test/*.test.js", - "test:database": "node --test test/database.integration.js" + "test:database": "node --test test/database.integration.js", + "wait:database": "node scripts/database.mjs wait" }, "dependencies": { "mongodb": "7.1.0" diff --git a/scripts/database.mjs b/scripts/database.mjs index 471803f..31707f5 100644 --- a/scripts/database.mjs +++ b/scripts/database.mjs @@ -1,3 +1,4 @@ +import { setTimeout as delay } from "node:timers/promises"; import { readConfig } from "../src/config.js"; import { createConnections } from "../src/connections.js"; import { readCatalog, requireCatalog, seedCatalog } from "../src/catalog.js"; @@ -5,13 +6,26 @@ import { WorkshopError, reportError } from "../src/errors.js"; async function run() { const [operation, flag, target, ...extra] = process.argv.slice(2); - if (!["seed", "indexes", "migrate", "check"].includes(operation) || - flag !== "--target" || !["local", "cloud"].includes(target) || extra.length) { - throw new WorkshopError(400, "USAGE", "Use: npm run -- --target . The target is always explicit."); + if (!["wait", "seed", "indexes", "migrate", "check"].includes(operation) || + flag !== "--target" || !["local", "site-b", "cloud"].includes(target) || extra.length) { + throw new WorkshopError(400, "USAGE", "Use: npm run -- --target . The target is always explicit."); } const connections = createConnections(readConfig()); try { const db = connections.db(target); + if (operation === "wait") { + const deadline = Date.now() + 240000; + for (;;) { + try { + await db.command({ ping: 1 }); + console.log(JSON.stringify({ target, ready: true })); + return; + } catch (error) { + if (Date.now() >= deadline) throw error; + await delay(2000); + } + } + } await db.command({ ping: 1 }); if (operation === "seed") { const result = await seedCatalog(db, await readCatalog()); diff --git a/scripts/setup.mjs b/scripts/setup.mjs index c52a4c5..3b6422e 100644 --- a/scripts/setup.mjs +++ b/scripts/setup.mjs @@ -1,40 +1,75 @@ import { randomBytes } from "node:crypto"; import { open, stat, chown } from "node:fs/promises"; import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; -const directory = process.env.SETUP_DIRECTORY || process.cwd(); -const filename = resolve(directory, ".env"); -const content = [ - "DOCUMENTDB_USERNAME=workshop", - `DOCUMENTDB_PASSWORD=${randomBytes(24).toString("hex")}`, - "WORKSHOP_MODE=starter", - `WORKSHOP_LOCATION=${process.env.CODESPACES === "true" ? "codespaces" : "laptop"}`, - `WORKSHOP_PUBLIC_HOST=${process.env.CODESPACES === "true" && process.env.CODESPACE_NAME ? `${process.env.CODESPACE_NAME}-3000.${process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN || "app.github.dev"}` : ""}`, - "WORKSHOP_PORT=3000", - "ACTIVE_TARGET=local", - "LOCAL_DATABASE_NAME=ato_workshop", - "CLOUD_DOCUMENTDB_URI=", - "CLOUD_DATABASE_NAME=", - "", -].join("\n"); - -try { - const file = await open(filename, "wx", 0o600); +export async function setup(directory = process.env.SETUP_DIRECTORY || process.cwd(), env = process.env, log = console.log) { + const filename = resolve(directory, ".env"); + const siteB = { + SITE_B_USERNAME: "workshop_site_b", + SITE_B_PASSWORD: randomBytes(24).toString("hex"), + SITE_B_DATABASE_NAME: "ato_workshop", + }; + const content = [ + "DOCUMENTDB_USERNAME=workshop", + `DOCUMENTDB_PASSWORD=${randomBytes(24).toString("hex")}`, + ...Object.entries(siteB).map(([key, value]) => `${key}=${value}`), + "WORKSHOP_MODE=starter", + `WORKSHOP_LOCATION=${env.CODESPACES === "true" ? "codespaces" : "laptop"}`, + `WORKSHOP_PUBLIC_HOST=${env.CODESPACES === "true" && env.CODESPACE_NAME ? `${env.CODESPACE_NAME}-3000.${env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN || "app.github.dev"}` : ""}`, + "WORKSHOP_PORT=3000", + "ACTIVE_TARGET=local", + "LOCAL_DATABASE_NAME=ato_workshop", + "CLOUD_DOCUMENTDB_URI=", + "CLOUD_DATABASE_NAME=", + "", + ].join("\n"); + let created = false; try { - await file.writeFile(content); - } finally { - await file.close(); + const file = await open(filename, "wx", 0o600); + try { await file.writeFile(content); } finally { await file.close(); } + created = true; + } catch (error) { + if (error.code !== "EEXIST") throw error; + // Append only absent Site B keys; never rewrite comments, old values or secrets. + // Empty/partial credentials may describe an existing volume: refuse to guess. + const file = await open(filename, "r+"); + try { + const info = await file.stat(); + if (!info.isFile()) throw new Error("The existing .env must be a regular file."); + const previous = await file.readFile("utf8"); + const keys = new Map(); + for (const line of previous.split(/\r?\n/)) { + const match = line.match(/^\s*(?:export\s+)?(SITE_B_[A-Z_]+)\s*=(.*)$/); + if (!match) continue; + if (keys.has(match[1])) throw new Error("Duplicate Site B settings require manual review; .env was not changed."); + keys.set(match[1], match[2].trim()); + } + const username = keys.has("SITE_B_USERNAME"); + const password = keys.has("SITE_B_PASSWORD"); + if (username !== password || [...keys.values()].some((value) => !value || value === '""' || value === "''")) { + throw new Error("Partial or empty Site B settings require manual review; .env was not changed. Never regenerate credentials for an existing volume."); + } + const additions = Object.entries(siteB).filter(([key]) => !keys.has(key)); + if (additions.length) { + const suffix = `${previous.endsWith("\n") ? "" : "\n"}# Independent Site B; existing configuration above is preserved.\n${additions.map(([key, value]) => `${key}=${value}`).join("\n")}\n`; + await file.write(suffix, info.size, "utf8"); + log("Added missing Site B settings to the existing .env; all previous values and credentials were preserved."); + } else { + log("Kept the existing .env unchanged."); + } + } finally { await file.close(); } } - if (process.getuid?.() === 0) { + if (created && process.getuid?.() === 0) { const owner = await stat(directory); await chown(filename, owner.uid, owner.gid); } - console.log("Created private development-database configuration. No managed Azure target is configured."); -} catch (error) { - if (error.code === "EEXIST") { - console.log("Kept the existing .env unchanged. To change environments, edit it deliberately."); - } else { - console.error(`Local setup failed (${error.code || error.name}). Check directory access; no credentials were printed.`); + if (created) log("Created private, independent Site A and Site B credentials. No Azure target is enabled for attendees."); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + setup().catch((error) => { + console.error(`Local setup failed: ${error.code || error.message}. No credentials were printed.`); process.exitCode = 1; - } + }); } diff --git a/scripts/workspace-start.mjs b/scripts/workspace-start.mjs index 3ad814c..7389456 100644 --- a/scripts/workspace-start.mjs +++ b/scripts/workspace-start.mjs @@ -1,9 +1,13 @@ import { spawnSync } from "node:child_process"; +import { setup } from "./setup.mjs"; import { pathToFileURL } from "node:url"; export const workspaceSteps = [ - ["compose", "up", "--build", "-d", "--wait", "--wait-timeout", "240"], - ["compose", "exec", "-T", "app", "npm", "run", "seed", "--", "--target", "local"], + ["compose", "-f", "compose.yaml", "up", "--build", "-d", "--wait", "--wait-timeout", "240"], + ["compose", "-f", "compose.yaml", "exec", "-T", "app", "npm", "run", "wait:database", "--", "--target", "local"], + ["compose", "-f", "compose.yaml", "exec", "-T", "app", "npm", "run", "wait:database", "--", "--target", "site-b"], + ["compose", "-f", "compose.yaml", "exec", "-T", "app", "npm", "run", "seed", "--", "--target", "local"], + ["compose", "-f", "compose.yaml", "exec", "-T", "app", "npm", "run", "seed", "--", "--target", "site-b"], ]; export function startWorkspace(run = spawnSync, log = console.log) { @@ -12,12 +16,13 @@ export function startWorkspace(run = spawnSync, log = console.log) { if (result.error) throw new Error(`Workspace startup could not run Docker (${result.error.code || result.error.name}).`); if (result.status !== 0) throw new Error(`Workspace startup stopped at docker ${args.join(" ")} (exit ${result.status ?? "interrupted"}).`); } - log("Development database is ready and the catalog is seeded. Open private port 3000 from the Ports tab."); - log("The starter's TODO prompt is intentional. No Azure sign-in or cloud provisioning was performed."); + log("Site A and Site B are ready and both catalogs are seeded. Open private port 3000 from the Ports tab."); + log("The starter's TODO prompt is intentional. Both sites are local simulations; no Azure connection, sign-in or provisioning was performed."); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { try { + await setup(); startWorkspace(); } catch (error) { console.error(error.message); diff --git a/src/catalog.js b/src/catalog.js index 54908ab..d15d6a4 100644 --- a/src/catalog.js +++ b/src/catalog.js @@ -92,10 +92,10 @@ export async function readCatalog() { export async function requireCatalog(db) { const catalog = await db.collection("workshop_meta").findOne({ _id: "catalog" }); - if (!catalog) { + if (!catalog || catalog.ready === false) { throw new WorkshopError(409, "CATALOG_NOT_SEEDED", "The selected database has no session catalog. Run the explicit seed command for this target."); } - const { _id, ...metadata } = catalog; + const { _id, ready, ...metadata } = catalog; return metadata; } @@ -104,19 +104,34 @@ export async function seedCatalog(db, catalog) { if (metadata && metadata.fingerprint !== catalog.fingerprint) { throw new WorkshopError(409, "CATALOG_MISMATCH", "This database has a different catalog. Review the schedule change instead of overwriting it with seed."); } - for (const session of catalog.sessions) { - const { id, ...fields } = session; + // Reject an interrupted legacy seed before claiming this database's catalog. + // This also detects drift instead of silently hiding old-fingerprint documents. + const incompatible = await db.collection("sessions").findOne({ catalogVersion: { $ne: catalog.fingerprint } }); + if (incompatible) { + throw new WorkshopError(409, "CATALOG_MISMATCH", "Existing sessions belong to another catalog, possibly from an interrupted seed. Preserve this database and choose a fresh database name or review a migration."); + } + const { sessions, ...fields } = catalog; + // Claim ownership BEFORE rows: concurrent or interrupted seeds cannot mix catalogs. + await db.collection("workshop_meta").updateOne( + { _id: "catalog" }, + { $setOnInsert: { ...fields, ready: false } }, + { upsert: true }, + ); + const owner = await db.collection("workshop_meta").findOne({ _id: "catalog" }); + if (owner.fingerprint !== catalog.fingerprint) { + throw new WorkshopError(409, "CATALOG_MISMATCH", "Another seed claimed a different catalog. No session rows were changed by this seed."); + } + for (const session of sessions) { + const { id, ...document } = session; await db.collection("sessions").updateOne( { _id: id }, - { $setOnInsert: { ...fields, catalogVersion: catalog.fingerprint, schemaVersion: 1 } }, + { $setOnInsert: { ...document, catalogVersion: catalog.fingerprint, schemaVersion: 1 } }, { upsert: true }, ); } - const { sessions, ...fields } = catalog; await db.collection("workshop_meta").updateOne( - { _id: "catalog" }, - { $setOnInsert: fields }, - { upsert: true }, + { _id: "catalog", fingerprint: catalog.fingerprint }, + { $set: { ready: true } }, ); return { sessions: sessions.length, kind: catalog.kind, version: catalog.version }; } diff --git a/src/config.js b/src/config.js index 0452946..01593da 100644 --- a/src/config.js +++ b/src/config.js @@ -1,3 +1,4 @@ +import { MongoClient } from "mongodb"; import { WorkshopError } from "./errors.js"; function configurationError(message) { @@ -12,83 +13,89 @@ function databaseName(value, label) { } export function validateCloudUri(value) { - let uri; - try { - uri = new URL(value); - } catch { + // WHATWG URL cannot parse valid MongoDB multi-host connection strings. + if (typeof value !== "string" || !/^mongodb(?:\+srv)?:\/\//.test(value) || value.includes("#")) { throw configurationError("CLOUD_DOCUMENTDB_URI must be a valid MongoDB connection URI."); } - if (!["mongodb:", "mongodb+srv:"].includes(uri.protocol) || !uri.hostname || uri.hash) { - throw configurationError("CLOUD_DOCUMENTDB_URI must use mongodb:// or mongodb+srv://."); - } - for (const [key, value] of uri.searchParams) { + // Check every option, including duplicates, before driver normalization. + for (const [key, optionValue] of new URLSearchParams(value.split("?").slice(1).join("?"))) { const option = key.toLowerCase(); if ( ["tlsinsecure", "tlsallowinvalidcertificates", "tlsallowinvalidhostnames"].includes(option) || - (["tls", "ssl"].includes(option) && value.toLowerCase() !== "true") + (["tls", "ssl"].includes(option) && optionValue.toLowerCase() !== "true") ) { throw configurationError("The cloud target must validate TLS certificates and hostnames. Remove insecure TLS options."); } } + try { + // Construction validates without opening a socket or resolving SRV records. + new MongoClient(value, { tls: true }); + } catch { + throw configurationError("CLOUD_DOCUMENTDB_URI must be a valid MongoDB connection URI."); + } return value; } +function developmentTarget(env, siteB = false) { + const prefix = siteB ? "SITE_B" : "DOCUMENTDB"; + const host = siteB ? (env.SITE_B_DOCUMENTDB_HOST || "documentdb-site-b") : (env.LOCAL_DOCUMENTDB_HOST || "documentdb"); + const allowedHosts = siteB ? ["documentdb-site-b", "localhost", "127.0.0.1"] : ["documentdb", "localhost", "127.0.0.1"]; + if (!allowedHosts.includes(host)) { + throw configurationError("A development database must use its local Compose service or loopback. Use presenter mode for remote databases."); + } + const username = env[`${prefix}_USERNAME`]; + const password = env[`${prefix}_PASSWORD`]; + if (!username || !password) throw configurationError(`${siteB ? "Site B" : "Site A"} credentials are missing. Run the setup command.`); + return { + uri: `mongodb://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:10260/?authMechanism=SCRAM-SHA-256&authSource=admin&directConnection=true`, + database: databaseName(siteB ? (env.SITE_B_DATABASE_NAME || "ato_workshop") : (env.LOCAL_DATABASE_NAME || "ato_workshop"), siteB ? "SITE_B_DATABASE_NAME" : "LOCAL_DATABASE_NAME"), + developmentCertificate: true, + }; +} + export function readConfig(env = process.env) { const mode = env.WORKSHOP_MODE || "complete"; + const scenario = env.WORKSHOP_SCENARIO || "attendee"; const location = env.WORKSHOP_LOCATION || "laptop"; const activeTarget = env.ACTIVE_TARGET || "local"; - if (!["starter", "complete"].includes(mode)) { - throw configurationError("WORKSHOP_MODE must be starter or complete."); - } - if (!["laptop", "codespaces"].includes(location)) { - throw configurationError("WORKSHOP_LOCATION must be laptop or codespaces."); - } - if (!["local", "cloud"].includes(activeTarget)) { - throw configurationError("ACTIVE_TARGET must be local or cloud."); - } - const localHost = env.LOCAL_DOCUMENTDB_HOST || "documentdb"; - if (!["documentdb", "localhost", "127.0.0.1"].includes(localHost)) { - throw configurationError("The development database must use the local documentdb service or loopback. Use the cloud target for remote databases."); - } - if (!env.DOCUMENTDB_USERNAME || !env.DOCUMENTDB_PASSWORD) { - throw configurationError("Local credentials are missing. Run the setup command before starting the app."); - } + if (!["starter", "complete"].includes(mode)) throw configurationError("WORKSHOP_MODE must be starter or complete."); + if (!["attendee", "presenter"].includes(scenario)) throw configurationError("WORKSHOP_SCENARIO must be attendee or presenter."); + if (!["laptop", "codespaces"].includes(location)) throw configurationError("WORKSHOP_LOCATION must be laptop or codespaces."); + if (!["local", "site-b", "cloud"].includes(activeTarget)) throw configurationError("ACTIVE_TARGET must be local, site-b, or cloud."); const port = Number(env.PORT || 3000); - if (!Number.isInteger(port) || port < 1 || port > 65535) { - throw configurationError("PORT must be an integer from 1 through 65535."); - } + if (!Number.isInteger(port) || port < 1 || port > 65535) throw configurationError("PORT must be an integer from 1 through 65535."); const publicHost = env.WORKSHOP_PUBLIC_HOST?.trim().toLowerCase() || ""; if (publicHost && !/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(publicHost)) { throw configurationError("WORKSHOP_PUBLIC_HOST must be one exact hostname, without a scheme, port, or wildcard."); } - const localUri = `mongodb://${encodeURIComponent(env.DOCUMENTDB_USERNAME)}:${encodeURIComponent(env.DOCUMENTDB_PASSWORD)}@${localHost}:10260/?authMechanism=SCRAM-SHA-256&authSource=admin&directConnection=true`; - const cloudUri = env.CLOUD_DOCUMENTDB_URI?.trim(); - const targets = { - local: { - uri: localUri, - database: databaseName(env.LOCAL_DATABASE_NAME || "ato_workshop", "LOCAL_DATABASE_NAME"), - developmentCertificate: true, - }, - }; - if (cloudUri) { - targets.cloud = { - uri: validateCloudUri(cloudUri), - database: databaseName(env.CLOUD_DATABASE_NAME, "CLOUD_DATABASE_NAME"), - developmentCertificate: false, - }; - } else if (env.CLOUD_DATABASE_NAME) { - throw configurationError("CLOUD_DATABASE_NAME is set but CLOUD_DOCUMENTDB_URI is missing."); - } - if (!targets[activeTarget]) { - throw configurationError("The requested initial database target is not configured."); + const targets = { local: developmentTarget(env) }; + if (scenario === "attendee") { + targets["site-b"] = developmentTarget(env, true); + if (env.SITE_B_PASSWORD === env.DOCUMENTDB_PASSWORD) throw configurationError("Site A and Site B must use independently generated passwords. Do not rotate an existing volume's credentials by editing .env."); + const hostA = env.LOCAL_DOCUMENTDB_HOST || "documentdb"; + const hostB = env.SITE_B_DOCUMENTDB_HOST || "documentdb-site-b"; + if (hostA === hostB || (["localhost", "127.0.0.1"].includes(hostA) && ["localhost", "127.0.0.1"].includes(hostB))) { + throw configurationError("Site A and Site B must be separate database endpoints, not two databases on one endpoint."); + } + // Cloud settings in a legacy .env are deliberately ignored in attendee mode. + } else { + const cloudUri = env.CLOUD_DOCUMENTDB_URI?.trim(); + if (cloudUri) { + targets.cloud = { + uri: validateCloudUri(cloudUri), + database: databaseName(env.CLOUD_DATABASE_NAME, "CLOUD_DATABASE_NAME"), + developmentCertificate: false, + }; + } else if (env.CLOUD_DATABASE_NAME) { + throw configurationError("CLOUD_DATABASE_NAME is set but CLOUD_DOCUMENTDB_URI is missing."); + } } - return { mode, location, activeTarget, port, host: env.HOST || "127.0.0.1", publicHost, targets }; + if (!Object.hasOwn(targets, activeTarget)) throw configurationError("The requested initial database target is not configured for this scenario."); + return { mode, scenario, location, activeTarget, port, host: env.HOST || "127.0.0.1", publicHost, targets }; } -export function targetLabel(target, location) { - return target === "cloud" - ? "Azure DocumentDB" - : location === "codespaces" - ? "Development database in Codespaces" - : "DocumentDB on this laptop"; +export function targetLabel(target, location, scenario = "attendee") { + if (target === "cloud") return "Azure DocumentDB (presenter)"; + if (scenario === "attendee") return target === "site-b" ? "Site B — self-hosted" : "Site A — self-hosted"; + return location === "codespaces" ? "Development database in Codespaces" : "DocumentDB on this laptop"; } diff --git a/src/connections.js b/src/connections.js index a584707..ed475e1 100644 --- a/src/connections.js +++ b/src/connections.js @@ -6,7 +6,7 @@ export function createConnections(config) { return { db(target) { if (!Object.hasOwn(config.targets, target)) { - throw new WorkshopError(409, "TARGET_NOT_CONFIGURED", "This target is not configured. An organizer must supply approved sandbox access first."); + throw new WorkshopError(409, "TARGET_NOT_CONFIGURED", "This target is not configured. Select a target configured for this workshop scenario."); } if (!clients.has(target)) { const settings = config.targets[target]; diff --git a/src/public/index.html b/src/public/index.html index b7a1972..c8fa9a6 100644 --- a/src/public/index.html +++ b/src/public/index.html @@ -145,7 +145,7 @@

Build your conference day.

-

Pick the sessions you want to attend. Keep your favorites, spot overlaps, and discover what really moves between your development database and managed Azure DocumentDB.

+

Pick the sessions you want to attend. Keep your favorites, spot overlaps, and discover why switching database connections does not move your data.

@@ -200,7 +200,7 @@

Your favorites

Copy, don't synchronize

Select favorites above to copy to the other database. Existing choices are kept; removals are not propagated.

- Cloud access has not been configured. + Checking the other database target.
    @@ -208,7 +208,7 @@

    Copy, don't synchronize

    Loading the catalog's source and snapshot date.

    -

    Restarting the app restores the target from ACTIVE_TARGET. A connection switch does not copy data.

    +

    Restarting the attendee app returns to Site A. A connection switch does not copy data.

    Official conference schedule / DocumentDB project

    @@ -245,8 +245,8 @@

    Confirm selected favorites

    if (className) element.className = className; return element; }; - const label = (target) => config.targets.find((item) => item.id === target)?.label || "Cloud (not configured)"; - const destination = () => config.target === "local" ? "cloud" : "local"; + const label = (target) => config.targets.find((item) => item.id === target)?.label || "Other target (not configured)"; + const destination = () => config.targets.find((item) => item.id !== config.target)?.id; const dayKey = (session) => new Intl.DateTimeFormat("en-CA", { timeZone: state.catalog.timeZone, year: "numeric", month: "2-digit", day: "2-digit", }).format(new Date(session.startsAt)); @@ -308,7 +308,7 @@

    Confirm selected favorites

    $("target-name").textContent = label(config.target); $("mode").textContent = `${config.mode === "starter" ? "TODO starter" : "Complete reference"} / Same application data layer`; $("target-select").replaceChildren(); - for (const target of ["local", "cloud"]) { + for (const { id: target } of config.targets) { const option = node("option", label(target)); option.value = target; option.disabled = !config.targets.some((item) => item.id === target); @@ -317,10 +317,10 @@

    Confirm selected favorites

    } $("copy-help").textContent = config.targets.some((target) => target.id === destination()) ? `Destination: ${label(destination())}. Select up to 100 favorites.` - : "Managed Azure access is not configured. Development planning and calendar export still work."; - notice("location-notice", config.location === "codespaces" - ? "Codespaces development environment: Docker and DocumentDB run here, not on your laptop. You only need a browser and connectivity. Azure DocumentDB is a separate managed target." - : ""); + : "The presenter cloud target is not configured. Local planning and calendar export still work."; + notice("location-notice", config.scenario === "attendee" + ? `Two independent self-hosted databases ${config.location === "codespaces" ? "inside this Codespace, not on your laptop" : "on this laptop"}. Site A / Site B simulate two sites; this is not live hybrid cloud, replication or automatic failover. No Azure account is needed.` + : `Presenter demonstration: ${config.location === "codespaces" ? "the development database is in Codespaces, not on-premises" : "the development database is on this laptop"}. Azure is a separate managed database; copying favorites is an explicit application operation, not replication.`); } function render() { diff --git a/src/server.js b/src/server.js index a5b628d..83610f3 100644 --- a/src/server.js +++ b/src/server.js @@ -39,8 +39,9 @@ export async function createApp({ config, connections, repository, logger = cons target: activeTarget, initialTarget: config.activeTarget, mode: config.mode, + scenario: config.scenario || "attendee", location: config.location, - targets: Object.keys(config.targets).map((id) => ({ id, label: targetLabel(id, config.location) })), + targets: Object.keys(config.targets).map((id) => ({ id, label: targetLabel(id, config.location, config.scenario) })), csrfToken, }); function assertTarget(target) { @@ -116,8 +117,8 @@ export async function createApp({ config, connections, repository, logger = cons const data = await readJson(request); assertTarget(data.target); if (request.method === "POST" && url.pathname === "/api/target") { - if (!["local", "cloud"].includes(data.nextTarget)) { - throw new WorkshopError(400, "INVALID_TARGET", "Choose the development or cloud target."); + if (!["local", "site-b", "cloud"].includes(data.nextTarget)) { + throw new WorkshopError(400, "INVALID_TARGET", "Choose one of the configured database targets."); } await connections.db(data.nextTarget).command({ ping: 1 }); assertTarget(data.target); @@ -138,7 +139,7 @@ export async function createApp({ config, connections, repository, logger = cons return; } if (request.method === "POST" && url.pathname === "/api/transfer") { - if (data.source !== target || !["local", "cloud"].includes(data.destination) || data.source === data.destination) { + if (data.source !== target || !["local", "site-b", "cloud"].includes(data.destination) || data.source === data.destination) { throw new WorkshopError(400, "INVALID_TRANSFER", "Copy from the active target to the other configured target."); } const result = await copyFavorites(connections.db(data.source), connections.db(data.destination), data.sessionIds); diff --git a/test/database.integration.js b/test/database.integration.js index 9690c1c..d95e219 100644 --- a/test/database.integration.js +++ b/test/database.integration.js @@ -12,19 +12,31 @@ import { createApp } from "../src/server.js"; import { WorkshopError } from "../src/errors.js"; import { readPracticeCatalog } from "./fixtures/catalog.js"; -test("real local DocumentDB: independent data, retry-safe round trip, partial outcomes, migration, API", async (t) => { +test("two real independent DocumentDB servers: independent data, retry-safe round trip, partial outcomes, migration, API", async (t) => { const runId = randomUUID().replaceAll("-", ""); const localEnv = { ...process.env, ACTIVE_TARGET: "local", + WORKSHOP_SCENARIO: "attendee", CLOUD_DOCUMENTDB_URI: "", CLOUD_DATABASE_NAME: "", }; const config = readConfig({ ...localEnv, LOCAL_DATABASE_NAME: `verify_source_${runId}` }); const sourceConnections = createConnections(config); - const destinationConnections = createConnections(readConfig({ ...localEnv, LOCAL_DATABASE_NAME: `verify_destination_${runId}` })); + const destinationConnections = createConnections(readConfig({ ...localEnv, SITE_B_DATABASE_NAME: `verify_destination_${runId}` })); const source = sourceConnections.db("local"); - const destination = destinationConnections.db("local"); + const destination = destinationConnections.db("site-b"); + assert.notEqual(config.targets.local.uri.split("@")[1], config.targets["site-b"].uri.split("@")[1], "integration requires two distinct server endpoints"); + // Site A's credentials must not authenticate to Site B (or vice versa). + for (const [from, to] of [["local", "site-b"], ["site-b", "local"]]) { + const foreign = createConnections({ targets: { local: { + ...config.targets[from], + uri: `${config.targets[from].uri.split("@")[0]}@${config.targets[to].uri.split("@")[1]}`, + } } }); + try { + await assert.rejects(foreign.db("local").command({ ping: 1 }), { code: 18 }); + } finally { await foreign.close(); } + } let sourceOwned = false; let destinationOwned = false; t.after(async () => { @@ -48,6 +60,7 @@ test("real local DocumentDB: independent data, retry-safe round trip, partial ou const ids = catalog.sessions.map((session) => session.id); await repository.saveFavorite(source, ids[0]); await repository.saveFavorite(source, ids[1]); + const originalSavedAt = (await source.collection("favorites").findOne({ _id: ids[0] })).savedAt; await repository.saveFavorite(destination, ids[2]); await seedCatalog(source, catalog); assert.equal((await readPlanner(source, repository)).favorites.length, 2); @@ -74,6 +87,7 @@ test("real local DocumentDB: independent data, retry-safe round trip, partial ou assert.equal(retry.complete, true); assert.deepEqual(retry.results.map((item) => item.status), ["already_present", "copied"]); const repeated = await copyFavorites(source, destination, [ids[0], ids[1]]); + assert.equal((await destination.collection("favorites").findOne({ _id: ids[0] })).savedAt, originalSavedAt); assert.ok(repeated.results.every((item) => item.status === "already_present")); await copyFavorites(destination, source, [ids[2]]); assert.deepEqual(new Set((await readPlanner(source, repository)).favorites), new Set(ids.slice(0, 3))); @@ -104,7 +118,11 @@ test("real local DocumentDB: independent data, retry-safe round trip, partial ou const app = await createApp({ config: { ...config, mode: "complete" }, - connections: { db: () => source, close: async () => {} }, + connections: { db: (target) => { + if (target === "local") return source; + if (target === "site-b") return destination; + throw new WorkshopError(409, "TARGET_NOT_CONFIGURED", "No cloud access in this test."); + }, close: async () => {} }, repository, logger: { error() {} }, }); @@ -126,6 +144,23 @@ test("real local DocumentDB: independent data, retry-safe round trip, partial ou }); assert.equal(saved.status, 200); assert.equal((await saved.json()).status, "saved"); + const post = (path, body) => fetch(`${origin}/api/${path}`, { + method: "POST", + headers: { "Content-Type": "application/json", "X-Workshop-Token": details.csrfToken }, + body: JSON.stringify(body), + }); + assert.equal((await post("target", { target: "local", nextTarget: "cloud" })).status, 409); + assert.equal((await post("target", { target: "local", nextTarget: "site-b" })).status, 200); + const siteBState = await (await fetch(`${origin}/api/state`)).json(); + assert.equal(siteBState.target, "site-b"); + assert.equal(siteBState.favorites.includes(ids[3]), false, "switching must not copy"); + assert.equal((await post("target", { target: "local", nextTarget: "site-b" })).status, 409, "stale requests fail closed"); + assert.equal((await post("target", { target: "site-b", nextTarget: "local" })).status, 200); + const copied = await post("transfer", { target: "local", source: "local", destination: "site-b", sessionIds: [ids[3]] }); + assert.equal(copied.status, 200); + assert.equal((await copied.json()).results[0].status, "copied"); + await source.collection("favorites").deleteOne({ _id: ids[3] }); + assert.ok(await destination.collection("favorites").findOne({ _id: ids[3] }), "removal is not synchronized"); } finally { await app.close(); } diff --git a/test/domain.test.js b/test/domain.test.js index 36aa619..810981b 100644 --- a/test/domain.test.js +++ b/test/domain.test.js @@ -11,7 +11,7 @@ import { WorkshopError, publicError, reportError } from "../src/errors.js"; import { validateSelection } from "../src/transfer.js"; import * as starter from "../exercises/starter/repository.js"; -const localEnv = { DOCUMENTDB_USERNAME: "test-user", DOCUMENTDB_PASSWORD: "test-only", LOCAL_DOCUMENTDB_HOST: "localhost" }; +const localEnv = { DOCUMENTDB_USERNAME: "test-user", DOCUMENTDB_PASSWORD: "test-only", LOCAL_DOCUMENTDB_HOST: "localhost", SITE_B_USERNAME: "site-b-user", SITE_B_PASSWORD: "site-b-only" }; test("the practice catalog is explicit, stable, and independent of input ordering", async () => { const catalog = await readPracticeCatalog(); @@ -69,14 +69,14 @@ test("calendar folding counts UTF-8 octets, including the continuation space", ( assert.equal(escapeCalendarText("a\r\nb,c;d\\e"), "a\\nb\\,c\\;d\\\\e"); }); -test("only the local development target permits a development certificate", () => { - const config = readConfig({ ...localEnv, CLOUD_DOCUMENTDB_URI: "mongodb+srv://cluster.example.invalid/", CLOUD_DATABASE_NAME: "test_workshop" }); +test("only fixed local development targets permit a development certificate", () => { + const config = readConfig({ ...localEnv, WORKSHOP_SCENARIO: "presenter", CLOUD_DOCUMENTDB_URI: "mongodb+srv://cluster.example.invalid/", CLOUD_DATABASE_NAME: "test_workshop" }); assert.equal(config.targets.local.developmentCertificate, true); assert.equal(config.targets.cloud.developmentCertificate, false); assert.equal(config.activeTarget, "local"); assert.throws(() => readConfig({ ...localEnv, LOCAL_DOCUMENTDB_HOST: "remote.example.invalid" }), /development database/); assert.throws(() => readConfig({ ...localEnv, ACTIVE_TARGET: "cloud" }), /not configured/); - assert.throws(() => readConfig({ ...localEnv, CLOUD_DOCUMENTDB_URI: "mongodb+srv://cluster.example.invalid/" }), /explicit database name/); + assert.throws(() => readConfig({ ...localEnv, WORKSHOP_SCENARIO: "presenter", CLOUD_DOCUMENTDB_URI: "mongodb+srv://cluster.example.invalid/" }), /explicit database name/); assert.throws(() => readConfig({ ...localEnv, WORKSHOP_MODE: "typo" }), /WORKSHOP_MODE/); assert.throws(() => readConfig({ ...localEnv, WORKSHOP_PUBLIC_HOST: "*.example.invalid" }), /exact hostname/); }); diff --git a/test/http.test.js b/test/http.test.js index f31bfd1..2395839 100644 --- a/test/http.test.js +++ b/test/http.test.js @@ -47,3 +47,48 @@ test("HTTP target changes are explicit; errors are sanitized and writes require assert.deepEqual(calls, ["local", "cloud"]); assert.equal((await fetch(`${origin}/missing`)).status, 404); }); + +test("unavailable Site B does not switch the active target or fall back after a successful switch", async (t) => { + let unavailable = true; + const calls = []; + const config = { activeTarget: "local", mode: "complete", scenario: "attendee", location: "codespaces", targets: { local: {}, "site-b": {} } }; + const app = await createApp({ + config, repository: {}, logger: { error() {} }, + connections: { + db(target) { + calls.push(target); + return { async command() { + if (target === "site-b" && unavailable) { + const error = new Error("synthetic private endpoint details"); + error.name = "MongoServerSelectionError"; + throw error; + } + return { ok: 1 }; + } }; + }, + async close() {}, + }, + }); + await new Promise((resolve) => app.server.listen(0, "127.0.0.1", resolve)); + t.after(() => app.close()); + const origin = `http://127.0.0.1:${app.server.address().port}`; + const configResponse = () => fetch(`${origin}/api/config`).then((response) => response.json()); + const details = await configResponse(); + assert.equal(details.scenario, "attendee"); + assert.deepEqual(details.targets.map((item) => item.label), ["Site A — self-hosted", "Site B — self-hosted"]); + const switchToB = () => fetch(`${origin}/api/target`, { + method: "POST", headers: { "Content-Type": "application/json", "X-Workshop-Token": details.csrfToken }, + body: JSON.stringify({ target: "local", nextTarget: "site-b" }), + }); + const failure = await switchToB(); + assert.equal(failure.status, 503); + assert.doesNotMatch(await failure.text(), /synthetic|private endpoint/); + assert.equal((await configResponse()).target, "local"); + unavailable = false; + assert.equal((await switchToB()).status, 200); + assert.equal((await configResponse()).target, "site-b"); + unavailable = true; + assert.equal((await fetch(`${origin}/api/health`)).status, 503); + assert.equal((await configResponse()).target, "site-b"); + assert.deepEqual(calls, ["site-b", "site-b", "site-b"]); +}); diff --git a/test/two-site.test.js b/test/two-site.test.js new file mode 100644 index 0000000..c413959 --- /dev/null +++ b/test/two-site.test.js @@ -0,0 +1,145 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, writeFile, stat, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setup } from "../scripts/setup.mjs"; +import { readConfig, validateCloudUri, targetLabel } from "../src/config.js"; +import { seedCatalog, requireCatalog, validateCatalog } from "../src/catalog.js"; +import { readPracticeCatalog } from "./fixtures/catalog.js"; +import { startWorkspace, workspaceSteps } from "../scripts/workspace-start.mjs"; + +const env = { DOCUMENTDB_USERNAME: "a", DOCUMENTDB_PASSWORD: "a-test-only", SITE_B_USERNAME: "b", SITE_B_PASSWORD: "b-test-only" }; + +test("attendees get exactly two independent sites and ignore even invalid legacy cloud settings", () => { + const config = readConfig({ ...env, CLOUD_DOCUMENTDB_URI: "not a uri", CLOUD_DATABASE_NAME: "invalid/name" }); + assert.equal(config.scenario, "attendee"); + assert.deepEqual(Object.keys(config.targets), ["local", "site-b"]); + assert.notEqual(config.targets.local.uri, config.targets["site-b"].uri); + assert.equal(config.targets["site-b"].developmentCertificate, true); + assert.match(targetLabel("local", "codespaces"), /Site A/); + assert.match(targetLabel("site-b", "codespaces"), /Site B/); + assert.throws(() => readConfig({ ...env, SITE_B_PASSWORD: env.DOCUMENTDB_PASSWORD }), /independently/); + assert.throws(() => readConfig({ ...env, SITE_B_DOCUMENTDB_HOST: "outside.example.invalid" }), /development database/); + assert.throws(() => readConfig({ ...env, LOCAL_DOCUMENTDB_HOST: "localhost", SITE_B_DOCUMENTDB_HOST: "127.0.0.1" }), /separate database endpoints/); + assert.throws(() => readConfig({ ...env, WORKSHOP_SCENARIO: "typo" }), /WORKSHOP_SCENARIO/); + assert.throws(() => readConfig({ ...env, ACTIVE_TARGET: "cloud", CLOUD_DOCUMENTDB_URI: "mongodb://example.invalid" }), /not configured/); +}); + +test("presenter mode is explicit, excludes Site B, and validates cloud TLS with multi-host URIs", () => { + const uri = "mongodb://host-a.example.invalid:27017,host-b.example.invalid:27017/?tls=true"; + assert.equal(validateCloudUri(uri), uri); + const config = readConfig({ ...env, SITE_B_PASSWORD: "", WORKSHOP_SCENARIO: "presenter", CLOUD_DOCUMENTDB_URI: uri, CLOUD_DATABASE_NAME: "approved_demo" }); + assert.deepEqual(Object.keys(config.targets), ["local", "cloud"]); + assert.equal(config.targets.cloud.developmentCertificate, false); + assert.match(targetLabel("local", "laptop", "presenter"), /laptop/); + assert.match(targetLabel("cloud", "laptop", "presenter"), /Azure/); + assert.throws(() => readConfig({ ...env, WORKSHOP_SCENARIO: "presenter", ACTIVE_TARGET: "site-b" }), /not configured/); + for (const suffix of ["&tls=false", "&tlsAllowInvalidCertificates=true", "&tLsInsecure=false", "&ssl=false"]) { + assert.throws(() => validateCloudUri(uri + suffix), /TLS/); + } +}); + +test("setup creates distinct credentials, preserves .env bytes, and safely extends a legacy notebook", async (t) => { + const directory = await mkdtemp(join(tmpdir(), "ato-setup-")); + t.after(() => rm(directory, { recursive: true })); + const messages = []; + await setup(directory, {}, (message) => messages.push(message)); + const filename = join(directory, ".env"); + const content = await readFile(filename, "utf8"); + const values = Object.fromEntries(content.trim().split("\n").map((line) => line.split("="))); + assert.notEqual(values.DOCUMENTDB_PASSWORD, values.SITE_B_PASSWORD); + if (process.platform !== "win32") assert.equal((await stat(filename)).mode & 0o077, 0); + await setup(directory, {}, () => {}); + assert.equal(await readFile(filename, "utf8"), content); + const legacy = '# Keep my notebook\r\nDOCUMENTDB_USERNAME=old\r\nDOCUMENTDB_PASSWORD=preserve-me\r\nLOCAL_DATABASE_NAME=my_favorites\r\nCLOUD_DOCUMENTDB_URI="legacy-secret"'; + await writeFile(filename, legacy); + await setup(directory, {}, (message) => messages.push(message)); + const extended = await readFile(filename, "utf8"); + assert.ok(extended.startsWith(legacy + "\n")); + assert.match(extended, /SITE_B_USERNAME=workshop_site_b/); + assert.match(extended, /SITE_B_PASSWORD=[0-9a-f]{48}/); + await setup(directory, {}, () => {}); + assert.equal(await readFile(filename, "utf8"), extended); + assert.doesNotMatch(messages.join("\n"), /preserve-me|legacy-secret|[0-9a-f]{48}/); + for (const partial of ["SITE_B_USERNAME=already_exists\n", "SITE_B_USERNAME=b\nSITE_B_PASSWORD=\n", "SITE_B_USERNAME=b\nSITE_B_PASSWORD=p\nSITE_B_PASSWORD=p2\n"]) { + await writeFile(filename, partial); + await assert.rejects(setup(directory, {}, () => {}), /manual review/); + assert.equal(await readFile(filename, "utf8"), partial); + } +}); + +test("any second-site readiness or seed failure stops startup without reporting success", () => { + for (let failing = 1; failing < workspaceSteps.length; failing++) { + let count = 0; + const logs = []; + assert.throws(() => startWorkspace(() => ({ status: count++ === failing ? 1 : 0 }), (line) => logs.push(line)), /startup stopped/); + assert.equal(count, failing + 1); + assert.deepEqual(logs, []); + } +}); + +function fakeDatabase() { + const data = { sessions: new Map(), workshop_meta: new Map() }; + let writes = 0; + let failAt = Infinity; + const matches = (document, filter) => Object.entries(filter).every(([key, value]) => + value && typeof value === "object" && "$ne" in value ? document[key] !== value.$ne : document[key] === value); + return { + data, + interruptAfter(count) { failAt = writes + count; }, + resume() { failAt = Infinity; }, + collection(name) { + const rows = data[name]; + return { + async findOne(filter) { return [...rows.values()].find((document) => matches(document, filter)) || null; }, + async updateOne(filter, update, options = {}) { + if (name === "sessions" && ++writes > failAt) throw new Error("simulated interruption"); + const row = [...rows.values()].find((document) => matches(document, filter)); + if (row) Object.assign(row, update.$set || {}); + else if (options.upsert) rows.set(filter._id, { ...filter, ...structuredClone(update.$setOnInsert || {}), ...update.$set }); + return { upsertedCount: !row && options.upsert ? 1 : 0 }; + }, + }; + }, + }; +} + +test("interrupted first seed claims its catalog and resumes without exposing partial readiness", async () => { + const db = fakeDatabase(); + const catalog = await readPracticeCatalog(); + db.interruptAfter(1); + await assert.rejects(seedCatalog(db, catalog), /interruption/); + await assert.rejects(requireCatalog(db), { code: "CATALOG_NOT_SEEDED" }); + const revised = validateCatalog({ ...catalog, sessions: catalog.sessions.map((session) => ({ ...session, room: "changed" })) }); + await assert.rejects(seedCatalog(db, revised), { code: "CATALOG_MISMATCH" }); + db.resume(); + await seedCatalog(db, catalog); + assert.equal((await requireCatalog(db)).fingerprint, catalog.fingerprint); + assert.equal(db.data.sessions.size, catalog.sessions.length); + assert.ok([...db.data.sessions.values()].every((row) => row.catalogVersion === catalog.fingerprint)); + await seedCatalog(db, catalog); + assert.equal(db.data.sessions.size, catalog.sessions.length); +}); + +test("legacy interrupted seed rows without metadata reject a changed catalog instead of hiding data", async () => { + const db = fakeDatabase(); + const catalog = await readPracticeCatalog(); + db.data.sessions.set("legacy-session", { _id: "legacy-session", catalogVersion: "old-fingerprint" }); + await assert.rejects(seedCatalog(db, catalog), { code: "CATALOG_MISMATCH" }); + assert.equal(db.data.workshop_meta.size, 0); + assert.equal(db.data.sessions.size, 1); +}); + +test("Compose default never passes Azure settings and keeps the old Site A volume", async () => { + const compose = await readFile(new URL("../compose.yaml", import.meta.url), "utf8"); + const presenter = await readFile(new URL("../compose.presenter.yaml", import.meta.url), "utf8"); + assert.match(compose, /documentdb-data:\/data/); + assert.match(compose, /documentdb-site-b-data:\/data/); + assert.match(compose, /WORKSHOP_SCENARIO: attendee/); + assert.match(compose, /CLOUD_DOCUMENTDB_URI: ""/); + assert.match(compose, /ACTIVE_TARGET: local/); + assert.doesNotMatch(compose, /\$\{CLOUD_/); + assert.match(presenter, /WORKSHOP_SCENARIO: presenter/); + assert.match(presenter, /\$\{CLOUD_DOCUMENTDB_URI:-\}/); +}); diff --git a/test/workspace.test.js b/test/workspace.test.js index e80bbaa..8fc4db6 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -39,7 +39,7 @@ test("attendee and organizer configurations share startup, not Azure authenticat } }); -test("workspace startup waits for readiness and seeds only the development target", () => { +test("workspace startup waits for both independent sites and never seeds Azure", () => { const calls = []; const messages = []; startWorkspace((program, args, options) => { @@ -49,6 +49,9 @@ test("workspace startup waits for readiness and seeds only the development targe assert.deepEqual(calls.map((call) => call.args), workspaceSteps); assert.ok(calls.every((call) => call.program === "docker" && call.timeout === 600000)); assert.deepEqual(calls[1].args.slice(-2), ["--target", "local"]); + assert.deepEqual(calls[2].args.slice(-2), ["--target", "site-b"]); + assert.deepEqual(calls.slice(3).map((call) => call.args.slice(-2)), [["--target", "local"], ["--target", "site-b"]]); + assert.ok(calls.every((call) => !call.args.includes("cloud") && call.args.includes("compose.yaml"))); assert.match(messages[0], /ready.*seeded/); }); From c35921a83f80ac778db0cb70d0c1177fbb9cf600 Mon Sep 17 00:00:00 2001 From: Patty Chow <91703531+patty-chow@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:30:49 -0700 Subject: [PATCH 2/2] Address live-test and review findings before workshop delivery --- Dockerfile | 2 +- README.md | 3 ++- docs/lab.md | 3 ++- docs/legacy-azure-provisioning.md | 12 ++++++++---- test/database.integration.js | 4 +++- test/two-site.test.js | 7 +++++++ 6 files changed, 23 insertions(+), 8 deletions(-) diff --git a/Dockerfile b/Dockerfile index ae4f4c3..76f882c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ FROM node:24.13.0-bookworm-slim@sha256:4660b1ca8b28d6d1906fd644abe34b2ed81d15434d26d845ef0aced307cf4b6f WORKDIR /app ARG NPM_REGISTRY=https://registry.npmjs.org/ -COPY package.json package-lock.json .npmrc ./ +COPY --chown=node:node package.json package-lock.json .npmrc ./ RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund --registry="$NPM_REGISTRY" COPY --chown=node:node src ./src COPY --chown=node:node scripts ./scripts diff --git a/README.md b/README.md index 215b175..d92bf34 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,8 @@ MongoDB feature parity or identical operational behavior. - `workshop_meta`: catalog ownership/readiness and practice/official metadata. - Switching connections does not seed, copy, replace, or delete favorites. - Explicit copying inserts only missing selected favorites; retries do not create - duplicates or overwrite their initial timestamps. + duplicates or overwrite their initial timestamps at the destination. Each site + records its own first-save time; copying does not transplant the source timestamp. - Per-record results distinguish copied, already present, invalid, failed, and unattempted. Partial success is not a transaction rollback. - Removals do not synchronize; this is not replication, general conflict diff --git a/docs/lab.md b/docs/lab.md index 84f1c1a..2150adb 100644 --- a/docs/lab.md +++ b/docs/lab.md @@ -121,7 +121,8 @@ Read the confirmation instead of assuming the destination. Partial results are per record: copied, already present, invalid, failed, or unattempted. A failed batch is not automatically rolled back. Resolve the cause -and retry safely; initial save timestamps and existing choices are preserved. +and retry safely; each destination's initial save timestamps and existing choices +are preserved. Each site records its own first-save time, not the other site's. ## 6. Bring one back diff --git a/docs/legacy-azure-provisioning.md b/docs/legacy-azure-provisioning.md index 3ff4b99..ff28aef 100644 --- a/docs/legacy-azure-provisioning.md +++ b/docs/legacy-azure-provisioning.md @@ -170,10 +170,14 @@ cluster-wide, so database names alone do not isolate participants. ## 5. Rehearse the application -Use the organizer's development app to verify the managed connection before -attendee delivery. Then follow the [lab](lab.md): seed the same catalog, switch -targets without moving favorites, copy selected favorites, retry safely, and -copy a new cloud favorite back. +Use the explicit presenter scenario in the [presenter runbook](presenter.md) +to verify the managed connection: seed the same catalog, switch targets without +moving favorites, copy selected favorites, retry safely, and copy a new cloud +favorite back. The attendee lab now uses only Site A/B and does not enable Azure. +If rehearsing from Codespaces, describe self-hosted-to-managed portability, not a +physical-laptop/on-prem topology. These newly provisioned rehearsal resources still +follow this legacy runbook's ownership-checked cleanup, not the existing-resource +retention instructions in the presenter guide. Opening a Codespace from the repository does not demonstrate this managed data-plane journey. Neither the new organizer profile nor this complete procedure diff --git a/test/database.integration.js b/test/database.integration.js index d95e219..d8700a4 100644 --- a/test/database.integration.js +++ b/test/database.integration.js @@ -83,11 +83,13 @@ test("two real independent DocumentDB servers: independent data, retry-safe roun const partial = await copyFavorites(source, partialDestination, [ids[0], ids[1], ids[3]]); assert.equal(partial.complete, false); assert.deepEqual(partial.results.map((item) => item.status), ["copied", "failed", "invalid"]); + const destinationSavedAt = (await destination.collection("favorites").findOne({ _id: ids[0] })).savedAt; const retry = await copyFavorites(source, destination, [ids[0], ids[1]]); assert.equal(retry.complete, true); assert.deepEqual(retry.results.map((item) => item.status), ["already_present", "copied"]); const repeated = await copyFavorites(source, destination, [ids[0], ids[1]]); - assert.equal((await destination.collection("favorites").findOne({ _id: ids[0] })).savedAt, originalSavedAt); + assert.equal((await destination.collection("favorites").findOne({ _id: ids[0] })).savedAt, destinationSavedAt); + assert.equal((await source.collection("favorites").findOne({ _id: ids[0] })).savedAt, originalSavedAt); assert.ok(repeated.results.every((item) => item.status === "already_present")); await copyFavorites(destination, source, [ids[2]]); assert.deepEqual(new Set((await readPlanner(source, repository)).favorites), new Set(ids.slice(0, 3))); diff --git a/test/two-site.test.js b/test/two-site.test.js index c413959..681ebdb 100644 --- a/test/two-site.test.js +++ b/test/two-site.test.js @@ -143,3 +143,10 @@ test("Compose default never passes Azure settings and keeps the old Site A volum assert.match(presenter, /WORKSHOP_SCENARIO: presenter/); assert.match(presenter, /\$\{CLOUD_DOCUMENTDB_URI:-\}/); }); + + +test("container package metadata stays readable by the non-root runtime with restrictive host modes", async () => { + const dockerfile = await readFile(new URL("../Dockerfile", import.meta.url), "utf8"); + assert.match(dockerfile, /COPY --chown=node:node package\.json package-lock\.json \.npmrc \.\//); + assert.match(dockerfile, /USER node/); +});