Files
vibemake-pcb-studio/codex_pcb/editing_projects.py
T

269 lines
13 KiB
Python

"""Authenticated task ownership and idempotent creation of cloud editing copies."""
import hashlib
import json
import os
import secrets
import sqlite3
import zipfile
from contextlib import closing, contextmanager
from dataclasses import dataclass, field
from functools import lru_cache
from urllib.parse import quote
import httpx
from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from . import storage
def origin():
return (os.environ.get('API_TARGET') or 'https://dev-vibemake-api.robotquan.com').rstrip('/')
def owner_key(user_code):
return hashlib.sha256((origin() + '\0' + user_code).encode()).hexdigest()
@dataclass(frozen=True)
class Account:
owner: str
token: str = field(repr=False)
async def platform(method, path, token, **kwargs):
try:
async with httpx.AsyncClient(timeout=12, follow_redirects=False) as client:
response = await client.request(method, origin() + '/api' + path,
headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/json'}, **kwargs)
if response.status_code in (401, 403):
raise HTTPException(response.status_code, '登录已失效或没有权限,请重新登录。')
if response.status_code == 429:
raise HTTPException(429, '平台请求过于频繁,请稍后再试。')
if response.status_code in (400, 404, 422):
raise HTTPException(response.status_code, '平台未接受该工程请求。')
response.raise_for_status()
payload = response.json()
except (httpx.HTTPError, ValueError) as exc:
raise HTTPException(503, '暂时无法确认平台响应,请稍后重试。') from exc
if not isinstance(payload, dict):
raise HTTPException(502, '平台返回的数据无法识别。')
if payload.get('code') == 'PCB_PROJECT_NOT_FOUND':
raise HTTPException(404, '这个云工程已删除。')
if payload.get('code') in ('UNAUTHORIZED', 'FORBIDDEN'):
raise HTTPException(401, '登录已失效,请重新登录。')
if payload.get('code') not in (None, 'OK') or 'data' not in payload:
raise HTTPException(502, '平台未确认请求。')
return payload['data']
async def current_account(credentials: HTTPAuthorizationCredentials | None = Depends(HTTPBearer(auto_error=False))):
if not credentials or credentials.scheme.lower() != 'bearer':
raise HTTPException(401, '请先登录后再查看 AI 绘板工程。', headers={'WWW-Authenticate':'Bearer'})
user = await platform('GET', '/users/me', credentials.credentials)
if not isinstance(user, dict) or not isinstance(user.get('userCode'), str) or not user['userCode'].strip():
raise HTTPException(502, '平台未返回有效的登录用户。')
return Account(owner_key(user['userCode']), credentials.credentials)
@contextmanager
def connection():
# Kept outside every agent workspace and original delivery directory.
folder = storage.TASKS.parent
folder.mkdir(parents=True, exist_ok=True)
with closing(sqlite3.connect(folder/'editing-projects.sqlite3', timeout=5)) as db, db:
db.row_factory = sqlite3.Row
db.execute('''CREATE TABLE IF NOT EXISTS projects(
task_id TEXT PRIMARY KEY, owner TEXT NOT NULL, marker TEXT NOT NULL UNIQUE,
attempted INTEGER NOT NULL DEFAULT 0, project_code TEXT UNIQUE)''')
db.execute('CREATE INDEX IF NOT EXISTS task_owner ON projects(owner)')
yield db
def bind(tid, owner):
storage.task_dir(tid) # validate the task identifier
with connection() as db:
db.execute('INSERT OR IGNORE INTO projects(task_id,owner,marker) VALUES(?,?,?)',
(tid, owner, 'AI PCB · ' + secrets.token_hex(16)))
row = db.execute('SELECT owner FROM projects WHERE task_id=?', (tid,)).fetchone()
if not row or row['owner'] != owner:
raise ValueError('任务已经绑定到其他账号,不能转移。')
def owned(owner):
with connection() as db:
return {row['task_id']: row['project_code'] for row in db.execute(
'SELECT task_id, project_code FROM projects WHERE owner=?', (owner,))}
def record(tid, owner):
with connection() as db:
row = db.execute('SELECT * FROM projects WHERE task_id=? AND owner=?', (tid, owner)).fetchone()
if not row:
raise HTTPException(404, '找不到此 AI 绘板工程。')
return row
async def require_owned(tid: str, account: Account = Depends(current_account)):
return record(tid, account.owner)
def file_key(path):
info = path.stat()
return path, info.st_mtime_ns, info.st_size
@lru_cache(maxsize=256)
def source_info(path, mtime, size):
try:
with zipfile.ZipFile(path) as z:
files = z.namelist()
boards = [name for name in files if name.endswith('.kicad_pcb')]
if boards:
stem = boards[0].removesuffix('.kicad_pcb')
if len(boards) == 1 and all(stem + suffix in files for suffix in ('.kicad_pro','.kicad_sch')):
return 'available', None
return 'unsupported', '工程缺少配套的单板 KiCad 工程或原理图。'
if 'project.json' not in files:
if 'project2.json' in files or any(n.lower().endswith('.epru') for n in files):
return 'unsupported', '此工程使用新版嘉立创格式,当前网页编辑器暂不支持。'
return 'unsupported', '未找到网页编辑器支持的工程源文件。'
if z.getinfo('project.json').file_size > 32 * 1024**2:
return 'unsupported', '工程索引超过网页编辑器支持的大小。'
meta = json.loads(z.read('project.json'))
if not isinstance(meta, dict):
raise ValueError('metadata')
if len(meta.get('pcbs') or {}) != 1 or len(meta.get('schematics') or {}) != 1:
return 'unsupported', '当前编辑器需要单 PCB、单原理图工程,请先在嘉立创中选择实际交付板。'
return 'available', None
except (ValueError, TypeError, OSError, KeyError, zipfile.BadZipFile, RuntimeError):
return 'unsupported', '无法读取交付的工程源文件。'
@lru_cache(maxsize=256)
def manifest_digest(path, mtime, size):
return storage.digest(path.read_bytes())
def editing_fields(task, code):
status, reason, manifest = 'pending', None, None
if task.get('state') == 'completed':
source = next((f for f in (task.get('delivery') or {}).get('files', []) if f.get('kind') == 'project'), None)
try:
folder = storage.task_dir(task['id'])/'delivery'
manifest = manifest_digest(*file_key(folder/'manifest.json'))
if not source:
raise ValueError('missing source')
status, reason = source_info(*file_key(storage.inside(folder, source['name'])))
except (OSError, ValueError, KeyError):
status, reason = 'unsupported', '缺少已核验的交付清单或工程源文件。'
return {'project_code': code, 'editing_status': status, 'editing_reason': reason, 'manifest_sha256': manifest}
def code_for(item, marker):
if not isinstance(item, dict) or item.get('description') != marker:
return None
code = item.get('pcbProjectCode')
if not isinstance(code, str) or not code or code in {'.','..'} or not code.isprintable():
raise HTTPException(502, '平台未返回有效的工程编号。')
return code
async def recover_code(token, marker):
# The platform has no creation idempotency key. Only match our private request
# marker inside the authenticated user's list, including renamed projects.
page = 1
found = set()
while True:
result = await platform('GET', '/pcb/workspace/projects', token,
params={'page':page, 'size':20, 'keyword':''})
if not isinstance(result, dict) or result.get('page') != page or not isinstance(result.get('items'), list):
raise HTTPException(502, '暂时无法核对平台工程列表。')
found.update(code for item in result['items'] if (code := code_for(item, marker)))
total, size = result.get('total'), result.get('size')
if not isinstance(total, int) or not isinstance(size, int) or size < 1 or total < 0:
raise HTTPException(502, '暂时无法核对平台工程分页。')
if page * size >= total or not result['items']:
break
page += 1
if len(found) != 1:
raise HTTPException(409, '正在核实上次创建的云工程。请稍后再试;若持续出现,请管理员核查创建记录。')
return found.pop()
async def editing_project(task, account):
tid = task['id']
row = record(tid, account.owner)
code = row['project_code']
if code:
try:
item = await platform('GET', '/pcb/workspace/projects/' + quote(code, safe=''), account.token)
if not isinstance(item, dict) or item.get('pcbProjectCode') != code:
raise HTTPException(502, '平台未确认编辑副本的工程编号。')
return code
except HTTPException as exc:
if exc.status_code != 404:
raise
# An explicit open may rebuild a deleted copy. Concurrent opens must
# share the new marker; an outage or authorization failure never resets it.
with connection() as db:
db.execute('UPDATE projects SET project_code=NULL, attempted=0, marker=? WHERE task_id=? AND owner=? AND project_code=?',
('AI PCB · ' + secrets.token_hex(16), tid, account.owner, code))
row = record(tid, account.owner)
if row['project_code']:
return row['project_code']
info = editing_fields(task, None)
if info['editing_status'] != 'available':
raise HTTPException(409, info['editing_reason'] or '交付完成后可打开编辑副本。')
marker = row['marker']
with connection() as db:
first = db.execute('UPDATE projects SET attempted=1 WHERE task_id=? AND owner=? AND marker=? AND attempted=0 AND project_code IS NULL',
(tid, account.owner, marker)).rowcount
if first:
name = (task.get('proposal') or {}).get('title') or task.get('request') or 'AI PCB'
name = ''.join(c if c.isprintable() else ' ' for c in name).strip()[:100] or 'AI PCB'
try:
item = await platform('POST', '/pcb/workspace/projects', account.token,
json={'name':name, 'description':marker})
except HTTPException as exc:
if exc.status_code in (400, 401, 403, 404, 422, 429): # definitive rejection
with connection() as db:
db.execute('UPDATE projects SET attempted=0 WHERE task_id=? AND marker=? AND project_code IS NULL', (tid, marker))
raise
code = code_for(item, marker)
if not code:
raise HTTPException(502, '平台创建回执不完整,请重试以核对原工程。')
else:
code = await recover_code(account.token, marker)
with connection() as db:
db.execute('UPDATE projects SET project_code=? WHERE task_id=? AND owner=? AND marker=? AND project_code IS NULL',
(code, tid, account.owner, marker))
linked = db.execute('SELECT project_code FROM projects WHERE task_id=? AND owner=?', (tid,account.owner)).fetchone()
if not linked or linked[0] != code:
raise HTTPException(409, '工程关联发生变化,请刷新后重新打开。')
return code
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Bind a verified historical AI task to its confirmed platform owner')
parser.add_argument('command', choices=['bind', 'allow-create-after-confirmed-absent'])
parser.add_argument('task_id')
parser.add_argument('user_code', help='Verified platform userCode (not a nickname or email)')
args = parser.parse_args()
if not args.user_code.strip() or not args.user_code.isprintable():
parser.error('Invalid userCode')
if storage.load(args.task_id).get('id') != args.task_id:
parser.error('Task does not exist')
owner = owner_key(args.user_code)
if args.command == 'bind':
bind(args.task_id, owner)
print('已绑定任务 ' + args.task_id)
else:
with connection() as db:
count = db.execute('UPDATE projects SET attempted=0, marker=? WHERE task_id=? AND owner=? AND attempted=1 AND project_code IS NULL',
('AI PCB · ' + secrets.token_hex(16), args.task_id, owner)).rowcount
if not count:
parser.error('此账号和任务没有待核实的云工程创建记录。')
print('已允许该任务再次申请云工程。')