HEL-892: document Krea2 API named inputs without inferred identities
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
"""HEL-892 isolated browser host: production workflow router, no execution worker.
|
||||
|
||||
From repo root: calliope-backend/.venv/bin/python e2e/krea-api-document-server.py
|
||||
Run Vite on 5173 alongside it. No remote ComfyUI endpoint is configured.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import uvicorn
|
||||
from calliope.comfyui.companions import load_companions
|
||||
from calliope.comfyui.library import import_library
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, migrate_db
|
||||
from calliope.routers import workflows
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA = ROOT / ".local-evidence" / "krea-api-document-server"
|
||||
settings.data_dir = DATA
|
||||
settings.db_name = "library.db"
|
||||
settings.assets_dir = DATA / "assets"
|
||||
settings.comfyui_endpoints = []
|
||||
settings.comfyui_base_url = "http://127.0.0.1:1"
|
||||
app = FastAPI()
|
||||
app.include_router(workflows.router, prefix="/api/workflows")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def read_only(request, call_next):
|
||||
if request.method != "GET":
|
||||
return JSONResponse({"detail": "隔离说明服务仅允许GET"}, status_code=405)
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
@app.get("/api/settings")
|
||||
def get_settings():
|
||||
return {"comfyui_endpoints": [], "comfyui_active_id": None}
|
||||
|
||||
|
||||
def prepare():
|
||||
DATA.mkdir(parents=True, exist_ok=True)
|
||||
asyncio.run(migrate_db(settings.db_path))
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
report = import_library(
|
||||
conn,
|
||||
ROOT / "example_ComfyUI_workflows",
|
||||
source_commit="ui-browser",
|
||||
companions=load_companions(ROOT / "docs/hel-892/supplied-api/manifest.json"),
|
||||
)
|
||||
print({"counts": report["counts"], "states": report["states"]})
|
||||
assert report["counts"] == {"imported": 155, "user_excluded": 1}
|
||||
assert report["states"] == {"pending_check": 16, "needs_conversion": 139}
|
||||
for name, document in [
|
||||
("旧工作流回退(隔离测试夹具)", None),
|
||||
("空说明回退(隔离测试夹具)", "{}"),
|
||||
]:
|
||||
if conn.execute("SELECT id FROM workflows WHERE name=?", (name,)).fetchone():
|
||||
continue
|
||||
conn.execute(
|
||||
"INSERT INTO workflows(name,kind,workflow_json,input_schema,description,"
|
||||
"is_enabled,doc_json) VALUES (?,?,?,?,?,?,?)",
|
||||
(
|
||||
name,
|
||||
"image",
|
||||
"{}",
|
||||
"[]",
|
||||
"隔离库旧条目回退测试;不代表真实工作流。",
|
||||
0,
|
||||
document,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
prepare()
|
||||
uvicorn.run(app, host="127.0.0.1", port=8247)
|
||||
@@ -0,0 +1,116 @@
|
||||
// Batch164 local GET-only:230 saved/5 Notes/85 exact/2 VHS gaps/13 unknown/4 hosts.
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const out='.local-evidence/krea-api-document/browser';fs.mkdirSync(out,{recursive:true});
|
||||
const checks=[],requests=[],errors=[],blockedFonts=[],assertionGroups={},interceptions=[];let group='aggregate';
|
||||
const textRenderings=[];
|
||||
function check(condition,label){assert.ok(condition,label);checks.push(label);assertionGroups[group]=(assertionGroups[group]||0)+1;console.log('PASS '+label);}
|
||||
function assertLocalUrl(raw){
|
||||
const u=new URL(String(raw));assert.ok(u.protocol==='http:'&&['127.0.0.1','localhost'].includes(u.hostname)&&['8247','5173'].includes(u.port)&&!u.username&&!u.password,'Refused before request: '+u);return u;
|
||||
}
|
||||
function localFetch(raw){assertLocalUrl(raw);return fetch(raw);}
|
||||
for(const raw of ['http://6.0.0.1:8247/api/workflows','http://127.0.0.1:9999/','https://example.invalid/','http://127.0.0.1:8247@evil.invalid/']){assert.throws(()=>assertLocalUrl(raw));check(true,'URL预检拒绝且未发送 '+raw);}
|
||||
for(const raw of ['http://127.0.0.1:8247/api/workflows','http://127.0.0.1:5173/connections'])assertLocalUrl(raw);
|
||||
const browser=await chromium.launch({headless:true,executablePath:process.env.BROWSER_EXECUTABLE});
|
||||
try {
|
||||
const page=await browser.newPage({viewport:{width:1440,height:1000}});
|
||||
await page.routeWebSocket('**/*',ws=>{ws.close();}); // No HMR socket transport is needed for read-only checks.
|
||||
await page.route('**/*',route=>{
|
||||
const u=new URL(route.request().url());
|
||||
if(u.hostname==='fonts.googleapis.com'){blockedFonts.push(String(u));return route.fulfill({contentType:'text/css',body:''});}
|
||||
try{assertLocalUrl(u);}catch(e){errors.push(String(e));return route.abort();}
|
||||
if(route.request().method()!=='GET'||u.pathname==='/api/view'||(/\.(mp4|png|wav|mp3|webm)$/i.test(u.pathname)&&u.pathname!=='/favicon.png')){errors.push('Forbidden request '+u);return route.abort();}
|
||||
return route.continue();
|
||||
});
|
||||
page.on('request',r=>{if(r.url().includes('/api/'))requests.push({method:r.method(),url:r.url()});});
|
||||
page.on('pageerror',e=>errors.push(e.message));
|
||||
requests.push({method:'GET',url:'http://127.0.0.1:8247/api/workflows'});
|
||||
const records=await(await localFetch('http://127.0.0.1:8247/api/workflows')).json();
|
||||
const reviews=JSON.parse(fs.readFileSync('calliope-backend/src/calliope/comfyui/source_reviews.json'));
|
||||
const path='example_ComfyUI_workflows/Krea2_t2i_20260818_API.json';
|
||||
const paths=[path,...Object.keys(reviews).filter(p=>p!==path&&reviews[p].fixed_version_document)];
|
||||
const details=[];let actualGetRaw;
|
||||
for(const p of paths){const r=records.find(r=>r.source_repo_path===p);assert.ok(r,p);const url=`http://127.0.0.1:8247/api/workflows/${r.id}`;requests.push({method:'GET',url});const raw=await(await localFetch(url)).text();const d=JSON.parse(raw);details.push(d);assert.deepEqual(d.doc_json.fixed_version,{...reviews[p].fixed_version_document,matched:true});if(p===path)actualGetRaw=raw;}
|
||||
check(details.length===146&&details.reduce((n,d)=>n+d.doc_json.fixed_version.fields.length,0)===10257,'146参考/10257保存项');
|
||||
check(details.slice(1).reduce((n,d)=>n+(d.doc_json.source_notes?.length||0),0)===287,'旧145/287注释摘要冻结');
|
||||
const original=JSON.parse(fs.readFileSync(path));
|
||||
const audit=JSON.parse(fs.readFileSync('docs/hel-892/krea-api-document-evidence/original-audit.json'));
|
||||
fs.writeFileSync(out+'/actual-get.json',actualGetRaw);
|
||||
const isolated=JSON.parse(fs.readFileSync('docs/hel-892/krea-api-document-evidence/actual-Krea2_t2i_20260818_API.json'));
|
||||
assert.deepEqual(details[0].doc_json,isolated);check(true,'actual GET=隔离doc JSON内容/解析类型,不称HTTP原字节');
|
||||
await page.goto(assertLocalUrl('http://127.0.0.1:5173/connections').href,{waitUntil:'networkidle'});
|
||||
const dialog=page.getByRole('dialog',{name:'工作流说明'});
|
||||
const fixedCard=dialog.locator('.card').filter({has:page.getByText('固定版本参数说明',{exact:true})});
|
||||
async function begin(name){const row=page.locator('.wf-row').filter({has:page.getByText(name,{exact:true})}).first();const button=row.getByRole('button',{name:'说明',exact:true});await button.focus();await page.keyboard.press('Enter');return button;}
|
||||
async function loaded(){await dialog.getByText('用途与来源',{exact:true}).waitFor();await dialog.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));}
|
||||
async function shot(name,locator){if(locator){await locator.evaluate(el=>el.scrollIntoView({block:'start'}));await dialog.locator('.drawer-body').evaluate(el=>el.scrollTop=Math.max(0,el.scrollTop-60));}await page.screenshot({path:out+'/'+name+'.png'});}
|
||||
for(const width of [1440,390]){
|
||||
await page.setViewportSize({width,height:width===390?844:1000});
|
||||
for(const d of details){
|
||||
group=d===details[0]?'new_API':'old_145';const b=d.doc_json.fixed_version,button=await begin(d.name);await loaded();
|
||||
check((await dialog.innerText()).includes(b.user_overview),`${width}/${d.id}中文用途`);
|
||||
check(await fixedCard.locator('[data-fixed-field]').count()===b.fields.length,`${width}/${d.id}字段数保持`);
|
||||
check(!d.is_enabled&&!d.doc_completed_at&&!d.exec_verified_at,`${width}/${d.id}资格关闭/时间空`);
|
||||
check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width}/${d.id}无溢出`);
|
||||
if(d!==details[0]){await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});check(await button.evaluate(el=>el===document.activeElement),`${width}/${d.id}旧摘要关闭焦点`);continue;}
|
||||
await shot(width+'-default');
|
||||
check(b.sources.length===0&&b.comments.length===0&&b.node_bindings.length===24&&b.node_bindings.every(n=>!n.implementation_verified&&n.scope==='root'),`${width}24root未知/零准确来源/零Note`);
|
||||
check(Object.values(original).every(n=>Object.keys(n).sort().join(',')==='_meta,class_type,inputs'),`${width}原件无version/mode/widgets/画布/子图`);
|
||||
await dialog.getByText('核对范围与来源依据',{exact:true}).click();
|
||||
const flowText=await fixedCard.innerText();
|
||||
for(const line of b.flow)check(flowText.includes(line),`${width}原流程/标题/引用 ${b.flow.indexOf(line)}`);
|
||||
for(const e of b.api_references){assert.deepEqual(original[e.target_node_id].inputs[e.input_name],e.original);check(e.output_index===0&&e.original.length===2,`${width}原34引用 ${e.pointer}`);}
|
||||
for(const i of [0,1,2,3,4,5,7,8,9])await shot(width+'-flow-'+i,fixedCard.getByText(b.flow[i],{exact:true}));
|
||||
for(const f of b.fields){
|
||||
assert.deepEqual(original[f.node_id].inputs[f.field],f.value);check(f.pointer===`/${f.node_id}/inputs/${f.field}`&&!('named_pointer'in f)&&!('named_value'in f)&&!('widget_index'in f),`${width}唯一原具名指针 ${f.pointer}`);
|
||||
const summary=fixedCard.locator(`details[data-fixed-field="${f.pointer}"] > summary`);await summary.focus();await page.keyboard.press('Enter');const box=summary.locator('..');
|
||||
check(await box.evaluate(el=>el.open),`${width}/${f.pointer}键盘展开`);
|
||||
const rendered=await box.locator(':scope > pre').textContent();
|
||||
if(typeof f.value==='string')assert.equal(rendered,f.value);else assert.deepEqual(JSON.parse(rendered),f.value);
|
||||
check(true,`${width}/${f.pointer}DOM原串或解析值/类型`);
|
||||
const text=await box.innerText();check(text.includes(f.effect)&&text.includes(f.schema_default)&&text.includes(f.unit)&&text.includes(f.execution_note),`${width}/${f.pointer}实现/单位/范围未知`);
|
||||
await box.getByText('来源依据',{exact:true}).click();check((await box.innerText()).includes(f.pointer)&&(await box.innerText()).includes(f.json_type),`${width}/${f.pointer}指针/类型可见`);
|
||||
check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width}/${f.pointer}展开无溢出`);
|
||||
if(audit.strings.some(s=>s.node_id===f.node_id)&&f.field==='value'){
|
||||
const a=audit.strings.find(s=>s.node_id===f.node_id),hash=crypto.createHash('sha256').update(rendered).digest('hex');check(hash===a.sha256&&Array.from(rendered).length===a.characters&&rendered.split('\n').length-1===a.LF&&rendered.endsWith('\n')===a.tail_LF,`${width}/${f.node_id}完整英文/前空格/尾LF/SHA`);textRenderings.push({viewport:width,node_id:f.node_id,raw_decoded_sha256:hash,dom_utf8_sha256:hash,report_json_value_sha256:crypto.createHash('sha256').update(JSON.stringify(f.value)).digest('hex')});await shot(width+'-text-'+f.node_id.replaceAll(':','_'),summary);
|
||||
}
|
||||
if(['152.lora_name','146.seed','172.denoise','171:153.sampling_mode.temperature','160.value','161.value','171:154.delimiter','171:162.delimiter'].includes(f.node_id+'.'+f.field))await shot(width+'-field-'+f.node_id.replaceAll(':','_')+'-'+f.field,summary);
|
||||
await summary.click();
|
||||
}
|
||||
check(await dialog.locator('img,canvas,video,audio,iframe').count()===0,`${width}纯文本不加载媒体`);
|
||||
await dialog.getByRole('button',{name:'关闭',exact:true}).focus();await page.keyboard.press('Tab');check(await dialog.evaluate(el=>el.contains(document.activeElement)),`${width}Tab焦点保留`);await page.keyboard.press('Shift+Tab');check(await dialog.evaluate(el=>el.contains(document.activeElement)),`${width}ShiftTab焦点保留`);
|
||||
await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});check(await button.evaluate(el=>el===document.activeElement),`${width}新API归还焦点`);
|
||||
}
|
||||
}
|
||||
group='shared_regressions';
|
||||
for(const name of ['旧工作流回退(隔离测试夹具)','空说明回退(隔离测试夹具)']){await begin(name);await loaded();check((await dialog.innerText()).includes('隔离库旧条目回退测试'),'旧/空说明回退 '+name);await page.keyboard.press('Escape');}
|
||||
// Missing summary and mismatched bindings are tested with local GET fixtures, without writes.
|
||||
for(const variant of ['missing-overview','mismatched','html-summary']){
|
||||
const d=structuredClone(details[0]);
|
||||
if(variant==='missing-overview')delete d.doc_json.fixed_version.user_overview;
|
||||
if(variant==='mismatched')d.doc_json.fixed_version={matched:false,notice:'固定版本参数说明待核对:源文件、声明版本或说明依据未匹配,未采用旧定义。'};
|
||||
if(variant==='html-summary')d.doc_json.fixed_version.user_overview='<img src="https://example.invalid/forbidden">仅纯文本';
|
||||
await page.route(`**/api/workflows/${d.id}`,route=>{interceptions.push({variant,url:route.request().url()});return route.fulfill({json:d});});
|
||||
const responseReady=page.waitForResponse(r=>new URL(r.url()).pathname===`/api/workflows/${d.id}`&&r.status()===200);
|
||||
await begin(d.name);const fixtureResponse=await responseReady;await fixtureResponse.finished();
|
||||
const returned=await fixtureResponse.json();assert.deepEqual(returned,d);
|
||||
const expectedSummary=variant==='missing-overview'?'这张图的用途和操作重点可在下方使用步骤中查看;目标环境与实际效果仍待核对。':variant==='mismatched'?d.doc_json.fixed_version.notice:d.doc_json.fixed_version.user_overview;
|
||||
await dialog.getByText(expectedSummary,{exact:true}).waitFor({timeout:20000});await loaded();
|
||||
if(variant==='missing-overview')check((await dialog.innerText()).includes('这张图的用途和操作重点可在下方使用步骤中查看;目标环境与实际效果仍待核对。'),'缺摘要自然中文回退');
|
||||
if(variant==='mismatched')check((await dialog.innerText()).includes(d.doc_json.fixed_version.notice)&&!await dialog.getByText('核对范围与来源依据',{exact:true}).count(),'错绑定提示明确且不展示旧字段');
|
||||
if(variant==='html-summary')check((await dialog.innerText()).includes(d.doc_json.fixed_version.user_overview)&&await dialog.locator('img').count()===0,'摘要HTML仅纯文本不创建图像或请求');
|
||||
check(!(await dialog.innerText()).includes('undefined'),'回退不暴露undefined');await page.keyboard.press('Escape');await page.unroute(`**/api/workflows/${d.id}`);
|
||||
}
|
||||
let release,entered,delivered;const hold=new Promise(r=>release=r),intercept=new Promise(r=>entered=r),done=new Promise(r=>delivered=r);
|
||||
await page.route(`**/api/workflows/${details[0].id}`,async route=>{interceptions.push({variant:"late",url:route.request().url()});entered();await hold;await route.fulfill({json:details[0]});delivered();});
|
||||
await begin(details[0].name);await intercept;await page.keyboard.press('Escape');await begin(details[1].name);await loaded();release();await done;
|
||||
check((await dialog.innerText()).includes(details[1].doc_json.fixed_version.user_overview)&&await fixedCard.locator('summary').filter({hasText:/^节点 [\d:]+ · /}).count()===details[1].doc_json.fixed_version.fields.length,'迟到新图响应不覆盖旧图摘要/字段');await page.keyboard.press('Escape');await page.unroute(`**/api/workflows/${details[0].id}`);
|
||||
await page.route(`**/api/workflows/${details[0].id}`,route=>{interceptions.push({variant:'failure',url:route.request().url()});return route.fulfill({status:500,json:{detail:'隔离失败夹具'}});});await begin(details[0].name);await dialog.getByRole('alert').waitFor({timeout:20000});check(await dialog.getByRole('button',{name:'重试',exact:true}).isVisible(),'GET失败显示重试');check(await dialog.getByText('用途与来源',{exact:true}).count()===0,'读取失败隐藏旧摘要');await page.unroute(`**/api/workflows/${details[0].id}`);await dialog.getByRole('button',{name:'重试',exact:true}).click();await loaded();check((await dialog.innerText()).includes(details[0].doc_json.fixed_version.user_overview),'重试恢复摘要');await page.keyboard.press('Escape');
|
||||
check(errors.length===0,'无脚本错误或禁止请求 '+JSON.stringify(errors));check(requests.every(r=>r.method==='GET'&&new URL(r.url).hostname==='127.0.0.1'&&!r.url.includes('/api/view')),'全程本地GET无写/生成/目标/历史预览请求');
|
||||
const polling=requests.filter(r=>['/api/jobs','/api/events'].includes(new URL(r.url).pathname));
|
||||
const fixed=requests.filter(r=>!polling.includes(r));
|
||||
const frequencies=rs=>Object.fromEntries([...new Set(rs.map(r=>new URL(r.url).pathname))].sort().map(p=>[p,rs.filter(r=>new URL(r.url).pathname===p).length]));
|
||||
fs.writeFileSync(`${out}/browser-results.json`,JSON.stringify({request_accounting:{fixed_count:fixed.length,fixed_paths:frequencies(fixed),polling_count:polling.length,polling_paths:frequencies(polling),polling_tolerance:1,reason:'固定请求逐路径核账;events零差额,只允许已证末次jobs至多1差额;禁止请求零容忍。'},assertion_count:checks.length,assertionGroups,text_renderings:textRenderings,interceptions,checks,requests,errors,blockedFonts,viewports:[1440,390]},null,2));
|
||||
} finally {await browser.close();}
|
||||
@@ -0,0 +1,123 @@
|
||||
"Foreground local browser check; stop every owned service before returning."
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / (".local-evidence/krea-api-document/browser")
|
||||
|
||||
|
||||
def main():
|
||||
# Require successful rebuilt and packaged current resources before any service starts.
|
||||
evidence = ROOT / "docs/hel-892/krea-api-document-evidence"
|
||||
for record in json.loads((evidence / "package-check.json").read_bytes()):
|
||||
product = ROOT / "calliope-backend/src/calliope/comfyui" / record["file"]
|
||||
assert hashlib.sha256(product.read_bytes()).hexdigest() == record["sha256"]
|
||||
assert record["wheel"] and record["sdist"] and record["definitions"] == 146
|
||||
protection = json.loads((evidence / "import-protection.json").read_bytes())
|
||||
assert protection["upgrade"] == {"updated": 1, "skipped": 154, "user_excluded": 1}
|
||||
data = ROOT / ".local-evidence/krea-api-document-server"
|
||||
assert not data.exists(), "Prior owned data must be reversibly quarantined before another run"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
(OUT / "fresh-path-check.json").write_text(
|
||||
json.dumps(dict(data_path=str(data.relative_to(ROOT)), existed_before_start=False)) + "\n"
|
||||
)
|
||||
# Refuse to reuse another operator's service or port.
|
||||
import socket
|
||||
|
||||
for port in (8247, 5173):
|
||||
with socket.socket() as sock:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.bind(("127.0.0.1", port))
|
||||
processes = []
|
||||
logs = []
|
||||
try:
|
||||
commands = [
|
||||
([sys.executable, str(ROOT / "e2e/krea-api-document-server.py")], ROOT),
|
||||
(
|
||||
["node", "node_modules/vite/bin/vite.js", "--host", "127.0.0.1"],
|
||||
ROOT / "calliope-web",
|
||||
),
|
||||
]
|
||||
for i, (command, cwd) in enumerate(commands):
|
||||
log = (OUT / f"service-{i}.log").open("w")
|
||||
logs.append(log)
|
||||
processes.append(
|
||||
subprocess.Popen(command, cwd=cwd, stdout=log, stderr=log, start_new_session=True)
|
||||
)
|
||||
for url in (
|
||||
"http://127.0.0.1:8247/api/workflows",
|
||||
"http://127.0.0.1:5173/connections",
|
||||
):
|
||||
parsed = urlsplit(url)
|
||||
if (
|
||||
parsed.scheme != "http"
|
||||
or parsed.hostname not in {"127.0.0.1", "localhost"}
|
||||
or parsed.port not in {8247, 5173}
|
||||
or parsed.username
|
||||
or parsed.password
|
||||
):
|
||||
raise ValueError("Refused before readiness request: " + url)
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
if any(p.poll() is not None for p in processes):
|
||||
raise RuntimeError("Local service exited; inspect service logs")
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=1) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
pass
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError(url)
|
||||
time.sleep(0.2)
|
||||
names = ["krea-api-document"]
|
||||
for name in names:
|
||||
subprocess.run(["node", f"e2e/{name}.mjs"], cwd=ROOT, check=True)
|
||||
finally:
|
||||
for p in processes:
|
||||
if p.poll() is None:
|
||||
os.killpg(p.pid, signal.SIGTERM)
|
||||
try:
|
||||
p.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(p.pid, signal.SIGKILL)
|
||||
p.wait(timeout=5)
|
||||
for log in logs:
|
||||
log.close()
|
||||
released = []
|
||||
for port in (8247, 5173):
|
||||
with socket.socket() as sock:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.bind(("127.0.0.1", port))
|
||||
released.append(port)
|
||||
with socket.socket() as probe:
|
||||
probe.settimeout(1)
|
||||
assert probe.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
(OUT / "service-stop.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"ports_released": released,
|
||||
"independent_connection_refused": released,
|
||||
"child_exit_codes": [p.returncode for p in processes],
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
print(("All owned browser services stopped; ports released."))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user