Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions docs/40-deployment/development-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ URLs in ignored `svc.local.json`; these are host facts, not repository defaults.

## Joint Development Lanes

Run `pnpm dev --core-source ../impl-py` to develop against a specific Python worktree.
Select a Python worktree with the `database` SVC target. The command asks that owner to
converge its database and opens an isolated Chromium session connected to its PostgREST.
It reports the Core worktree, source fingerprint, and migration after the Web App reads
Peer data. Install Chromium once with `pnpm exec playwright install chromium`.
Use `--headless` to verify the connection and close the browser automatically.
Close the browser to end the session. The Python worktree owns its database lifecycle.

`pnpm dev:all` runs the web Host with local Extension remotes. A missing remote output is built in a
separate process before mounting because Module Federation virtual modules are package-local; the
Host Vite process must not absorb a producer build. Producer playgrounds remain isolated lifecycle
Expand Down Expand Up @@ -163,15 +171,23 @@ and point the Docker CLI at the same daemon.
For a pushed candidate, dispatch **App checks** on the TypeScript ref and supply the full
`impl-py` commit as `core_revision`. The source acceptance job runs the same command.

To reuse an existing candidate, set `INKCRE_CORE_IMAGE` to its published digest or its full
local image ID (`sha256:…`) and run `pnpm test:e2e:web` or `pnpm test:e2e:webext`.
An initial worktree run prints the path to its Core receipt before launching Playwright.
For another run on that Docker daemon, pass the same receipt to the browser or type
generation command:

```sh
pnpm test:e2e:core --core-receipt ./core-receipt.json webext
pnpm contract:check --core-receipt ./core-receipt.json
pnpm contract:sync --core-receipt ./core-receipt.json
```

The Core receipt identifies the image to reuse. Each command still owns a fresh database.
For a published digest, use `INKCRE_CORE_IMAGE` with either browser lane directly.
For normal interactive development, attach to a running Python worktree using the
`external` descriptor described above.

尚未发布的候选 Core 可用 `pnpm contract:sync --image sha256:<完整的本地镜像 ID>` 生成投影,再用相同参数追加
`--check` 核对。镜像必须已存在于所选 local/ssh Docker daemon,工具核对 ID 并使用同一不可变镜像创建、清理
独占的 typegen 数据库,不接受可移动 tag,也不会拉取本地 ID。此入口不支持 external provider;需选择构建候选的
同一 provider。`contracts/core-release.json` 仍只接纳已发布的 GHCR digest,本地生成不能代替发布产物验收。
类型生成也可用 `--image` 显式指定完整本地镜像 ID 或发布摘要。选择一个拥有独立数据库的 local/ssh provider。
`contracts/core-release.json` 的准入使用已发布的 GHCR digest。

## Operator Commands

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"check:package": "node scripts/check-package-contract.mjs",
"test:e2e": "pnpm test:e2e:web && pnpm test:e2e:webext",
"test:e2e:core": "node scripts/test-e2e-from-core.mjs",
"test:e2e:registry": "node scripts/test-e2e-from-core.mjs --registry",
"test:e2e:web": "node scripts/test-e2e.mjs",
"test:e2e:webext": "node scripts/test-webext-e2e.mjs",
"verify:twitter": "playwright test --config scripts/tests/twitter-acceptance.config.ts",
Expand Down
4 changes: 0 additions & 4 deletions scripts/check-database-contract.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@ for (const image of Object.values(config.runtime_images)) {
for (const expected of [
'${INKCRE_CORE_IMAGE:?INKCRE_CORE_IMAGE is required}',
'database-contract:/database-contract',
"user: '0:0'",
'psql -v ON_ERROR_STOP=1 -h postgres -U postgres -d inkcre',
"['python', 'scripts/container.py', 'db', 'init'",
"['python', 'scripts/container.py', 'web']",
]) {
if (!compose.includes(expected)) errors.push(`database Compose is missing ${expected}`)
}
Expand Down
1 change: 0 additions & 1 deletion scripts/check-local-runtime-contract.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ if (!localTargets) {

const databaseCompose = await readFile(`${repoRoot}/runtime/database.compose.yml`, 'utf8')
for (const required of [
"command: ['python', 'scripts/container.py', 'db', 'init', '--profile', 'development']",
'${INKCRE_CORE_IMAGE:?INKCRE_CORE_IMAGE is required}',
'database-contract:/database-contract',
'${POSTGRES_PORT:-0}',
Expand Down
32 changes: 32 additions & 0 deletions scripts/database-provider.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,38 @@ export function assertLocalDatabaseAccess(provider) {
}
}

export function configureOwnedCandidateProvider() {
let provider = resolveDatabaseProviderConfig()
if (provider.kind === 'external' && process.env.INKCRE_E2E_DATABASE_PROVIDER) {
process.env.INKCRE_DATABASE_PROVIDER = process.env.INKCRE_E2E_DATABASE_PROVIDER
provider = resolveDatabaseProviderConfig()
if (provider.kind === 'external') {
throw new Error('Candidate verification requires an owned local or SSH database runtime')
}
}
if (provider.kind === 'ssh') return provider

const endpoint =
(!process.env.DOCKER_CONTEXT && process.env.DOCKER_HOST) ||
runDatabaseDocker({ kind: 'local' }, [
'context',
'inspect',
'--format',
'{{.Endpoints.docker.Host}}',
])
// The SSH provider also makes loopback ports reachable by consumer processes.
const target = endpoint.match(/^ssh:\/\/([a-zA-Z0-9][a-zA-Z0-9._-]{0,127})$/)?.[1]
if (target && (!process.env.INKCRE_DATABASE_PROVIDER || provider.kind === 'external')) {
process.env.INKCRE_DATABASE_PROVIDER = 'ssh'
process.env.INKCRE_DATABASE_SSH_TARGET = target
} else if (provider.kind === 'external') {
process.env.INKCRE_DATABASE_PROVIDER = 'local'
}
provider = resolveDatabaseProviderConfig()
if (provider.kind === 'local') assertLocalDatabaseAccess(provider)
return provider
}

export function readExternalDatabaseDescriptor(provider) {
const descriptor = JSON.parse(readFileSync(provider.descriptor, 'utf8'))
if (descriptor.owner_repository !== 'InKCre/impl-py') {
Expand Down
140 changes: 140 additions & 0 deletions scripts/dev-from-core.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { execFile } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { realpath } from 'node:fs/promises'
import { basename, join } from 'node:path'
import { promisify } from 'node:util'

import { chromium } from '@playwright/test'
import { CONFIG_STORAGE_KEY } from '../packages/core/src/config/types.ts'
import { readExternalDatabaseDescriptor } from './database-provider.mjs'
import { resolveDevOrigin } from './dev-origin.mjs'
import {
readiness,
repoRoot,
runtimeCredentials,
runtimeState,
waitForRuntime,
} from './database-runtime-lib.mjs'

const exec = promisify(execFile)
const instancePattern = /^[a-f0-9]{16}$/

async function ensureTarget(target, cwd, env) {
const argv = ['dev', 'ensure', target, '--repo', cwd, '--json']
let result
try {
const { stdout } = await exec('svc', argv, { cwd, env, timeout: 660_000 })
result = JSON.parse(stdout)
} catch (error) {
try {
result = JSON.parse(error.stdout)
} catch {
throw new Error(`Could not run SVC for ${target} in ${cwd}: ${error.message}`)
}
}
if (result.ready !== true || !instancePattern.test(result.workspace?.instance ?? '')) {
const reason =
result.error?.details?.reason ??
result.error?.message ??
result.reason ??
result.status ??
'unrecognized SVC result'
const log = result.attempt?.logs?.merged?.path
throw new Error(`SVC ${target} in ${cwd}: ${reason}${log ? `; log: ${log}` : ''}`)
}
return result
}

export async function launchWebWithCoreSource(args) {
const [source, mode, ...extra] = args
if (!source || source.startsWith('-') || (mode && mode !== '--headless') || extra.length) {
console.error('Usage: pnpm dev --core-source <impl-py worktree> [--headless]')
return 2
}

const coreRoot = await realpath(source)
const coreEnv = { ...process.env }
if (coreEnv.INKCRE_DATABASE_PROVIDER === 'external') delete coreEnv.INKCRE_DATABASE_PROVIDER
const { stdout } = await exec('pdm', ['run', '--json'], { cwd: coreRoot, env: coreEnv })
if (!Object.hasOwn(JSON.parse(stdout), 'dev:database')) {
throw new Error(`Core worktree does not declare the dev:database task: ${coreRoot}`)
}
console.log(`[core-source] Preparing ${coreRoot}`)
const core = await ensureTarget('database', coreRoot, coreEnv)
const descriptor = join(coreRoot, '.runtime', 'database', core.workspace.instance, 'runtime.json')
const backend = readExternalDatabaseDescriptor({ descriptor })
if (backend.identity !== core.workspace.instance) {
throw new Error('Core development descriptor does not match the selected worktree instance')
}

process.env.INKCRE_DATABASE_PROVIDER = 'external'
process.env.INKCRE_DATABASE_RUNTIME_DESCRIPTOR = descriptor
const state = await runtimeState(backend.identity)
readiness(state.identity)
await waitForRuntime(state)
const credentials = await runtimeCredentials(state.identity)
if (typeof credentials.JWT_SECRET !== 'string' || !credentials.JWT_SECRET) {
throw new Error('Selected Core development runtime has no browser credential')
}
const web = await ensureTarget('web', repoRoot, process.env)
const url = resolveDevOrigin('web', web.workspace.instance)

const id = randomUUID()
const config = {
INKCRE_PGREST_URL: state.urls.postgrest,
INKCRE_JWT_SECRET: credentials.JWT_SECRET,
INKCRE_PEER_ID: randomUUID(),
}
const storage = {
...config,
activeConnectionId: id,
connections: [{ id, name: basename(coreRoot), config }],
}
const observation = {
web: url.href,
core_worktree: coreRoot,
core_instance: state.runtime_instance,
source_revision: state.core_source_revision,
source_fingerprint: state.source_fingerprint,
migration_head: state.migration_head,
postgrest: state.urls.postgrest,
}
const headless = mode === '--headless'
const browser = await chromium.launch({ headless })
try {
const context = await browser.newContext({
ignoreHTTPSErrors: true,
storageState: {
cookies: [],
origins: [
{
origin: url.origin,
localStorage: [{ name: CONFIG_STORAGE_KEY, value: JSON.stringify(storage) }],
},
],
},
})
const page = await context.newPage()
const peerEndpoint = new URL('peers', state.urls.postgrest)
const connected = page.waitForResponse((response) => {
const observed = new URL(response.url())
return (
response.ok() &&
response.request().method() === 'GET' &&
observed.origin === peerEndpoint.origin &&
observed.pathname === peerEndpoint.pathname
)
})
await Promise.all([connected, page.goto(url.href)])
console.log(JSON.stringify(observation))
if (!headless && browser.isConnected() && !page.isClosed()) {
await Promise.race([
page.waitForEvent('close', { timeout: 0 }),
browser.waitForEvent('disconnected'),
])
}
} finally {
await browser.close()
}
return 0
}
25 changes: 25 additions & 0 deletions scripts/dev-origin.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { execFileSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'

const repoRoot = fileURLToPath(new URL('..', import.meta.url))
const routePrefixes = { web: 'client-web', 'web-ui': 'client-web-ui', webext: 'webext' }

export function resolveDevOrigin(target, instance) {
const prefix = routePrefixes[target]
if (!prefix || !/^[a-f0-9]{16}$/.test(instance ?? '')) {
throw new Error('Invalid worktree route identity')
}
const hostname = `${prefix}-${instance}.localhost`
const routes = execFileSync(`${repoRoot}/node_modules/.bin/portless`, ['list'], {
cwd: repoRoot,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
timeout: 3_000,
})
const origin = routes
.split('\n')
.map((line) => line.match(/(https:\/\/([a-z0-9.-]+\.localhost)(?::[0-9]+)?)(?=\s|$)/))
.find((match) => match?.[2] === hostname)?.[1]
if (!origin) throw new Error(`Portless has no HTTPS route for ${hostname}`)
return new URL(origin)
}
41 changes: 25 additions & 16 deletions scripts/dev.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,28 @@ async function runDeclaredTarget() {
})
}

const exitCode = process.env.SVC_DEV_TARGET
? await runDeclaredTarget()
: await (async () => {
const databaseExit = await run('svc', [
'dev',
'ensure',
'database',
'--repo',
repoRoot,
'--json',
])
if (databaseExit !== 0) return databaseExit
return run('svc', ['dev', 'ensure', target, '--repo', repoRoot, '--json'])
})()

process.exitCode = exitCode
async function main() {
if (process.env.SVC_DEV_TARGET) return runDeclaredTarget()

const commandArgs = process.argv.slice(3)
if (commandArgs[0] === '--') commandArgs.shift()
if (target === 'web' && commandArgs[0] === '--core-source') {
const { launchWebWithCoreSource } = await import('./dev-from-core.mjs')
return launchWebWithCoreSource(commandArgs.slice(1))
}
if (commandArgs.length > 0) {
const usage = 'Usage: pnpm dev [--core-source <impl-py worktree> [--headless]]'
if (target === 'web' && commandArgs.length === 1 && commandArgs[0] === '--help') {
console.log(usage)
return 0
}
console.error(target === 'web' ? usage : `Unexpected options for the ${target} target`)
return 2
}

const databaseExit = await run('svc', ['dev', 'ensure', 'database', '--repo', repoRoot, '--json'])
if (databaseExit !== 0) return databaseExit
return run('svc', ['dev', 'ensure', target, '--repo', repoRoot, '--json'])
}

process.exitCode = await main()
36 changes: 4 additions & 32 deletions scripts/probe-dev.mjs
Original file line number Diff line number Diff line change
@@ -1,22 +1,10 @@
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { realpathSync } from 'node:fs'
import { get } from 'node:https'
import { fileURLToPath } from 'node:url'
import { resolveDevOrigin } from './dev-origin.mjs'

const target = process.argv[2]
const instance = process.argv[3]
const repoRoot = fileURLToPath(new URL('..', import.meta.url))
const portlessBin = `${repoRoot}/node_modules/.bin/portless`
const names = {
// Keep the browser origin stable so existing local settings remain readable.
web: 'client-web',
'web-ui': 'client-web-ui',
webext: 'webext',
}
if (!names[target] || !instance || !/^[a-f0-9]{16}$/.test(instance)) {
process.exit(2)
}

let expectedUiSource = null
try {
Expand All @@ -30,29 +18,13 @@ try {
process.exit(1)
}

const routeName = `${names[target]}-${instance}`
let origin
let endpoint
try {
const routes = execFileSync(portlessBin, ['list'], {
cwd: repoRoot,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
timeout: 3_000,
})
const route = routes
.split('\n')
.map((line) => line.match(/(https:\/\/([a-z0-9-]+)\.localhost(?::[0-9]+)?)/))
.find((match) => match?.[2] === routeName)
origin = route?.[1]
endpoint = new URL(`/__inkcre/dev/${instance}`, resolveDevOrigin(target, instance))
} catch {
// Portless is not running yet.
process.exit(1)
}

if (!origin) process.exit(1)

const url = `${origin}/__inkcre/dev/${instance}`
const endpoint = new URL(url)

const observation = await new Promise((resolve) => {
const request = get(
{
Expand Down
Loading