2026-10-23 09:03:27 +08:00
""" Opt-in real business API regression against a localhost-only scanner fixture.
- - manage - dev temporarily restarts only this project ' s idle dev backend, builds the
current sources , and supplies ephemeral scanner settings . Finally restores normal
dev settings and cleans only this run ' s marked business data. No hardware used.
"""
from __future__ import annotations
import argparse
import datetime as dt
import io
import json
import os
from pathlib import Path
2026-11-02 17:38:34 +08:00
import shutil
2026-10-23 09:03:27 +08:00
import subprocess
import threading
import time
import urllib . parse
import urllib . request
import uuid
import struct
from concurrent . futures import ThreadPoolExecutor
from http . server import BaseHTTPRequestHandler , ThreadingHTTPServer
from bootstrap_db import insert_new
from cleanup_verification import cleanup
from robot_simulator import ResourceStore
from verify_cmvr_native import Client , require , safe
from verify_scan_only import ScanOnlyVerifier , NOTE
ROOT = Path ( __file__ ) . resolve ( ) . parents [ 1 ]
JAVA = Path ( os . environ . get ( ' JAVA_HOME ' , r ' C: \ Users \ Administrator \ .jdks \ ms-17.0.19 ' ) ) / ' bin/java.exe '
MAVEN = Path ( os . environ . get ( ' AM_FREESCAN_MAVEN ' , r ' E: \ soft \ IntelliJ IDEA 2025.2.5 \ plugins \ maven \ lib \ maven3 \ bin \ mvn.cmd ' ) )
REPORT = ROOT / ' .local/scanner-workflow-verification.json '
2026-11-02 17:38:34 +08:00
JAR = ROOT / ' am-backend/yudao-server/target-verification/yudao-server.jar '
2026-10-23 09:03:27 +08:00
CREATE_NO_WINDOW = getattr ( subprocess , ' CREATE_NO_WINDOW ' , 0 )
PLY = b ' ply \n format ascii 1.0 \n element vertex 3 \n property float x \n property float y \n property float z \n end_header \n 0 0 0 \n 1 0 0 \n 0 1 0 \n '
STL = b ' solid fixture \n facet normal 0 0 1 \n outer loop \n vertex 0 0 0 \n vertex 1 0 0 \n vertex 0 1 0 \n endloop \n endfacet \n endsolid fixture \n '
2026-11-02 17:38:34 +08:00
def require_idle_scanner ( client , allow_unreachable = False ) :
response = client . native ( ' GET ' , ' /scanner/status ' , expected = None )
if response . get ( ' code ' ) == 200 :
status = response [ ' data ' ]
require ( all ( status . get ( k ) is False for k in ( ' scanning ' , ' busy ' , ' stateUncertain ' , ' restartRequired ' ) ) and not status . get ( ' calibrationActive ' ) , ' Physical scanner is not confirmed idle ' )
else :
require ( allow_unreachable and response . get ( ' code ' ) in ( 503 , 504 ) and response . get ( ' scannerCode ' ) == ' transport_uncertain ' , ' Physical scanner status cannot be verified; fixture opt-in required ' )
2026-10-23 09:03:27 +08:00
def wait_for ( fn , timeout = 30 , message = ' condition ' ) :
deadline = time . monotonic ( ) + timeout
last = None
while time . monotonic ( ) < deadline :
try :
last = fn ( )
if last :
return last
except ( OSError , ValueError ) :
pass
time . sleep ( .2 )
raise AssertionError ( ' Timed out: ' + message + ' ' + str ( last ) )
class Supplier :
def __init__ ( self , preview_width = 8 ) :
self . key = uuid . uuid4 ( ) . hex
self . session = uuid . uuid4 ( ) . hex
self . project = ' '
2026-11-02 17:38:34 +08:00
self . scan_mode = ' trak ' ; self . scan_type = ' mesh ' ; self . scan_device = ' scanner '
self . project_has_acquisition = False ; self . framework_has_acquisition = False
self . framework_optimized = False ; self . framework_imported = False ; self . framework_file_count = 0
self . framework_uploads = { }
self . device_online = True ; self . initialized = True
2026-10-23 09:03:27 +08:00
self . scanning = False
self . preview = False
2026-10-26 11:04:07 +08:00
self . mesh = ' none '
2026-10-23 09:03:27 +08:00
self . uncertain = False
self . hold_controls = False
self . failed_operation = None
2026-10-26 11:04:07 +08:00
self . fail_redundant_stop = False
self . project_delay_seconds = 0
self . project_building = False
self . project_timers = [ ]
2026-10-23 09:03:27 +08:00
self . tasks = { }
self . files = { }
2026-11-02 17:38:34 +08:00
self . file_names = { }
self . gets = [ ]
2026-10-23 09:03:27 +08:00
self . posts = [ ]
self . sequence = 1
self . lock = threading . RLock ( )
2026-10-26 11:04:07 +08:00
self . closed = threading . Event ( )
2026-10-23 09:03:27 +08:00
from PIL import Image
pixels = io . BytesIO ( )
if preview_width > 8 :
Image . effect_noise ( ( preview_width , round ( preview_width * 9 / 16 ) ) , 60 ) . convert ( ' RGB ' ) . save ( pixels , format = ' JPEG ' , quality = 85 )
else : Image . new ( ' RGB ' , ( 8 , 8 ) , ' #224466 ' ) . save ( pixels , format = ' JPEG ' )
self . jpeg = pixels . getvalue ( )
supplier = self
class Handler ( BaseHTTPRequestHandler ) :
def log_message ( self , * _ ) : pass
def reply ( self , value , code = 200 , content = ' application/json ' , headers = None ) :
payload = value if isinstance ( value , bytes ) else json . dumps ( value ) . encode ( )
self . send_response ( code )
self . send_header ( ' Content-Type ' , content )
self . send_header ( ' Content-Length ' , str ( len ( payload ) ) )
for k , v in ( headers or { } ) . items ( ) : self . send_header ( k , str ( v ) )
self . end_headers ( )
self . wfile . write ( payload )
def do_GET ( self ) :
2026-10-26 11:04:07 +08:00
if self . path == ' /api/v1/preview/stream ' :
if self . headers . get ( ' Authorization ' ) != ' Bearer ' + supplier . key :
return self . reply ( { ' error ' : { ' code ' : ' unauthorized ' } } , 401 )
self . send_response ( 200 )
self . send_header ( ' Content-Type ' , ' multipart/x-mixed-replace; boundary=frame ' )
self . end_headers ( )
try :
while not supplier . closed . wait ( .05 ) :
with supplier . lock :
supplier . sequence + = 1
sequence = supplier . sequence ; payload = supplier . jpeg
self . wfile . write ( ( ' --frame \r \n Content-Type: image/jpeg \r \n Content-Length: ' + str ( len ( payload ) ) + ' \r \n X-Frame-Sequence: ' + str ( sequence ) + ' \r \n \r \n ' ) . encode ( ) + payload + b ' \r \n ' )
self . wfile . flush ( )
except ( ConnectionError , OSError ) : pass
return
2026-10-23 09:03:27 +08:00
with supplier . lock :
2026-10-26 11:04:07 +08:00
if self . path != ' / ' and self . headers . get ( ' Authorization ' ) != ' Bearer ' + supplier . key :
2026-10-23 09:03:27 +08:00
return self . reply ( { ' error ' : { ' code ' : ' unauthorized ' } } , 401 )
2026-11-02 17:38:34 +08:00
supplier . gets . append ( self . path )
2026-10-23 09:03:27 +08:00
if self . path == ' /api/v1/status ' :
2026-11-02 17:38:34 +08:00
return self . reply ( dict ( sessionId = supplier . session , projectId = supplier . project or None ,
2026-10-23 09:03:27 +08:00
projectReady = bool ( supplier . project ) , scanning = supplier . scanning ,
2026-10-26 11:04:07 +08:00
previewEnabled = supplier . preview , busy = supplier . hold_controls or supplier . project_building , stateUncertain = supplier . uncertain ,
2026-11-02 17:38:34 +08:00
restartRequired = False , deviceOnline = supplier . device_online , initialized = supplier . initialized , state = ' ready ' if supplier . initialized else ' disconnected ' , meshState = supplier . mesh ,
scanMode = supplier . scan_mode , scanType = supplier . scan_type , scanDevice = supplier . scan_device ,
projectHasAcquisition = supplier . project_has_acquisition , frameworkHasAcquisition = supplier . framework_has_acquisition ,
frameworkOptimized = supplier . framework_optimized , frameworkImported = supplier . framework_imported , frameworkFileCount = supplier . framework_file_count ) )
if self . path == ' /api/v1/data/scene ' :
return self . reply ( dict ( available = bool ( supplier . project ) , projectUuid = uuid . uuid5 ( uuid . NAMESPACE_URL , supplier . project ) . hex ,
cloudUuid = ' 11111111-1111-1111-1111-111111111111 ' , pointIdsAvailable = False , pointCount = 3 , markerCount = 3 ) )
2026-10-23 09:03:27 +08:00
if self . path == ' /api/v1/preview/metrics ' :
return self . reply ( dict ( latestSequence = supplier . sequence , encoderRunning = supplier . preview ) )
if self . path == ' /api/v1/preview/image ' :
supplier . sequence + = 1
return self . reply ( supplier . jpeg , content = ' image/jpeg ' , headers = { ' X-Frame-Sequence ' : supplier . sequence } )
if self . path . startswith ( ' /api/v1/tasks/ ' ) :
result = supplier . tasks . get ( self . path . rsplit ( ' / ' , 1 ) [ 1 ] )
return self . reply ( result or { ' error ' : { ' code ' : ' task_not_found ' } } , 200 if result else 404 )
if self . path . startswith ( ' /api/v1/files/ ' ) :
2026-11-02 17:38:34 +08:00
file_id = self . path . rsplit ( ' / ' , 1 ) [ 1 ]
payload = supplier . files . get ( file_id )
name = supplier . file_names . get ( file_id )
headers = { ' Content-Disposition ' : " attachment; filename*=UTF-8 ' ' " + urllib . parse . quote ( name , safe = ' ' ) } if name else None
return self . reply ( payload or b ' ' , 200 if payload else 404 , ' application/octet-stream ' , headers )
2026-10-23 09:03:27 +08:00
return self . reply ( dict ( service = ' LOCALHOST REGRESSION FIXTURE ' , running = True ) )
def do_POST ( self ) :
with supplier . lock :
2026-10-26 11:04:07 +08:00
if self . headers . get ( ' Authorization ' ) != ' Bearer ' + supplier . key :
2026-10-23 09:03:27 +08:00
return self . reply ( { ' error ' : { ' code ' : ' unauthorized ' } } , 401 )
2026-11-02 17:38:34 +08:00
payload = self . rfile . read ( int ( self . headers . get ( ' Content-Length ' , 0 ) ) )
if self . path == ' /api/v1/framework/files ' :
name = urllib . parse . unquote ( self . headers . get ( ' X-File-Name ' , ' ' ) ) ; file_id = uuid . uuid4 ( ) . hex
supplier . framework_uploads [ file_id ] = dict ( name = name , bytes = payload )
supplier . posts . append ( dict ( path = self . path , body = dict ( name = name , size = len ( payload ) ) ) )
return self . reply ( dict ( fileId = file_id , name = name , size = len ( payload ) , uploadedUtc = dt . datetime . now ( dt . timezone . utc ) . isoformat ( ) ) , 201 )
body = json . loads ( payload )
2026-10-23 09:03:27 +08:00
supplier . posts . append ( dict ( path = self . path , body = body ) )
task_id = uuid . uuid4 ( ) . hex
result = { }
2026-10-26 11:04:07 +08:00
failure = supplier . failed_operation == self . path or ( supplier . fail_redundant_stop and self . path == ' /api/v1/scan/stop ' and not supplier . scanning )
if supplier . failed_operation == self . path :
2026-10-23 09:03:27 +08:00
supplier . failed_operation = None
2026-11-02 17:38:34 +08:00
error_code = ' fixture_sdk_error '
def new_project ( ) :
supplier . project = result [ ' projectId ' ] ; supplier . mesh = ' none ' ; supplier . scan_mode = body . get ( ' mode ' , ' trak ' )
supplier . scan_type = ' mesh ' ; supplier . scan_device = ' scanner ' ; supplier . project_has_acquisition = False
supplier . framework_has_acquisition = False ; supplier . framework_optimized = False ; supplier . framework_imported = False ; supplier . framework_file_count = 0
2026-10-26 11:04:07 +08:00
if failure :
pass
2026-11-02 17:38:34 +08:00
elif self . path == ' /api/v1/device/connect ' : supplier . device_online = True ; supplier . initialized = True
elif self . path in ( ' /api/v1/device/disconnect ' , ' /api/v1/device/reconnect ' ) :
if body . get ( ' expectedProjectId ' ) != ( supplier . project or None ) or body . get ( ' expectedSessionId ' ) != supplier . session :
failure = True ; error_code = ' project_changed '
else :
reconnect = self . path . endswith ( ' /reconnect ' ) ; supplier . device_online = reconnect ; supplier . initialized = reconnect
supplier . project = ' ' ; supplier . mesh = ' none ' ; supplier . session = uuid . uuid4 ( ) . hex
2026-10-23 09:03:27 +08:00
elif self . path == ' /api/v1/projects ' :
2026-10-26 11:04:07 +08:00
result [ ' projectId ' ] = uuid . uuid4 ( ) . hex
if not supplier . project_delay_seconds :
2026-11-02 17:38:34 +08:00
new_project ( )
elif self . path == ' /api/v1/scan/type ' :
requested = body [ ' scanType ' ] ; device = body . get ( ' device ' , ' tracker ' if requested == ' photogrammetry ' else ' scanner ' if requested == ' markers ' else supplier . scan_device )
if not supplier . project or supplier . scanning or supplier . mesh != ' none ' : failure = True
elif device != supplier . scan_device and ( supplier . project_has_acquisition or supplier . framework_imported ) : failure = True ; error_code = ' project_data_present '
elif device != supplier . scan_device and not body . get ( ' confirm ' ) : failure = True
elif requested == ' photogrammetry ' and ( supplier . scan_mode != ' trak ' or device != ' tracker ' ) : failure = True
elif requested == ' markers ' and ( supplier . scan_mode != ' laser ' or device != ' scanner ' ) : failure = True
else : supplier . scan_type = requested ; supplier . scan_device = device
elif self . path == ' /api/v1/framework/import ' :
ids = body [ ' fileIds ' ]
if supplier . scanning or supplier . scan_mode != ' trak ' or supplier . scan_type != ' mesh ' or supplier . scan_device != ' scanner ' or supplier . mesh != ' none ' or any ( i not in supplier . framework_uploads for i in ids ) : failure = True
else : supplier . framework_imported = True ; supplier . framework_file_count = len ( ids )
elif self . path == ' /api/v1/framework/optimize ' :
if supplier . scanning or supplier . scan_mode != ' trak ' or supplier . scan_type != ' photogrammetry ' or supplier . scan_device != ' tracker ' or not supplier . framework_has_acquisition or supplier . mesh != ' none ' : failure = True
else : supplier . framework_optimized = True
elif self . path == ' /api/v1/scan/start ' :
supplier . scanning = True ; supplier . project_has_acquisition = True
if supplier . scan_type == ' photogrammetry ' : supplier . framework_has_acquisition = True ; supplier . framework_optimized = False
2026-10-23 09:03:27 +08:00
elif self . path == ' /api/v1/scan/stop ' : supplier . scanning = False
elif self . path == ' /api/v1/preview/start ' : supplier . preview = True
elif self . path == ' /api/v1/preview/stop ' : supplier . preview = False
2026-10-26 11:04:07 +08:00
elif self . path == ' /api/v1/mesh ' : supplier . mesh = ' preview '
elif self . path == ' /api/v1/mesh/confirm ' : supplier . mesh = ' confirmed '
elif self . path == ' /api/v1/mesh/undo ' : supplier . mesh = ' none '
2026-10-23 09:03:27 +08:00
elif self . path in ( ' /api/v1/exports ' , ' /api/v1/data/snapshots ' ) :
2026-10-26 11:04:07 +08:00
result [ ' files ' ] = [ ]
2026-11-02 17:38:34 +08:00
if self . path . endswith ( ' exports ' ) and body . get ( ' formats ' ) == [ ' P3 ' ] and not ( supplier . scan_mode == ' trak ' and supplier . scan_type == ' photogrammetry ' and supplier . scan_device == ' tracker ' and supplier . framework_has_acquisition and supplier . framework_optimized and not supplier . scanning ) : failure = True
2026-10-26 11:04:07 +08:00
for ext in ( [ str ( f ) . lower ( ) for f in body . get ( ' formats ' , [ ' stl ' ] ) ] if self . path . endswith ( ' exports ' ) else [ ' ply ' ] ) :
2026-11-02 17:38:34 +08:00
payload = PLY if ext == ' ply ' else STL if ext == ' stl ' else b ' FRAMEWORK FIXTURE \n '
2026-10-26 11:04:07 +08:00
file_id = uuid . uuid4 ( ) . hex
supplier . files [ file_id ] = payload
result [ ' files ' ] . append ( dict ( fileId = file_id , name = ' fixture. ' + ext , format = ext ,
bytes = len ( payload ) , downloadUrl = ' /api/v1/files/ ' + file_id ) )
pending = self . path == ' /api/v1/projects ' and supplier . project_delay_seconds and not failure
supplier . tasks [ task_id ] = dict ( taskId = task_id , state = ' failed ' if failure else ' running ' if pending else ' succeeded ' ,
2026-11-02 17:38:34 +08:00
result = None if pending else result , error = dict ( code = error_code , message = ' Intentional regression failure ' , httpStatus = 409 ) if failure else None )
2026-10-26 11:04:07 +08:00
if pending :
supplier . project_building = True
def complete_project ( ) :
with supplier . lock :
if supplier . closed . is_set ( ) : return
2026-11-02 17:38:34 +08:00
new_project ( ) ; supplier . project_building = False
2026-10-26 11:04:07 +08:00
supplier . tasks [ task_id ] . update ( state = ' succeeded ' , result = result )
timer = threading . Timer ( supplier . project_delay_seconds , complete_project ) ; timer . daemon = True
supplier . project_timers . append ( timer ) ; timer . start ( )
2026-10-23 09:03:27 +08:00
self . reply ( dict ( taskId = task_id , statusUrl = ' /api/v1/tasks/ ' + task_id ) , 202 )
self . server = ThreadingHTTPServer ( ( ' 127.0.0.1 ' , 0 ) , Handler )
self . port = self . server . server_address [ 1 ]
def start ( self ) : threading . Thread ( target = self . server . serve_forever , daemon = True ) . start ( )
2026-10-26 11:04:07 +08:00
def close ( self ) :
self . closed . set ( )
for timer in self . project_timers : timer . cancel ( )
self . server . shutdown ( ) ; self . server . server_close ( )
2026-10-23 09:03:27 +08:00
def count ( self , path ) : return sum ( p [ ' path ' ] == path for p in self . posts )
def scanner_flow ( sleep_ms = 5000 , missing = None ) :
specs = [ ( ' connect ' , ' SCANNER_INITIALIZE ' , { } ) , ( ' project ' , ' SCANNER_CREATE_PROJECT ' , { ' name ' : ' REGRESSION ' , ' mode ' : ' laser ' } ) ,
( ' parameters ' , ' SCANNER_PARAMETERS ' , { ' brightness ' : 10 } ) , ( ' preview ' , ' SCANNER_PREVIEW_START ' , { } ) ,
( ' startScan ' , ' SCANNER_START ' , { } ) , ( ' wait ' , ' SLEEP ' , None ) ,
( ' snapshot ' , ' SCANNER_SNAPSHOT ' , { ' maxPoints ' : 1000 , ' include ' : [ ' points ' , ' markers ' , ' meshes ' ] } ) ,
( ' stopScan ' , ' SCANNER_STOP ' , { } ) , ( ' mesh ' , ' SCANNER_MESH ' , { } ) ,
( ' confirmMesh ' , ' SCANNER_MESH_CONFIRM ' , { } ) , ( ' export ' , ' SCANNER_EXPORT ' , { ' name ' : ' REGRESSION ' , ' formats ' : [ ' stl ' ] } ) ,
( ' previewStop ' , ' SCANNER_PREVIEW_STOP ' , { } ) ]
nodes = [ dict ( id = ' start ' , type = ' start ' , properties = dict ( name = ' 开始 ' , action = ' START ' , schemaVersion = 2 ,
inputParams = [ dict ( name = ' verificationMarker ' , type = ' String ' , required = True ) ] ,
resourceRoles = [ dict ( roleKey = ' scanner ' , displayName = ' 扫描工位 ' , required = True ,
deviceSlots = [ dict ( slotKey = ' scanner ' , displayName = ' 扫描仪 ' , deviceKind = 14 , required = True , allowReuse = False ) ] ) ] ) ) ]
for identifier , action , body in specs :
p = dict ( name = identifier , action = action , inputParams = [ ] , nodeParams = [ ] )
if action == ' SLEEP ' : p [ ' nodeParams ' ] = [ dict ( name = ' delayMs ' , type = ' input ' , input = str ( sleep_ms ) ) ]
else :
p . update ( nodeType = ' EDGE ' , executionTarget = dict ( roleKey = ' scanner ' , deviceSlotKey = ' scanner ' ) )
p [ ' nodeParams ' ] = [ dict ( name = ' requestJson ' , type = ' input ' , input = json . dumps ( body ) ) ,
dict ( name = ' timeoutMs ' , type = ' input ' , input = 120000 ) ]
if missing == identifier : p [ ' nodeParams ' ] . pop ( )
nodes . append ( dict ( id = identifier , type = ' sleep ' if action == ' SLEEP ' else ' serviceNode ' , properties = p ) )
nodes . append ( dict ( id = ' end ' , type = ' end ' , properties = dict ( name = ' 结束 ' , action = ' END ' ) ) )
for i , n in enumerate ( nodes ) : n . update ( x = 100 + 250 * i , y = 180 )
return dict ( schemaVersion = 2 , nodes = nodes , edges = [ dict ( id = ' edge- ' + str ( i ) , sourceNodeId = nodes [ i ] [ ' id ' ] , targetNodeId = nodes [ i + 1 ] [ ' id ' ] ) for i in range ( len ( nodes ) - 1 ) ] )
class ScannerVerifier ( ScanOnlyVerifier ) :
2026-10-26 11:04:07 +08:00
def __init__ ( self , prefix , supplier , report_path = REPORT ) :
2026-10-23 09:03:27 +08:00
super ( ) . __init__ ( )
self . prefix = prefix
self . sample_code = prefix + ' -SAMPLE '
self . robot = prefix + ' -robot '
self . device = prefix + ' -device '
self . supplier = supplier
2026-10-26 11:04:07 +08:00
self . report_path = Path ( report_path )
2026-10-23 09:03:27 +08:00
self . report . update ( prefix = prefix , hardwareRequests = 0 )
self . review_seconds = 0
self . live_review_seconds = 0
self . performance = False
def check ( self , name , * * detail ) :
self . report [ ' checks ' ] . append ( dict ( name = name , passed = True , * * safe ( detail ) ) )
print ( ' PASS ' , name , flush = True )
2026-10-26 11:04:07 +08:00
self . report_path . write_text ( json . dumps ( self . report , ensure_ascii = False , indent = 2 ) , encoding = ' utf-8 ' )
2026-10-23 09:03:27 +08:00
def create_scanner_case ( self , suffix , * * kwargs ) :
case = self . create_case ( suffix )
case [ ' graph ' ] = scanner_flow ( * * kwargs )
version = self . native . publish ( case [ ' itemId ' ] , case [ ' graph ' ] , NOTE )
case . update ( versionId = version [ ' id ' ] , versionNo = version [ ' versionNo ' ] )
return case
def prepare_body ( self , task_id , case_id , * * overrides ) :
options = dict ( robotId = self . robot , runParams = dict ( verificationMarker = ' LOCALHOST-SCANNER-FIXTURE ' ) ,
runtimeAssignments = [ dict ( roleKey = ' scanner ' , members = [ dict ( memberKey = ' scanner-1 ' , robotId = self . robot , devices = { ' scanner ' : self . device } ) ] ) ] )
options . update ( overrides )
return super ( ) . prepare_body ( task_id , case_id , * * options )
def assert_occupied ( self , task_id , occupied = True ) :
rows = self . native . db . select ( ' SELECT task_id FROM lab_scan_robot_occupation WHERE robot_id= %s AND deleted=0 ' , ( self . robot , ) )
require ( bool ( rows ) == occupied , ' Scanner occupation was not retained/released correctly ' )
if rows : require ( str ( rows [ 0 ] [ ' task_id ' ] ) == str ( task_id ) , ' Wrong occupation owner ' )
def waiting ( self , execution_id ) :
inst = self . binding ( execution_id ) [ ' cmvr_inst_id ' ]
wait_for ( lambda : any ( r . get ( ' action ' ) == ' SLEEP ' and str ( r . get ( ' status ' ) ) in ( ' RUNNING ' , ' 1 ' ) for r in self . native . node_logs ( inst ) ) , 20 , ' scan acquisition wait ' )
def view ( self , execution_id , suffix = ' ' , rejected = False ) :
return self . api ( ' GET ' , ' /lab/execution/scanner-view ' + suffix , query = dict ( executionId = execution_id ) , rejected = rejected )
def binary ( self , path , execution_id ) :
req = urllib . request . Request ( self . client . base_url + ' /admin-api/lab/execution/scanner-view ' + path + ' ? ' + urllib . parse . urlencode ( dict ( executionId = execution_id ) ) ,
headers = { ' tenant-id ' : ' 1 ' , ' Authorization ' : ' Bearer ' + self . client . _token } )
with urllib . request . urlopen ( req , timeout = 15 ) as response : return response . headers , response . read ( )
def snapshot ( self , execution_id , nonce ) :
req = urllib . request . Request ( self . client . base_url + ' /admin-api/lab/execution/scanner-view/snapshot? ' + urllib . parse . urlencode ( dict ( executionId = execution_id ) ) ,
method = ' POST ' , data = b ' ' , headers = { ' tenant-id ' : ' 1 ' , ' Authorization ' : ' Bearer ' + self . client . _token , ' X-Scanner-Command-Key ' : nonce } )
with urllib . request . urlopen ( req , timeout = 15 ) as response : result = json . load ( response )
require ( result [ ' code ' ] == 0 , ' Snapshot rejected: ' + str ( result ) )
return result [ ' data ' ]
def run_flow ( self ) :
bad = self . create_scanner_case ( ' missing-timeout ' , missing = ' startScan ' )
task = self . import_task ( ' bad ' , bad [ ' caseId ' ] , 1 )
self . prepare ( task , bad [ ' caseId ' ] , expect_ready = False )
result = self . api ( ' POST ' , ' /lab/scan-task/precheck ' , dict ( taskId = task ) )
require ( any ( not i [ ' passed ' ] and ' timeoutMs ' in i [ ' message ' ] for i in result [ ' items ' ] ) , ' Missing timeout not reported before start ' )
self . start_rejected ( task )
self . check ( ' 缺少扫描节点超时参数:预检和开始均阻止,未发送设备操作 ' )
good = self . create_scanner_case ( ' complete ' , sleep_ms = 5000 + self . live_review_seconds * 1000 )
task = self . import_task ( ' two-units ' , good [ ' caseId ' ] , 2 )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , self . prepare_body ( task , good [ ' caseId ' ] , runParams = { } ) )
result = self . api ( ' POST ' , ' /lab/scan-task/precheck ' , dict ( taskId = task ) )
require ( not result [ ' passed ' ] and any ( ' verificationMarker ' in i [ ' message ' ] for i in result [ ' items ' ] ) , ' Required start parameter not checked ' )
self . start_rejected ( task )
detail = self . prepare ( task , good [ ' caseId ' ] )
first , body = self . start ( task , detail [ ' units ' ] [ 0 ] )
require ( str ( self . api ( ' POST ' , ' /lab/scan-task/start-unit ' , body ) ) == str ( first ) , ' Repeated start duplicated execution ' )
self . waiting ( first )
view = wait_for ( lambda : self . view ( first ) if self . view ( first ) . get ( ' available ' ) else None , 10 , ' bound scanner view ' )
headers , jpeg = self . binary ( ' /image ' , first )
require ( headers [ ' Content-Type ' ] . startswith ( ' image/jpeg ' ) and jpeg == self . supplier . jpeg , ' Live image not relayed ' )
before = self . supplier . count ( ' /api/v1/data/snapshots ' )
nonce = uuid . uuid4 ( ) . hex
accepted = self . snapshot ( first , nonce )
again = self . snapshot ( first , nonce )
require ( again [ ' commandKey ' ] == accepted [ ' commandKey ' ] and self . supplier . count ( ' /api/v1/data/snapshots ' ) == before + 1 , ' Snapshot re-POSTed ' )
assets = wait_for ( lambda : self . view ( first , ' /assets ' ) , 10 , ' point cloud snapshot ' )
_ , payload = self . binary ( ' /asset/ ' + assets [ 0 ] [ ' fileId ' ] , first )
require ( payload == PLY , ' Point cloud bytes differ ' )
self . check ( ' 真实业务开始幂等、实时画面与本件绑定、点云快照重复点击仅下发一次 ' )
if self . performance :
def image_probe ( _ ) :
started = time . perf_counter ( )
_ , frame = self . binary ( ' /image ' , first )
require ( frame == self . supplier . jpeg , ' Concurrent image differed ' )
return round ( ( time . perf_counter ( ) - started ) * 1000 , 2 )
with ThreadPoolExecutor ( max_workers = 8 ) as pool : latencies = sorted ( pool . map ( image_probe , range ( 16 ) ) )
self . report [ ' imagePerformance ' ] = dict ( concurrentReaders = 8 , requests = 16 , bytes = len ( self . supplier . jpeg ) ,
p50Ms = latencies [ len ( latencies ) / / 2 ] , p95Ms = latencies [ - 2 ] , maxMs = latencies [ - 1 ] , hardwareRequests = 0 )
print ( ' IMAGE PERFORMANCE ' + json . dumps ( self . report [ ' imagePerformance ' ] ) , flush = True )
2026-10-26 11:04:07 +08:00
self . verify_stream ( first )
2026-10-23 09:03:27 +08:00
self . review_browser ( task , first , live = True )
self . api ( ' POST ' , ' /lab/scan-task/pause ' , dict ( taskId = task ) )
self . wait_execution ( first , ' PAUSED ' , 5 )
require ( not self . supplier . scanning , ' Pause did not stop acquisition ' )
self . assert_occupied ( task )
self . api ( ' POST ' , ' /lab/scan-task/resume ' , dict ( taskId = task ) )
require ( self . supplier . scanning , ' Resume did not restore acquisition ' )
self . wait_execution ( first , timeout = 30 + self . live_review_seconds )
self . verify_logs ( first )
require ( not self . supplier . scanning , ' Completion left scanner acquiring ' )
self . assert_occupied ( task )
history = self . view ( first )
require ( not history [ ' available ' ] and history [ ' state ' ] == ' history ' , ' Historical execution attached to live scanner ' )
files = self . view ( first , ' /assets ' )
require ( any ( f . get ( ' format ' ) == ' stl ' for f in files ) , ' Completed mesh export absent ' )
self . check ( ' 暂停停止采集并保留占用、恢复同一工程、首件完成保留任务资源与成果 ' )
self . review_browser ( task , first )
second , _ = self . start ( task , self . task ( task ) [ ' units ' ] [ 1 ] )
self . waiting ( second )
require ( self . view ( second ) [ ' projectId ' ] != view [ ' projectId ' ] , ' Second sample reused first project binding ' )
require ( self . view ( second , ' /assets ' ) == [ ] , ' Second sample sees previous assets ' )
self . view ( first , ' /image ' , rejected = True )
self . api ( ' GET ' , ' /lab/execution/scanner-view/asset/ ' + files [ 0 ] [ ' fileId ' ] , query = dict ( executionId = second ) , rejected = True )
self . wait_execution ( second , timeout = 30 + self . live_review_seconds )
self . verify_logs ( second )
wait_for ( lambda : self . task ( task ) [ ' task ' ] [ ' status ' ] == ' COMPLETED ' , 10 , ' two-unit task completion ' )
self . assert_occupied ( task , False )
self . active_tasks . discard ( task )
self . check ( ' 第二件独立工程,跨件图像和文件访问阻止,全部完成后释放资源 ' )
fail = self . create_scanner_case ( ' sdk-failure ' , sleep_ms = 200 )
task = self . import_task ( ' sdk-failure ' , fail [ ' caseId ' ] , 1 )
detail = self . prepare ( task , fail [ ' caseId ' ] )
self . supplier . failed_operation = ' /api/v1/parameters '
execution , _ = self . start ( task , detail [ ' units ' ] [ 0 ] )
self . wait_execution ( execution , ' FAILED ' , 30 )
self . assert_occupied ( task )
self . wait_stop_confirmation ( task )
detail = self . task ( task )
execution , _ = self . start ( task , detail [ ' units ' ] [ 0 ] , reason = ' LOCALHOST regression retry ' )
self . wait_execution ( execution , timeout = 30 )
self . assert_occupied ( task , False )
self . active_tasks . discard ( task )
self . check ( ' 设备任务HTTP成功但SDK失败时整件失败, 人工重试建立新执行并成功 ' )
task = self . import_task ( ' cancel-stop ' , good [ ' caseId ' ] , 1 )
detail = self . prepare ( task , good [ ' caseId ' ] )
execution , _ = self . start ( task , detail [ ' units ' ] [ 0 ] )
self . waiting ( execution )
self . supplier . uncertain = True
self . api ( ' POST ' , ' /lab/scan-task/cancel ' , dict ( taskId = task , reason = ' LOCALHOST stop uncertainty regression ' ) )
require ( self . task ( task ) [ ' config ' ] [ ' stopPending ' ] , ' Unconfirmed stop silently released resources ' )
self . assert_occupied ( task )
self . supplier . uncertain = False
self . api ( ' POST ' , ' /lab/scan-task/confirm-stop ' , dict ( taskId = task , reason = ' LOCALHOST fixture status restored ' ) )
wait_for ( lambda : not self . task ( task ) [ ' config ' ] . get ( ' stopPending ' ) , 15 , ' stop acknowledgement ' )
self . assert_occupied ( task , False )
require ( not self . supplier . scanning , ' Cancel failed to stop scanner ' )
self . active_tasks . discard ( task )
self . check ( ' 取消时停止未确认保留资源,状态恢复并确认停止后释放 ' )
2026-10-26 11:04:07 +08:00
def verify_stream ( self , execution ) :
path = ' /admin-api/lab/execution/scanner-view/stream? ' + urllib . parse . urlencode ( { ' executionId ' : execution } )
request = urllib . request . Request ( self . client . base_url + path , headers = { ' Authorization ' : ' Bearer ' + self . client . _token , ' tenant-id ' : ' 1 ' } )
sequences = [ ]
with urllib . request . urlopen ( request , timeout = 15 ) as response :
require ( response . headers . get ( ' Content-Type ' , ' ' ) . startswith ( ' multipart/x-mixed-replace ' ) , ' Live route did not return MJPEG ' )
for _ in range ( 3 ) :
require ( response . readline ( ) . strip ( ) == b ' --scanframe ' , ' Unexpected platform stream boundary ' )
headers = { }
while True :
line = response . readline ( )
require ( line , ' Truncated MJPEG headers ' )
if line == b ' \r \n ' : break
key , value = line . decode ( ' ascii ' ) . split ( ' : ' , 1 ) ; headers [ key . lower ( ) ] = value . strip ( )
require ( response . read ( int ( headers [ ' content-length ' ] ) ) == self . supplier . jpeg , ' MJPEG frame bytes changed ' )
sequences . append ( int ( headers [ ' x-frame-sequence ' ] ) )
require ( response . read ( 2 ) == b ' \r \n ' , ' Invalid frame terminator ' )
require ( all ( a < b for a , b in zip ( sequences , sequences [ 1 : ] ) ) , ' Stream sequences did not advance ' )
self . check ( ' 真实MJPEG流连续三帧完整, 帧编号递增, 关闭后不阻塞后续设备查询 ' )
2026-10-23 09:03:27 +08:00
def verify_logs ( self , execution ) :
inst = self . binding ( execution ) [ ' cmvr_inst_id ' ]
full = self . client . native ( ' GET ' , ' /test/inst/log/detail ' , query = dict ( instId = inst , pageNum = 1 , pageSize = 1000 ) )
rows = full [ ' rows ' ]
require ( rows and all ( str ( r . get ( ' status ' ) ) . upper ( ) in ( ' SUCCESS ' , ' SUCCEEDED ' , ' SKIPPED ' , ' 0 ' ) for r in rows ) , ' Successful execution has unfinished/failed node logs ' )
cursor = rows [ len ( rows ) / / 2 ] [ ' id ' ]
delta = self . client . native ( ' GET ' , ' /test/inst/log/detail ' , query = dict ( instId = inst , afterId = cursor , pageNum = 1 , pageSize = 1000 ) )
require ( [ str ( r [ ' id ' ] ) for r in delta [ ' rows ' ] ] == [ str ( r [ ' id ' ] ) for r in rows if int ( r [ ' id ' ] ) > = int ( cursor ) ] , ' Incremental log query lost or duplicated rows ' )
rejected = self . client . native ( ' GET ' , ' /test/inst/log/detail ' , query = dict ( instId = inst , afterId = - 1 ) , expected = None )
require ( rejected [ ' code ' ] not in ( 0 , 200 , 500 ) , ' Negative log cursor was not rejected ' )
self . report . setdefault ( ' completedExecutionLogs ' , [ ] ) . append ( dict ( executionId = str ( execution ) , nodes = len ( rows ) , incrementalNodes = len ( delta [ ' rows ' ] ) , allTerminal = True ) )
def review_browser ( self , task , execution , live = False ) :
seconds = self . live_review_seconds if live else self . review_seconds
if not seconds : return
# Inspect immutable files after the first item completes, while waiting
# for the next item. Never race a human review against a control POST.
phase = ' scanner-live-browser-review ' if live else ' scanner-browser-review '
review = ROOT / ' .local ' / f ' { phase } .json '
done = ROOT / ' .local ' / f ' { phase } .done '
review . write_text ( json . dumps ( dict ( prefix = self . prefix , taskId = str ( task ) , executionId = str ( execution ) ) , ensure_ascii = False ) , encoding = ' utf-8 ' )
print ( ' BROWSER REVIEW READY: ' + str ( review ) , flush = True )
deadline = time . monotonic ( ) + seconds
try :
while time . monotonic ( ) < deadline :
if done . exists ( ) and done . read_text ( encoding = ' utf-8 ' ) . strip ( ) == self . prefix : break
time . sleep ( .2 )
finally :
review . unlink ( missing_ok = True )
if done . exists ( ) and done . read_text ( encoding = ' utf-8 ' ) . strip ( ) == self . prefix : done . unlink ( )
def start_rejected ( self , task ) :
body = dict ( taskId = task , unitId = self . task ( task ) [ ' units ' ] [ 0 ] [ ' id ' ] , expectedRevision = self . task ( task ) [ ' config ' ] [ ' revision ' ] ,
loadedConfirmed = True , idempotencyKey = uuid . uuid4 ( ) . hex , physicalSerial = ' LOCALHOST-FIXTURE ' )
before = len ( self . supplier . posts )
self . api ( ' POST ' , ' /lab/scan-task/start-unit ' , body , rejected = True )
require ( len ( self . supplier . posts ) == before , ' Rejected start reached scanner ' )
class LocalResources :
2026-11-02 17:38:34 +08:00
def __init__ ( self , prefix , port , preserved_leases = None ) :
2026-10-23 09:03:27 +08:00
self . store = ResourceStore ( )
self . prefix = prefix
self . robot = prefix + ' -robot '
self . device = prefix + ' -device '
self . port = port
self . stop = threading . Event ( )
self . error = None
2026-11-02 17:38:34 +08:00
self . preserved_leases = preserved_leases
2026-10-23 09:03:27 +08:00
def provision ( self ) :
with self . store . cursor ( ) as c :
for table in ( ' lab_resource_occupation ' , ' lab_scan_robot_occupation ' ) :
2026-11-02 17:38:34 +08:00
if table == ' lab_resource_occupation ' and self . preserved_leases is not None :
require ( all ( row [ ' status ' ] == ' STOP_PENDING ' and row [ ' owner_key ' ] . startswith ( ' NATIVE: ' ) for row in self . preserved_leases ) , ' Only exact pending native-trial leases may be preserved ' )
c . execute ( ' SELECT owner_key,resource_type,resource_id,status FROM lab_resource_occupation WHERE deleted=0 ORDER BY owner_key,resource_type,resource_id ' )
require ( list ( c . fetchall ( ) ) == self . preserved_leases , ' Original pending-stop leases changed before fixture provisioning ' )
continue
2026-10-23 09:03:27 +08:00
c . execute ( ' SELECT COUNT(*) n FROM ' + table + ' WHERE deleted=0 ' )
require ( c . fetchone ( ) [ ' n ' ] == 0 , ' Dev backend has active resource occupations ' )
insert_new ( c , ' iot_robot ' , dict ( id = uuid . uuid4 ( ) . hex , robot_id = self . robot , robot_code = self . robot ,
robot_name = self . prefix , robot_type = ' GENERIC ' , archived_status = ' 0 ' , connect_status = ' 1 ' ,
create_by = self . prefix , update_by = self . prefix , remark = ' LOCALHOST SCANNER REGRESSION ' ) , [ ' robot_id ' ] )
insert_new ( c , ' iot_device ' , dict ( id = uuid . uuid4 ( ) . hex , robot_id = self . robot , device_id = self . device , device_name = self . prefix ,
2026-11-02 17:38:34 +08:00
device_kind = 14 , device_type = ' FreeScan HTTP API ' , device_index = 0 , enabled = ' 1 ' , online_status = ' 1 ' ,
2026-10-23 09:03:27 +08:00
has_error = ' 0 ' , manager_state = 1 , health_status = 1 , create_by = self . prefix , update_by = self . prefix , remark = ' LOCALHOST SCANNER REGRESSION ' ) , [ ' robot_id ' , ' device_id ' ] )
self . store . connection . commit ( )
self . beat ( )
self . thread = threading . Thread ( target = self . heartbeat , daemon = True )
self . thread . start ( )
def beat ( self ) :
now = dt . datetime . now ( )
with self . store . cursor ( ) as c :
c . execute ( " UPDATE iot_robot SET connect_status= ' 1 ' ,ip_address= ' 127.0.0.1 ' ,port= %s ,last_heartbeat_time= %s ,runtime_status= ' 2 ' ,update_time= %s WHERE robot_id= %s AND create_by= %s " , ( self . port , now , now , self . robot , self . prefix ) )
c . execute ( " UPDATE iot_device SET online_status= ' 1 ' ,last_seen_time= %s ,status_updated_time= %s ,update_time= %s WHERE robot_id= %s AND device_id= %s AND create_by= %s " , ( now , now , now , self . robot , self . device , self . prefix ) )
self . store . connection . commit ( )
def heartbeat ( self ) :
while not self . stop . wait ( 1 ) :
try : self . beat ( )
except Exception as e : self . error = str ( e ) ; return
def close ( self ) :
self . stop . set ( )
if hasattr ( self , ' thread ' ) : self . thread . join ( 5 )
with self . store . cursor ( ) as c :
c . execute ( ' SELECT COUNT(*) n FROM lab_resource_occupation WHERE robot_id= %s AND deleted=0 ' , ( self . robot , ) )
require ( c . fetchone ( ) [ ' n ' ] == 0 , ' Scanner still occupied: refusing fixture removal ' )
c . execute ( ' SELECT lab_device_id FROM lab_runtime_device_link WHERE robot_id= %s AND device_id= %s ' , ( self . robot , self . device ) )
for r in c . fetchall ( ) :
c . execute ( " DELETE FROM lab_device WHERE id= %s AND external_type= ' CMVR ' AND external_id IN (SELECT id FROM iot_device WHERE robot_id= %s AND device_id= %s AND create_by= %s ) " ,
( r [ ' lab_device_id ' ] , self . robot , self . device , self . prefix ) )
c . execute ( ' DELETE FROM lab_runtime_device_link WHERE robot_id= %s AND device_id= %s ' , ( self . robot , self . device ) )
c . execute ( ' DELETE FROM iot_device WHERE robot_id= %s AND device_id= %s AND create_by= %s ' , ( self . robot , self . device , self . prefix ) )
c . execute ( ' DELETE FROM iot_robot WHERE robot_id= %s AND create_by= %s ' , ( self . robot , self . prefix ) )
self . store . connection . commit ( )
self . store . connection . close ( )
class DevBackend :
2026-11-02 17:38:34 +08:00
def __init__ ( self , jar = None ) :
self . process = None ; self . log = None ; self . changed = False
self . jar = Path ( jar or JAR ) . resolve ( )
require ( self . jar in { JAR . resolve ( ) , ( ROOT / ' am-backend/yudao-server/target/yudao-server.jar ' ) . resolve ( ) } , ' Unexpected project backend package ' )
self . runtime_jar = ROOT / ' .local/backend-runtime/yudao-server.jar '
2026-10-23 09:03:27 +08:00
def stop_existing ( self ) :
# Exact project JAR match; no other Java process is touched.
2026-11-02 17:38:34 +08:00
script = " $p=Get-CimInstance Win32_Process -Filter \" name = ' java.exe ' \" | Where-Object { $_.CommandLine -like ' *-jar* ' -and ($_.CommandLine.Contains( ' " + str ( self . jar ) + " ' ) -or $_.CommandLine.Contains( ' " + str ( self . runtime_jar ) + " ' )) }; if (@($p).Count -gt 1) { throw ' Multiple project backends ' }; $listeners=@(Get-NetTCPConnection -LocalPort 48090 -State Listen -ErrorAction SilentlyContinue); if ($listeners | Where-Object { $_.OwningProcess -notin @($p.ProcessId) }) { throw ' Port 48090 belongs to an unrecognized process; no process stopped ' }; $p | ForEach-Object { Stop-Process -Id $_.ProcessId -Force } "
2026-10-23 09:03:27 +08:00
subprocess . run ( [ ' powershell ' , ' -NoProfile ' , ' -Command ' , script ] , check = True , creationflags = CREATE_NO_WINDOW )
self . changed = True
time . sleep ( 2 )
def build ( self ) :
print ( ' Building current dev backend ' , flush = True )
env = os . environ . copy ( ) ; env [ ' JAVA_HOME ' ] = str ( JAVA . parent . parent )
with ( ROOT / ' .local/logs/scanner-workflow-build.log ' ) . open ( ' w ' ) as log :
2026-11-02 17:38:34 +08:00
subprocess . run ( [ str ( MAVEN ) , ' -Pisolated-verification ' , ' -pl ' , ' yudao-server ' , ' -am ' , ' package ' , ' -DskipTests ' ] , cwd = ROOT / ' am-backend ' , env = env , stdout = log , stderr = subprocess . STDOUT , check = True , creationflags = CREATE_NO_WINDOW )
def require_current_package ( self ) :
require ( self . jar . exists ( ) , ' No built backend JAR ' )
sources = [ p for p in ( ROOT / ' am-backend ' ) . rglob ( ' * ' ) if p . is_file ( ) and not any ( part . startswith ( ' target ' ) for part in p . parts ) and p . suffix in ( ' .java ' , ' .yaml ' , ' .yml ' , ' .xml ' , ' .proto ' ) ]
require ( all ( p . stat ( ) . st_mtime < = self . jar . stat ( ) . st_mtime for p in sources ) , ' Backend source changed; build is required ' )
2026-10-23 09:03:27 +08:00
def start ( self , supplier = None , resources = None ) :
runtime = json . loads ( ( ROOT / ' .local/runtime.json ' ) . read_text ( encoding = ' utf-8-sig ' ) )
require ( runtime [ ' mysql ' ] [ ' host ' ] == ' 192.168.28.10 ' and runtime [ ' mysql ' ] [ ' database ' ] == ' am-freescan ' , ' Unexpected database ' )
env = os . environ . copy ( )
env . update ( AM_FREESCAN_DB_USER = runtime [ ' mysql ' ] [ ' user ' ] , AM_FREESCAN_DB_PASSWORD = runtime [ ' mysql ' ] [ ' password ' ] , AM_FREESCAN_REDIS_PASSWORD = runtime [ ' redis ' ] [ ' password ' ] )
name = ' scanner-workflow-backend ' if supplier else ' backend-dev '
2026-11-02 17:38:34 +08:00
# Keep the executable separate from Maven output, which Windows may lock.
require ( self . jar . is_file ( ) and self . jar . stat ( ) . st_size > 100_000_000 , ' Backend package is incomplete ' )
self . runtime_jar . parent . mkdir ( parents = True , exist_ok = True )
shutil . copy2 ( self . jar , self . runtime_jar )
args = [ str ( JAVA ) , ' -Djdk.net.unixdomain.tmpdir= ' + str ( ROOT / ' .local/nio-tcp-fallback ' ) , ' -Dfile.encoding=UTF-8 ' , ' -jar ' , str ( self . runtime_jar ) ,
2026-10-23 09:03:27 +08:00
' --spring.profiles.active=dev ' , ' --spring.data.redis.database= ' + str ( runtime [ ' redis ' ] [ ' database ' ] ) ,
' --lab.artifact.nas-root= ' + str ( ROOT / ' .local/artifacts ' ) , ' --logging.file.name= ' + str ( ROOT / ' .local/logs ' / f ' { name } .log ' ) ]
if supplier : args + = [ ' --cmvr.scanner.host=127.0.0.1 ' , ' --cmvr.scanner.port= ' + str ( supplier . port ) , ' --cmvr.scanner.api-key= ' + supplier . key ,
' --cmvr.scanner.robot-id= ' + resources . robot , ' --cmvr.scanner.device-id= ' + resources . device , ' --cmvr.scanner.poll-interval-ms=30 ' ]
self . log = ( ROOT / ' .local/logs ' / f ' { name } -launcher.log ' ) . open ( ' w ' )
self . process = subprocess . Popen ( args , cwd = ROOT , env = env , stdout = self . log , stderr = subprocess . STDOUT , creationflags = CREATE_NO_WINDOW )
2026-11-02 17:38:34 +08:00
if not supplier : ( ROOT / ' .local/backend-dev.pid ' ) . write_text ( str ( self . process . pid ) , encoding = ' utf-8 ' )
2026-10-23 09:03:27 +08:00
def ready ( ) :
if self . process . poll ( ) is not None : raise RuntimeError ( ' Backend exited: ' + name )
with urllib . request . urlopen ( ' http://127.0.0.1:48090/admin-api/system/tenant/get-id-by-name?name=AM %20F reeScan ' , timeout = 2 ) as response : return response . status == 200
wait_for ( ready , 100 , ' backend startup ' )
print ( ' Dev backend ready ( ' + ( ' localhost fixture ' if supplier else ' normal configuration ' ) + ' ) ' , flush = True )
def stop ( self ) :
if self . process and self . process . poll ( ) is None : self . process . terminate ( ) ; self . process . wait ( 15 )
if self . log : self . log . close ( )
self . process = None
def main ( ) :
parser = argparse . ArgumentParser ( description = __doc__ )
parser . add_argument ( ' --manage-dev ' , action = ' store_true ' , required = True )
parser . add_argument ( ' --review-seconds ' , type = int , default = 0 , choices = range ( 0 , 301 ) , metavar = ' 0..300 ' )
parser . add_argument ( ' --live-review-seconds ' , type = int , default = 0 , choices = range ( 0 , 121 ) , metavar = ' 0..120 ' , help = ' Inspect a running acquisition during a longer deterministic SLEEP node ' )
parser . add_argument ( ' --skip-build ' , action = ' store_true ' , help = ' Reuse a JAR only when newer than backend sources ' )
parser . add_argument ( ' --performance ' , action = ' store_true ' , help = ' Use a million-point PLY and 1920x1080 JPEG; probe 8 concurrent viewers ' )
args = parser . parse_args ( )
if args . performance :
global PLY
count = 1000000
header = ( ' ply \n format binary_little_endian 1.0 \n element vertex ' + str ( count ) + ' \n property float x \n property float y \n property float z \n end_header \n ' ) . encode ( )
cloud = bytearray ( header ) ; cloud . extend ( bytes ( count * 12 ) )
for i in range ( count ) : struct . pack_into ( ' <fff ' , cloud , len ( header ) + i * 12 , i % 1000 , i / / 1000 , ( i % 101 ) / 100 )
PLY = bytes ( cloud )
prefix = ' E2E-SCANNER- ' + dt . datetime . now ( ) . strftime ( ' % m %d % H % M % S ' ) + ' - ' + uuid . uuid4 ( ) . hex [ : 4 ]
print ( ' Regression prefix: ' , prefix , flush = True )
supplier = Supplier ( 1920 if args . performance else 8 ) ; supplier . start ( )
resources = LocalResources ( prefix , supplier . port )
backend = DevBackend ( ) ; verifier = None ; passed = False
try :
resources . provision ( )
backend . stop_existing ( )
if args . skip_build :
2026-11-02 17:38:34 +08:00
backend . require_current_package ( )
2026-10-23 09:03:27 +08:00
else : backend . build ( )
backend . start ( supplier , resources )
verifier = ScannerVerifier ( prefix , supplier )
verifier . review_seconds = args . review_seconds
verifier . live_review_seconds = args . live_review_seconds
verifier . performance = args . performance
verifier . run_flow ( )
passed = True
finally :
try :
if verifier :
supplier . uncertain = False
for task in verifier . active_tasks :
state = verifier . task ( task )
if state [ ' task ' ] [ ' status ' ] not in ( ' COMPLETED ' , ' CANCELLED ' ) :
2026-11-02 17:38:34 +08:00
verifier . cancel_for_cleanup ( task , ' LOCALHOST regression cleanup ' )
2026-10-23 09:03:27 +08:00
if verifier . task ( task ) [ ' config ' ] . get ( ' stopPending ' ) :
verifier . api ( ' POST ' , ' /lab/scan-task/confirm-stop ' , dict ( taskId = task , reason = ' LOCALHOST regression cleanup confirmation ' ) )
result = cleanup ( [ prefix ] , apply = True )
require ( not cleanup ( [ prefix ] ) [ ' counts ' ] , ' Regression business data remains ' )
verifier . report . update ( passed = passed , cleanup = result , supplierPosts = len ( supplier . posts ) )
REPORT . write_text ( json . dumps ( verifier . report , ensure_ascii = False , indent = 2 ) , encoding = ' utf-8 ' )
print ( ' Marked business data cleaned ' , flush = True )
resources . close ( )
finally :
backend . stop ( )
supplier . close ( )
if backend . changed : backend . start ( )
print ( json . dumps ( dict ( passed = passed , checks = len ( verifier . report [ ' checks ' ] ) , hardwareRequests = 0 , report = str ( REPORT ) ) , ensure_ascii = False ) )
if __name__ == ' __main__ ' : main ( )