Files
baiyue-firstleg/scripts/inbound-plan-resource-fault-runtime.test.mjs
T

86 lines
6.7 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import {spawnSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
const script=String.raw`
import importlib.util,sys,json,hashlib,copy,urllib.error
import io
from pathlib import Path
spec=importlib.util.spec_from_file_location('resource_runtime',sys.argv[1]);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
payload={'scope':{'marker':'stdin'},'complete':'x'*200000}
assert m.read_stdin_config(io.BytesIO(json.dumps(payload).encode()))==payload
try:m.read_stdin_config(io.BytesIO(b'x'*(1024*1024+1)));raise AssertionError('unbounded config accepted')
except RuntimeError as e:assert str(e)=='RUNTIME_STDIN_CONFIG_TOO_LARGE'
try:m.read_stdin_config(io.BytesIO(b'{"private":"secret"'));raise AssertionError('partial JSON accepted')
except json.JSONDecodeError as e:
d=m.safe_diagnostic(e);assert d['diagnostic']['stage']=='READ_STDIN_CONFIG';assert 'secret' not in json.dumps(d)
m.STAGE='NACOS_SOURCE_READ'
for endpoint,stage in [('/nacos/v3/auth/user/login','NACOS_LOGIN'),('/nacos/v3/admin/cs/config','NACOS_CONFIG_READ')]:
d=m.safe_diagnostic(urllib.error.HTTPError('http://user:password@private.invalid'+endpoint+'?token=secret',404,'secret body',{},None))
assert d=={'ok':False,'error':stage+'_HTTP_404','diagnostic':{'stage':stage,'errorType':'HTTPError','httpStatus':404}}
assert 'secret' not in json.dumps(d) and 'private' not in json.dumps(d)
assert m.safe_diagnostic(TypeError('private-secret-response'))=={'ok':False,'error':'INBOUND_RESOURCE_ACTION_FAILED','diagnostic':{'stage':'NACOS_SOURCE_READ','errorType':'TypeError'}}
import socket
dns=m.safe_diagnostic(urllib.error.URLError(socket.gaierror(-2,'private DNS hostname secret')))
assert dns=={'ok':False,'error':'NACOS_SOURCE_READ_TRANSPORT_FAILED','diagnostic':{'stage':'NACOS_SOURCE_READ','errorType':'URLError','transportErrorType':'gaierror','errno':-2}}
assert 'private' not in json.dumps(dns) and 'secret' not in json.dumps(dns)
base=Path(sys.argv[1]).with_name('order-submit-dependency-fault-runtime.py').read_text()
C,ns=m.runtime_class(base)
scope={'environment':'TEST','marker':'OFFLINE','containerBookingId':'2106714159440728066','warehouseId':'193000000000200003','batchPrefixHash':hashlib.sha256(json.dumps('2106714159440728066').encode()).hexdigest(),'planSha256':'a'*64}
r=C(scope,{})
assert ns['ORDER']=='firstleg-test-lastleg' and ns['PROPERTIES']=={'WAREHOUSE':'baiyue.warehouse.base-url'}
assert r.lock.name=='chongchong-inbound-resource.lock'
assert 'lastleg-service.yml' in C.config_fingerprint.__code__.co_consts or any(isinstance(c,tuple) and 'lastleg-service.yml' in c for c in C.config_fingerprint.__code__.co_consts)
state={'originalBody':{'Entrypoint':['sh','-c','exec java $JAVA_OPTS org.springframework.boot.loader.launch.JarLauncher']},'proxyPort':4321,'originalImageId':'sha256:'+'c'*64,'originalFingerprint':'f'}
entry=r.injected_entrypoint(state)
assert entry[2].endswith(' --baiyue.warehouse.base-url=http://host.docker.internal:4321')
assert '/warehouse' not in entry[2] and state['originalBody']['Entrypoint'][2].endswith('JarLauncher')
saved=[];calls=[]
r.save=lambda s:saved.append(copy.deepcopy(s))
def lost(*args):calls.append(args);raise RuntimeError('connection lost')
r.tools={'docker':lost};journal={}
try:r.mutation(journal,'STOP_INTENT','POST','/containers/frozen/stop?t=15');raise AssertionError('unknown accepted')
except RuntimeError as e:assert str(e)=='UNCERTAIN_DOCKER_MUTATION'
assert saved[0]['mutation']['step']=='STOP_INTENT' and journal['uncertain']
try:r.mutation(journal,'DELETE_INTENT','DELETE','/containers/frozen');raise AssertionError('blind retry')
except RuntimeError as e:assert str(e)=='UNCERTAIN_MUTATION_REQUIRES_RECONCILE'
assert len(calls)==1
original={'NetworkSettings':{'Networks':{'test-net':{'IPAddress':'172.18.0.7'}}}}
warehouse={'Id':'warehouse-frozen','Image':'sha256:'+'e'*64,'State':{'Health':{'Status':'healthy'}},'NetworkSettings':{'Networks':{'test-net':{'IPAddress':'172.18.0.8'}}}}
token='offline-internal-identity'
r.tools={'inspect':lambda name: warehouse if name=='firstleg-test-warehouse-overseas' else (_ for _ in ()).throw(AssertionError('wrong upstream')),
'require_test':lambda c,name:None,'env_of':lambda c:{'SERVER_PORT':'9305','DEPLOY_ENV':'test','INTERNAL_SERVICE_TOKEN':token}}
routing={'upstreams':{'WAREHOUSE':'http://172.18.0.8:9305'}}
assert r.verified_upstream(original,routing,token)['Id']=='warehouse-frozen'
for url in ['http://172.18.0.9:9305','http://172.18.0.8:9999','http://user:secret@172.18.0.8:9305','http://172.18.0.8:9305/fallback']:
try:r.verified_upstream(original,{'upstreams':{'WAREHOUSE':url}},token);raise AssertionError('wrong route accepted')
except RuntimeError as e:assert str(e)=='UPSTREAM_NOT_VERIFIED_TEST_CONTAINER'
current={'Image':state['originalImageId'],'Config':{'Entrypoint':entry},'State':{'Health':{'Status':'healthy'}}}
r.tools={'fingerprint':lambda c:'f' if c['Config']['Entrypoint']==state['originalBody']['Entrypoint'] else 'wrong'}
assert r.matches_injected(current,state)
changed=copy.deepcopy(current);changed['Config']['Entrypoint'][2]+=' --unrelated=true';assert not r.matches_injected(changed,state)
def refuse(_):raise RuntimeError('RESTORED_NOT_HEALTHY')
r.verify_restored=refuse
try:r.finish(state);raise AssertionError('finished before restored')
except RuntimeError as e:assert str(e)=='RESTORED_NOT_HEALTHY'
for key,value in [('environment','PROD'),('warehouseId','0'),('batchPrefixHash','b'*64)]:
bad=scope|{key:value}
try:m.validate_scope(bad);raise AssertionError('invalid scope accepted')
except RuntimeError:pass
import base64
original_factory=m.runtime_class
class MissingState:
def __init__(self,*_):pass
def load(self):raise FileNotFoundError('private-state-path-must-not-escape')
m.runtime_class=lambda _:(MissingState,{'common_tools':lambda _: {}})
try:m.execute({'action':'status','scope':scope,'baseSource':base64.b64encode(b'offline').decode(),'commonSource':base64.b64encode(b'offline').decode()});raise AssertionError('missing state accepted')
except FileNotFoundError as e:
d=m.safe_diagnostic(e);assert d['diagnostic']=={'stage':'RUNTIME_STATE_READ','errorType':'FileNotFoundError'};assert 'private' not in json.dumps(d)
m.runtime_class=original_factory
print('OFFLINE_RUNTIME_PASS')
`;
test('reviewed Docker methods retain exact target, one-property overlay, journal uncertainty and restore-before-cleanup',()=>{
const result=spawnSync(process.env.PYTHON||'python',['-c',script,fileURLToPath(new URL('./inbound-plan-resource-fault-runtime.py',import.meta.url))],{encoding:'utf8',env:{...process.env,PYTHONDONTWRITEBYTECODE:'1'}});
assert.equal(result.status,0,result.stderr||result.error?.message);assert.ok(result.stdout.includes('OFFLINE_RUNTIME_PASS'));
});