diff --git a/.github/workflows/build-medusa.yaml b/.github/workflows/build-medusa.yaml deleted file mode 100644 index cea9e772..00000000 --- a/.github/workflows/build-medusa.yaml +++ /dev/null @@ -1,38 +0,0 @@ -name: Build Medusa Kubero image - -on: - workflow_dispatch: - push: - branches: [main] - paths: - - 'services/medusa/**' - - '.github/workflows/build-medusa.yaml' - -permissions: - contents: read - packages: write - -jobs: - build: - runs-on: [self-hosted, Linux, X64] - steps: - - uses: actions/checkout@v4 - - - name: Log in to GHCR - uses: docker/login-action@v3 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Build and push - uses: docker/build-push-action@v6 - with: - context: services/medusa - push: true - tags: | - ghcr.io/stackblaze/stack-templates/medusa:2.21.0 - ghcr.io/stackblaze/stack-templates/medusa:latest diff --git a/index.json b/index.json index ad66e547..b2c1c44e 100644 --- a/index.json +++ b/index.json @@ -13683,9 +13683,9 @@ "name": "Medusa Commerce", "description": "Build custom shopping experiences with modular commerce APIs, product management, carts, and checkout.\nA developer-first alternative to Shopify Plus and commercetools.", "source": "https://github.com/medusajs/medusa", - "icon": "https://avatars.githubusercontent.com/u/62591822?s=200&v=4", + "icon": "https://raw.githubusercontent.com/stackblaze/stack-templates/main/services/medusa/icon.png", "website": "https://medusajs.com", - "installation": "Deploys the Medusa 2 backend and admin (at /app) with PostgreSQL and Valkey add-ons. First boot runs migrations and creates the admin user from MEDUSA_ADMIN_EMAIL / MEDUSA_ADMIN_PASSWORD (default admin@example.com / changeme \u2014 rotate immediately). JWT_SECRET and COOKIE_SECRET are generated per deploy. After login, create a publishable API key under Settings > API Key Management if you attach a Next.js storefront (official starter: github.com/medusajs/dtc-starter apps/storefront) and set STORE_CORS to that storefront URL. Product images persist on the uploads volume.", + "installation": "Builds on deploy: StackBlaze publishes no Medusa image. Your project builds the Medusa 2.22.7 server from upstream's starter (medusajs/dtc-starter, pinned commit) with the Dockerfile in this template's folder (stackblaze/stack-templates, services/medusa/image), so the first deploy takes about 8 minutes (about 6 for the build). Changing a variable rebuilds the image too: about 6 minutes on a cold build node, about 1 minute warm; restarts and scaling reuse the built image. Deploys the Medusa 2 server with its admin dashboard (the app URL opens /app), the Store API, Postgres and Valkey. The first start runs the migrations, seeds upstream's starter store (a Europe region, a warehouse, shipping options, four sample products and a publishable API key) and creates the admin user before the app is reachable. Sign in with admin@example.com (MEDUSA_ADMIN_EMAIL) and the generated password in MEDUSA_ADMIN_PASSWORD (Variables). To use your own address, invite it under Settings > Users (copy the invite link), accept it, then delete the first user. There is no storefront in this template: build one from upstream's starter (github.com/medusajs/dtc-starter, apps/storefront) with the publishable key from Settings > Publishable API Keys, and add its URL to STORE_CORS and AUTH_CORS. Product images upload to the data volume and are served from /static. Medusa sends no email on its own: password resets and invites need a notification module in your own build. Licence: Medusa is MIT except its Enterprise materials (RBAC roles, SSO/OIDC), which ship inside Medusa's npm packages: your build fetches them from npm, and they stay inert without a Medusa licence key. The template runs without them.", "architecture": [], "categories": [ "e-commerce", @@ -13693,24 +13693,26 @@ "work" ], "screenshots": [ - "https://medusajs.com/images/og.jpg" + "https://raw.githubusercontent.com/stackblaze/stack-templates/main/services/medusa/screenshot-orders.png", + "https://raw.githubusercontent.com/stackblaze/stack-templates/main/services/medusa/screenshot-order.png", + "https://raw.githubusercontent.com/stackblaze/stack-templates/main/services/medusa/screenshot-product.png" ], "links": [ "https://docs.medusajs.com/learn/deployment/general", - "https://docs.medusajs.com/" + "https://docs.medusajs.com/", + "https://github.com/medusajs/dtc-starter" ], "addons": [ "Cluster", - "Valkey", - "Smtp" + "Valkey" ], - "stars": 36333, - "forks": 5253, - "watchers": 36333, - "issues": 0, - "last_updated": "2026-09-16T00:00:00Z", - "last_pushed": "2026-09-16T00:00:00Z", - "created_at": "2021-03-08T00:00:00Z", + "stars": 37232, + "forks": 5520, + "watchers": 37232, + "issues": 111, + "last_updated": "2026-11-13T12:27:45Z", + "last_pushed": "2026-11-13T16:02:37Z", + "created_at": "2020-01-18T13:39:04Z", "size": 0, "language": "TypeScript", "gitops": false, diff --git a/scripts/capture-specs/medusa.json b/scripts/capture-specs/medusa.json new file mode 100644 index 00000000..0698425e --- /dev/null +++ b/scripts/capture-specs/medusa.json @@ -0,0 +1,22 @@ +{ + "viewport": { "width": 1920, "height": 1080 }, + "deviceScaleFactor": 2, + "login": { + "path": "/app/login", + "steps": [ + { "waitForSelector": "input[name=email]", "timeout": 60000 }, + { "fill": { "input[name=email]": "${MEDUSA_ADMIN_EMAIL}" } }, + { "fill": { "input[name=password]": "${MEDUSA_ADMIN_PASSWORD}" } }, + { "press": { "selector": "input[name=password]", "key": "Enter" } }, + { "waitForSelector": "tbody tr", "timeout": 30000 } + ], + "waitAfterMs": 2000 + }, + "pages": [ + { "name": "orders", "path": "/app/orders", "waitFor": "tbody tr", "waitMs": 2500 }, + { "name": "order", "path": "/app/orders", "waitFor": "tbody tr", "waitMs": 1500, + "steps": [ { "click": "tbody tr >> nth=0" }, { "sleep": 3000 } ] }, + { "name": "product", "path": "/app/products", "waitFor": "tbody tr", "waitMs": 1500, + "steps": [ { "click": "text=Medusa T-Shirt" }, { "sleep": 3000 } ] } + ] +} diff --git a/services/medusa/.dockerignore b/services/medusa/.dockerignore deleted file mode 100644 index c28f1285..00000000 --- a/services/medusa/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -* -!medusa-config.ts -!kubero-entrypoint.sh diff --git a/services/medusa/Dockerfile b/services/medusa/Dockerfile deleted file mode 100644 index 076e9f94..00000000 --- a/services/medusa/Dockerfile +++ /dev/null @@ -1,38 +0,0 @@ -# Medusa does not publish an official production image. This builds the -# official DTC starter backend (Medusa 2.21) for the catalog template. -FROM node:22-bookworm-slim AS builder - -RUN apt-get update \ - && apt-get install -y --no-install-recommends git python3 make g++ ca-certificates \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /src -RUN git clone --depth 1 https://github.com/medusajs/dtc-starter.git . -COPY medusa-config.ts apps/backend/medusa-config.ts - -RUN corepack enable \ - && corepack prepare pnpm@10.11.1 --activate \ - && pnpm install --frozen-lockfile --filter @dtc/backend... \ - && pnpm --filter @dtc/backend build - -WORKDIR /src/apps/backend/.medusa/server -RUN npm install --omit=dev - -FROM node:22-bookworm-slim - -RUN apt-get update \ - && apt-get install -y --no-install-recommends ca-certificates \ - && rm -rf /var/lib/apt/lists/* \ - && mkdir -p /server/static \ - && chown -R node:node /server - -WORKDIR /server -COPY --from=builder --chown=node:node /src/apps/backend/.medusa/server /server -COPY --chown=node:node kubero-entrypoint.sh /usr/local/bin/kubero-entrypoint.sh -RUN chmod +x /usr/local/bin/kubero-entrypoint.sh - -USER node -ENV NODE_ENV=production -ENV PORT=9000 -EXPOSE 9000 -ENTRYPOINT ["/usr/local/bin/kubero-entrypoint.sh"] diff --git a/services/medusa/app.yaml b/services/medusa/app.yaml index b74ce645..a8019ed4 100644 --- a/services/medusa/app.yaml +++ b/services/medusa/app.yaml @@ -5,20 +5,11 @@ metadata: annotations: kubero.dev/template.architecture: '[]' kubero.dev/template.description: "Build custom shopping experiences with modular commerce APIs, product management, carts, and checkout.\nA developer-first alternative to Shopify Plus and commercetools." - kubero.dev/template.icon: https://avatars.githubusercontent.com/u/62591822?s=200&v=4 + kubero.dev/template.icon: https://raw.githubusercontent.com/stackblaze/stack-templates/main/services/medusa/icon.png kubero.dev/template.homepage: /app - kubero.dev/template.installation: 'Deploys the Medusa 2 backend and admin (at /app) - with PostgreSQL and Valkey add-ons. Open /app — the root URL has no storefront. - First boot runs migrations and creates the admin user from MEDUSA_ADMIN_EMAIL / - MEDUSA_ADMIN_PASSWORD (default admin@example.com / changeme — rotate immediately). - JWT_SECRET and COOKIE_SECRET are generated per deploy. After login, create a - publishable API key under Settings > API Key Management if you attach a Next.js - storefront (official starter: github.com/medusajs/dtc-starter apps/storefront) - and set STORE_CORS to that storefront URL. Product images persist on the uploads - volume.' - kubero.dev/template.links: '["https://docs.medusajs.com/learn/deployment/general", - "https://docs.medusajs.com/"]' - kubero.dev/template.screenshots: '["https://medusajs.com/images/og.jpg"]' + kubero.dev/template.installation: "Builds on deploy: StackBlaze publishes no Medusa image. Your project builds the Medusa 2.22.7 server from upstream's starter (medusajs/dtc-starter, pinned commit) with the Dockerfile in this template's folder (stackblaze/stack-templates, services/medusa/image), so the first deploy takes about 8 minutes (about 6 for the build). Changing a variable rebuilds the image too: about 6 minutes on a cold build node, about 1 minute warm; restarts and scaling reuse the built image. Deploys the Medusa 2 server with its admin dashboard (the app URL opens /app), the Store API, Postgres and Valkey. The first start runs the migrations, seeds upstream's starter store (a Europe region, a warehouse, shipping options, four sample products and a publishable API key) and creates the admin user before the app is reachable. Sign in with admin@example.com (MEDUSA_ADMIN_EMAIL) and the generated password in MEDUSA_ADMIN_PASSWORD (Variables). To use your own address, invite it under Settings > Users (copy the invite link), accept it, then delete the first user. There is no storefront in this template: build one from upstream's starter (github.com/medusajs/dtc-starter, apps/storefront) with the publishable key from Settings > Publishable API Keys, and add its URL to STORE_CORS and AUTH_CORS. Product images upload to the data volume and are served from /static. Medusa sends no email on its own: password resets and invites need a notification module in your own build. Licence: Medusa is MIT except its Enterprise materials (RBAC roles, SSO/OIDC), which ship inside Medusa's npm packages: your build fetches them from npm, and they stay inert without a Medusa licence key. The template runs without them." + kubero.dev/template.links: '["https://docs.medusajs.com/learn/deployment/general", "https://docs.medusajs.com/", "https://github.com/medusajs/dtc-starter"]' + kubero.dev/template.screenshots: '["https://raw.githubusercontent.com/stackblaze/stack-templates/main/services/medusa/screenshot-orders.png", "https://raw.githubusercontent.com/stackblaze/stack-templates/main/services/medusa/screenshot-order.png", "https://raw.githubusercontent.com/stackblaze/stack-templates/main/services/medusa/screenshot-product.png"]' kubero.dev/template.source: https://github.com/medusajs/medusa kubero.dev/template.categories: '["e-commerce", "development", "work"]' kubero.dev/template.title: "Medusa Commerce" @@ -27,7 +18,17 @@ metadata: manager: kubero spec: name: medusa - deploymentstrategy: docker + # Build on deploy (Railway-style): no published image. Each deploy clones + # this repo at the pinned commit and builds services/medusa/image (the + # Dockerfile: upstream's starter at a pinned commit, npm packages fetched + # by the deploying project's own build). `branch` is a commit SHA, so a + # push to this repo never rebuilds anyone's app. + deploymentstrategy: git + buildstrategy: dockerfile + gitrepo: + clone_url: https://github.com/stackblaze/stack-templates.git + branch: c7c0f096d489da9abeafddb4c31a4fd794bf78fd + buildContext: services/medusa/image addons: - displayName: PostgreSQL (CloudNativePG) env: [] @@ -75,7 +76,7 @@ spec: type: kubernetes.io/basic-auth stringData: username: postgres - password: medusa + password: '{{STACKBLAZE_GEN_ALNUM:24}}' appUserSecret: apiVersion: v1 kind: Secret @@ -84,7 +85,11 @@ spec: type: kubernetes.io/basic-auth stringData: username: medusa - password: medusa + password: '{{STACKBLAZE_GEN_ALNUM:24}}' + # Valkey: REDIS_URL is injected. Upstream's production guide replaces the + # in-memory development modules with Redis ones: admin sessions, the event + # bus (subscribers such as the product search index), the workflow engine + # (scheduled jobs, long-running workflows), the cache and locking. - displayName: Valkey env: [] icon: /img/addons/redis.svg @@ -114,42 +119,47 @@ spec: limits: cpu: 500m memory: 256Mi - # Platform email (see README "Email contract"). Medusa notifications are - # module-based; SMTP_* is injected while Email is live for a future - # notification provider / admin mail settings. - - displayName: Email - icon: /img/addons/email.svg - id: kubero-smtp - kind: Smtp - env: [] - resourceDefinitions: {} + cronjobs: [] envVars: - name: NODE_ENV value: production - name: PORT value: '9000' + # No sslmode: Medusa then connects with TLS (rejectUnauthorized false) to a + # non-local host (load-module-database-config.ts). - name: DATABASE_URL - value: 'postgres://$(PGUSER):$(PGPASSWORD)@$(PGHOST):$(PGPORT)/$(PGDATABASE)?sslmode=disable' + value: 'postgres://$(PGUSER):$(PGPASSWORD)@$(PGHOST):$(PGPORT)/$(PGDATABASE)' + # One process serves the API and the admin and runs subscribers and + # scheduled jobs (upstream's "shared" worker mode). - name: MEDUSA_WORKER_MODE value: shared - name: DISABLE_MEDUSA_ADMIN value: 'false' - name: JWT_SECRET - value: '{{STACKBLAZE_GEN_ALNUM:32}}' + value: '{{STACKBLAZE_GEN_ALNUM:48}}' - name: COOKIE_SECRET - value: '{{STACKBLAZE_GEN_ALNUM:32}}' + value: '{{STACKBLAZE_GEN_ALNUM:48}}' + # The app's own URL: public links of uploaded files (/static/…). + - name: MEDUSA_BACKEND_URL + value: '{{STACKBLAZE_APP_URL}}' + # Add your storefront's URL to STORE_CORS and AUTH_CORS (comma-separated). - name: STORE_CORS value: '{{STACKBLAZE_APP_URL}}' - name: ADMIN_CORS value: '{{STACKBLAZE_APP_URL}}' - name: AUTH_CORS value: '{{STACKBLAZE_APP_URL}}' - - name: MEDUSA_BACKEND_URL - value: '{{STACKBLAZE_APP_URL}}' + # The first admin user, created by a one-time migration script on a new + # database (services/medusa/image). Changing these later changes nothing. - name: MEDUSA_ADMIN_EMAIL value: admin@example.com - name: MEDUSA_ADMIN_PASSWORD - value: changeme + value: '{{STACKBLAZE_GEN_ALNUM:24}}' + - name: MEDUSA_DISABLE_TELEMETRY + value: 'true' + # Product images and other uploads (Medusa's local file provider, served at + # /static). Private files (product exports) land here too, as upstream's + # local provider has no private store. extraVolumes: - accessModes: - ReadWriteMany @@ -158,37 +168,31 @@ spec: name: '{{STACKBLAZE_APP_NAME}}-uploads' size: 5Gi storageClass: shared - cronjobs: [] web: replicaCount: 1 worker: replicaCount: 0 resources: requests: - cpu: 500m - memory: 1Gi + cpu: 250m + memory: 768Mi limits: cpu: '2' - memory: 3Gi + memory: 2Gi healthcheck: enabled: true path: /health - startupSeconds: 900 + startupSeconds: 600 timeoutSeconds: 5 periodSeconds: 10 image: containerPort: '9000' pullPolicy: IfNotPresent - # Referenced as ghcr.io on purpose: zone nodes mirror ghcr.io through - # the regional registry (containerd hosts.d -> registry./v2/ghcr, - # the zot in each services cluster, on-demand sync, ghcr.io fallback). - # Anonymous read on the LAN, no pull secret. Pinned tag, not :latest. - repository: ghcr.io/stackblaze/stack-templates/medusa - tag: '2.21.0' + # Set by the build (the project's own registry); nothing to pull before. + repository: '' + tag: '' run: securityContext: + runAsUser: 1000 + runAsGroup: 1000 readOnlyRootFilesystem: false - # Medusa 2 serves admin at /app. Without this, GET / is Express "Cannot GET /". - ingress: - annotations: - nginx.ingress.kubernetes.io/app-root: /app diff --git a/services/medusa/icon.png b/services/medusa/icon.png new file mode 100644 index 00000000..6d179dfb Binary files /dev/null and b/services/medusa/icon.png differ diff --git a/services/medusa/image/.dockerignore b/services/medusa/image/.dockerignore new file mode 100644 index 00000000..46b62623 --- /dev/null +++ b/services/medusa/image/.dockerignore @@ -0,0 +1,7 @@ +* +!Dockerfile +!medusa-config.ts +!docker-entrypoint.sh +!wait-for-services.js +!src/migration-scripts/stackblaze-admin.ts +!src/api/route.ts diff --git a/services/medusa/image/Dockerfile b/services/medusa/image/Dockerfile new file mode 100644 index 00000000..48cb0e58 --- /dev/null +++ b/services/medusa/image/Dockerfile @@ -0,0 +1,66 @@ +# Medusa publishes no runtime image: a Medusa store is a project you build. +# This image is upstream's official starter (medusajs/dtc-starter, backend +# app only) at a pinned commit, built the way upstream's deployment guide +# says (`medusa build`, then `npm install` in .medusa/server), with a +# StackBlaze medusa-config.ts (Valkey modules, local files on the volume) and +# one extra migration script that creates the first admin user, and a +# redirect from / to the admin (/app). +ARG NODE_IMAGE=docker.io/library/node:22.23.5-bookworm-slim + +FROM ${NODE_IMAGE} AS builder + +# medusajs/dtc-starter "chore: update @medusajs/* to v2.22.7 (#103)" +ARG STARTER_SHA=44f2979627d8b9dac3336ee039a99a433f4c3123 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends git python3 make g++ ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /src +RUN git init -q . \ + && git remote add origin https://github.com/medusajs/dtc-starter.git \ + && git fetch -q --depth 1 origin "$STARTER_SHA" \ + && git checkout -q FETCH_HEAD + +COPY medusa-config.ts apps/backend/medusa-config.ts +COPY src/migration-scripts/stackblaze-admin.ts apps/backend/src/migration-scripts/stackblaze-admin.ts +COPY src/api/route.ts apps/backend/src/api/route.ts + +ENV MEDUSA_DISABLE_TELEMETRY=true +RUN corepack enable \ + && corepack prepare pnpm@10.11.1 --activate \ + && pnpm install --frozen-lockfile --filter @dtc/backend... \ + && pnpm --filter @dtc/backend build + +# --force: the starter pins @medusajs/ui 4.2.9 while @medusajs/draft-order +# 2.22.7 asks for 4.2.14 as an optional peer (ERESOLVE). The UI package only +# matters for building the admin, which is already built at this point. +WORKDIR /src/apps/backend/.medusa/server +RUN npm install --omit=dev --no-audit --no-fund --force \ + && npm cache clean --force + +FROM ${NODE_IMAGE} + +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates tini \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir -p /server/static \ + && chown -R node:node /server + +WORKDIR /server +COPY --from=builder --chown=node:node /src/apps/backend/.medusa/server /server +COPY --chown=node:node wait-for-services.js /usr/local/lib/stackblaze/wait-for-services.js +COPY --chown=node:node docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh +RUN chmod +x /usr/local/bin/docker-entrypoint.sh + +USER node +# Telemetry off: MEDUSA_DISABLE_TELEMETRY stops the events; the stored opt-out +# (what `medusa telemetry --disable` writes) also stops the startup banner. +RUN mkdir -p /home/node/.config/medusa \ + && echo '{"telemetry":{"enabled":false}}' > /home/node/.config/medusa/config.json +ENV NODE_ENV=production \ + PORT=9000 \ + MEDUSA_DISABLE_TELEMETRY=true +EXPOSE 9000 +VOLUME ["/server/static"] +ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/docker-entrypoint.sh"] diff --git a/services/medusa/image/docker-entrypoint.sh b/services/medusa/image/docker-entrypoint.sh new file mode 100755 index 00000000..d8b253be --- /dev/null +++ b/services/medusa/image/docker-entrypoint.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# StackBlaze start for Medusa: wait for Postgres (a real login) and Valkey, +# run upstream's predeploy step (migrations, link sync and migration scripts, +# which on a new database include the starter's store seed and the first +# admin user), then start the server. +set -eu +cd /server + +node /usr/local/lib/stackblaze/wait-for-services.js + +echo "[stackblaze] running database migrations" +./node_modules/.bin/medusa db:migrate + +echo "[stackblaze] starting Medusa" +exec ./node_modules/.bin/medusa start diff --git a/services/medusa/image/medusa-config.ts b/services/medusa/image/medusa-config.ts new file mode 100644 index 00000000..f24ab8e7 --- /dev/null +++ b/services/medusa/image/medusa-config.ts @@ -0,0 +1,82 @@ +import { loadEnv, defineConfig } from '@medusajs/framework/utils' + +loadEnv(process.env.NODE_ENV || 'production', process.cwd()) + +// StackBlaze build of upstream's starter config (medusajs/dtc-starter +// apps/backend/medusa-config.ts). Additions, all from upstream's production +// deployment guide and Medusa Cloud's own defaults (defineConfig): +// - Valkey (REDIS_URL) for admin sessions, the event bus, the workflow +// engine, the cache and locking, instead of the in-memory development +// modules. +// - Local files on the mounted volume (/server/static, served at /static), +// with public URLs on the app's own address instead of localhost:9000. +const redisUrl = process.env.REDIS_URL +const backendUrl = (process.env.MEDUSA_BACKEND_URL || 'http://localhost:9000').replace(/\/+$/, '') + +module.exports = defineConfig({ + projectConfig: { + databaseUrl: process.env.DATABASE_URL, + redisUrl, + workerMode: + (process.env.MEDUSA_WORKER_MODE as 'shared' | 'worker' | 'server') || + 'shared', + http: { + storeCors: process.env.STORE_CORS!, + adminCors: process.env.ADMIN_CORS!, + authCors: process.env.AUTH_CORS!, + jwtSecret: process.env.JWT_SECRET, + cookieSecret: process.env.COOKIE_SECRET, + }, + }, + admin: { + // Unset at build time, so the admin calls the API on its own origin. + backendUrl: process.env.MEDUSA_ADMIN_BACKEND_URL, + disable: process.env.DISABLE_MEDUSA_ADMIN === 'true', + }, + modules: [ + { + resolve: '@medusajs/medusa/file', + options: { + providers: [ + { + resolve: '@medusajs/medusa/file-local', + id: 'local', + options: { + upload_dir: 'static', + backend_url: `${backendUrl}/static`, + }, + }, + ], + }, + }, + ...(redisUrl + ? [ + { + resolve: '@medusajs/medusa/event-bus-redis', + options: { redisUrl }, + }, + { + resolve: '@medusajs/medusa/workflow-engine-redis', + options: { redis: { redisUrl } }, + }, + { + resolve: '@medusajs/medusa/cache-redis', + options: { redisUrl }, + }, + { + resolve: '@medusajs/medusa/locking', + options: { + providers: [ + { + resolve: '@medusajs/medusa/locking-redis', + id: 'locking-redis', + is_default: true, + options: { redisUrl }, + }, + ], + }, + }, + ] + : []), + ], +}) diff --git a/services/medusa/image/src/api/route.ts b/services/medusa/image/src/api/route.ts new file mode 100644 index 00000000..70a33364 --- /dev/null +++ b/services/medusa/image/src/api/route.ts @@ -0,0 +1,7 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http' + +// StackBlaze: the app URL opens the admin. Medusa serves nothing at `/` +// (Express "Cannot GET /"), and the admin lives at /app. +export const GET = (_req: MedusaRequest, res: MedusaResponse) => { + res.redirect(302, '/app') +} diff --git a/services/medusa/image/src/migration-scripts/stackblaze-admin.ts b/services/medusa/image/src/migration-scripts/stackblaze-admin.ts new file mode 100644 index 00000000..ad52b36b --- /dev/null +++ b/services/medusa/image/src/migration-scripts/stackblaze-admin.ts @@ -0,0 +1,59 @@ +import { MedusaContainer } from '@medusajs/framework' +import { ContainerRegistrationKeys, Modules } from '@medusajs/framework/utils' + +/** + * StackBlaze: create the first admin user on a new database, so a fresh + * deploy is never open for someone else to claim. Medusa runs each migration + * script once (`medusa db:migrate`, tracked in `script_migrations`), before + * the server starts. Same steps as upstream's `medusa user -e … -p …` CLI + * (packages/medusa/src/commands/user.ts): create the user, register an + * email/password identity, link the two. + * + * Credentials come from MEDUSA_ADMIN_EMAIL and MEDUSA_ADMIN_PASSWORD (a + * generated secret). If any user exists already, nothing is changed. + */ +export default async function stackblazeAdmin({ + container, +}: { + container: MedusaContainer +}) { + const logger = container.resolve(ContainerRegistrationKeys.LOGGER) + const email = process.env.MEDUSA_ADMIN_EMAIL?.trim() + const password = process.env.MEDUSA_ADMIN_PASSWORD + + if (!email || !password) { + logger.warn( + '[stackblaze] MEDUSA_ADMIN_EMAIL / MEDUSA_ADMIN_PASSWORD not set: no admin user created. Create one with `npx medusa user`.' + ) + return + } + + const userService = container.resolve(Modules.USER) + const [, count] = await userService.listAndCountUsers({}, { take: 1 }) + if (count > 0) { + logger.info('[stackblaze] admin user exists already; skipping') + return + } + + const workflowService = container.resolve(Modules.WORKFLOW_ENGINE) + const authService = container.resolve(Modules.AUTH) + + const { result: users } = await workflowService.run('create-users-workflow', { + input: { users: [{ email }] }, + }) + const user = users[0] + + const { authIdentity, error } = await authService.register('emailpass', { + body: { email, password }, + }) + if (error || !authIdentity) { + throw new Error(`[stackblaze] could not register the admin identity: ${error}`) + } + + await authService.updateAuthIdentities({ + id: authIdentity.id, + app_metadata: { user_id: user.id }, + }) + + logger.info(`[stackblaze] admin user ${email} created`) +} diff --git a/services/medusa/image/wait-for-services.js b/services/medusa/image/wait-for-services.js new file mode 100644 index 00000000..ec73f703 --- /dev/null +++ b/services/medusa/image/wait-for-services.js @@ -0,0 +1,64 @@ +// Waits until Postgres accepts a real login (not just an open port) and, when +// REDIS_URL is set, until Valkey answers PING. Add-ons can come up after the +// app pod, and the operator creates the database user some seconds after the +// port opens. Gives up after about 5 minutes so the pod restarts visibly. +const { createRequire } = require('module') +const appRequire = createRequire('/server/package.json') +const { Client } = appRequire('pg') +const Redis = appRequire('ioredis') + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const TRIES = 100 + +async function waitPostgres() { + for (let i = 1; i <= TRIES; i++) { + const client = new Client({ + connectionString: process.env.DATABASE_URL, + ssl: { rejectUnauthorized: false }, + connectionTimeoutMillis: 5000, + }) + try { + await client.connect() + await client.query('select 1') + await client.end() + if (i > 1) console.log('[stackblaze] database ready') + return + } catch (err) { + try { await client.end() } catch (_) {} + console.log(`[stackblaze] waiting for the database (${i}): ${err.code || err.message}`) + await sleep(3000) + } + } + console.log('[stackblaze] database not reachable; stopping') + process.exit(1) +} + +async function waitRedis() { + if (!process.env.REDIS_URL) return + for (let i = 1; i <= TRIES; i++) { + const redis = new Redis(process.env.REDIS_URL, { + lazyConnect: true, + maxRetriesPerRequest: 0, + retryStrategy: () => null, + connectTimeout: 5000, + }) + redis.on('error', () => {}) + try { + await redis.connect() + await redis.ping() + redis.disconnect() + if (i > 1) console.log('[stackblaze] Valkey ready') + return + } catch (err) { + redis.disconnect() + console.log(`[stackblaze] waiting for Valkey (${i}): ${err.code || err.message}`) + await sleep(3000) + } + } + console.log('[stackblaze] Valkey not reachable; stopping') + process.exit(1) +} + +waitPostgres() + .then(waitRedis) + .then(() => process.exit(0)) diff --git a/services/medusa/kubero-entrypoint.sh b/services/medusa/kubero-entrypoint.sh deleted file mode 100755 index 4f86c982..00000000 --- a/services/medusa/kubero-entrypoint.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -set -eu - -cd /server - -echo "Running Medusa database migrations..." -npx medusa db:migrate - -if [ -n "${MEDUSA_ADMIN_EMAIL:-}" ] && [ -n "${MEDUSA_ADMIN_PASSWORD:-}" ]; then - echo "Ensuring admin user ${MEDUSA_ADMIN_EMAIL} exists..." - npx medusa user -e "$MEDUSA_ADMIN_EMAIL" -p "$MEDUSA_ADMIN_PASSWORD" || true -fi - -exec npx medusa start diff --git a/services/medusa/medusa-config.ts b/services/medusa/medusa-config.ts deleted file mode 100644 index 67fe7d40..00000000 --- a/services/medusa/medusa-config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { loadEnv, defineConfig } from '@medusajs/framework/utils' - -loadEnv(process.env.NODE_ENV || 'production', process.cwd()) - -const redisUrl = process.env.REDIS_URL - -module.exports = defineConfig({ - projectConfig: { - databaseUrl: process.env.DATABASE_URL, - redisUrl, - workerMode: - (process.env.MEDUSA_WORKER_MODE as 'shared' | 'worker' | 'server') || - 'shared', - http: { - storeCors: process.env.STORE_CORS!, - adminCors: process.env.ADMIN_CORS!, - authCors: process.env.AUTH_CORS!, - jwtSecret: process.env.JWT_SECRET, - cookieSecret: process.env.COOKIE_SECRET, - }, - }, - admin: { - backendUrl: process.env.MEDUSA_BACKEND_URL, - disable: process.env.DISABLE_MEDUSA_ADMIN === 'true', - }, - modules: redisUrl - ? [ - { - resolve: '@medusajs/medusa/cache-redis', - options: { redisUrl }, - }, - { - resolve: '@medusajs/medusa/event-bus-redis', - options: { redisUrl }, - }, - { - resolve: '@medusajs/medusa/workflow-engine-redis', - options: { redis: { url: redisUrl } }, - }, - ] - : undefined, -}) diff --git a/services/medusa/screenshot-order.png b/services/medusa/screenshot-order.png new file mode 100644 index 00000000..8303c6d0 Binary files /dev/null and b/services/medusa/screenshot-order.png differ diff --git a/services/medusa/screenshot-orders.png b/services/medusa/screenshot-orders.png new file mode 100644 index 00000000..e23e6ff6 Binary files /dev/null and b/services/medusa/screenshot-orders.png differ diff --git a/services/medusa/screenshot-product.png b/services/medusa/screenshot-product.png new file mode 100644 index 00000000..42176e9d Binary files /dev/null and b/services/medusa/screenshot-product.png differ