File size: 9,906 Bytes
d044abe fa26615 bebe819 fa26615 95a405f bebe819 4106468 d044abe 4106468 d044abe 4106468 d044abe 4106468 d044abe 4106468 d044abe bebe819 d044abe fa26615 d044abe 95a405f d044abe fa26615 d044abe fa26615 d044abe fa26615 d044abe fa26615 bebe819 d044abe bebe819 fa26615 d044abe fa26615 95a405f fa26615 95a405f fa26615 95a405f fa26615 d044abe 95a405f d044abe fa26615 d044abe fa26615 bebe819 fa26615 bebe819 fa26615 d044abe 95a405f d044abe 95a405f d044abe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | """Trusted in-container supervisor. Never import or invoke this on host candidates."""
import json
import os
from pathlib import Path
import resource
import signal
import subprocess
import sys
import tempfile
from protocol import COMMANDS,wrap_source
def publish_state(phase,observations=None,scenario=None,operation=None,syntax_success=True):
path=os.environ.get('SMOLSCRIPT_WORKER_STATE')
if not path:return
target=Path(path);tmp=target.with_suffix('.tmp')
tmp.write_text(json.dumps({'phase':phase,'syntax_success':syntax_success,
'scenario':scenario,'operation':operation,'observations':observations or []}))
tmp.replace(target)
def limits(seconds,file_limit):
os.setsid()
resource.setrlimit(resource.RLIMIT_CPU,(seconds,seconds+1))
resource.setrlimit(resource.RLIMIT_FSIZE,(file_limit,file_limit))
resource.setrlimit(resource.RLIMIT_CORE,(0,0))
def execute(command,stdin,seconds,file_limit=1024*1024):
with tempfile.TemporaryFile() as out,tempfile.TemporaryFile() as err:
p=subprocess.Popen(command,stdin=subprocess.PIPE,stdout=out,stderr=err,
preexec_fn=lambda:limits(seconds,file_limit),env={'PATH':os.environ['PATH'],'HOME':'/tmp','LANG':'C.UTF-8',
'LC_ALL':'C.UTF-8','TZ':'UTC','PYTHONHASHSEED':'0','MONO_THREADS_PER_CPU':'1'})
timed_out=False
try:p.communicate(stdin.encode(),timeout=seconds+1)
except subprocess.TimeoutExpired:timed_out=True
finally:
try:os.killpg(p.pid,signal.SIGKILL)
except ProcessLookupError:pass
p.wait()
out.seek(0);err.seek(0)
output=out.read(65537)
return {'exit_code':p.returncode,'timeout':timed_out,'output_limit':len(output)>65536,
'stdout':output[:65536].decode('utf8','replace'),'stderr':err.read(2000).decode('utf8','replace')}
def program(request):
filename,compile_cmd,run_cmd=COMMANDS[request['language']]
Path(filename).write_text(wrap_source(request['language'],request['kind'],request['code']))
compilation=execute(compile_cmd,'',30,file_limit=64*1024*1024)
syntax=compilation['exit_code']==0 and not compilation['timeout']
if not syntax:return {'syntax_success':False,'compilation':compilation,'observations':[]}
observations=[]
for value in request['inputs']:
line=' '.join(map(str,value)) if isinstance(value,list) else str(value)
observations.append(execute(run_cmd,line+'\n',request['timeout_seconds']))
return {'syntax_success':True,'observations':observations}
def observe(page,check):
loc=page.locator(check['selector']);kind=check['kind']
if kind=='count':return loc.count()
if kind in ('layout_column','layout_row'):
if loc.count()!=1:return {'error':'missing or ambiguous layout target'}
return loc.evaluate('''(e,kind) => { const a=e.querySelectorAll('span'); if(a.length!==2) return false;
const x=a[0].getBoundingClientRect(), y=a[1].getBoundingClientRect();
return kind==='layout_column' ? Math.abs(x.x-y.x)<1 && y.y>=x.bottom : Math.abs(x.y-y.y)<1 && y.x>=x.right; }''',kind)
if kind=='exists':return loc.count()>0
if loc.count()!=1:return {'error':'selector must resolve to exactly one element','count':loc.count()}
if kind=='html_text':return loc.evaluate('(e)=>({text:e.textContent,white_space:getComputedStyle(e).whiteSpace})')
if kind=='text':return loc.text_content()
if kind=='attribute':return loc.get_attribute(check['name'])
if kind=='value':return loc.input_value()
if kind=='property':return loc.evaluate('(e,k)=>e[k]',check['name'])
if kind in ('style','unchanged'):return loc.evaluate('(e,p)=>getComputedStyle(e).getPropertyValue(p)',check['property'])
raise ValueError(kind)
def inject_css(page,css):
# Playwright 1.56 add_style_tag awaits a stylesheet load callback, which can
# stall with page scripting disabled. CSSOM insertion needs no event callback.
page.evaluate("""css => {
const style=document.createElement('style');
style.textContent=css;
document.head.appendChild(style);
}""",css)
def browser(request):
from playwright.sync_api import sync_playwright,TimeoutError as BrowserTimeout
kind=request['kind'];code=request['code']
if kind=='html':
import html5lib
import re
parser=html5lib.HTMLParser()
document=re.match(r'(?is)\s*(?:<!--.*?-->\s*)*(?:<!doctype\s|<html(?:\s|>))',code)
if document:parser.parse(code)
else:parser.parseFragment(code)
syntax=not parser.errors
elif kind=='css':
import tinycss2
rules=tinycss2.parse_stylesheet(code,skip_comments=True,skip_whitespace=True)
def errors(nodes):
for n in nodes:
if n.type=='error':return True
if n.type=='qualified-rule':
if any(x.type=='error' for x in tinycss2.parse_declaration_list(n.content)):return True
if n.type=='at-rule' and n.content is not None:
if errors(tinycss2.parse_rule_list(n.content)):return True
return False
syntax=bool(rules) and not errors(rules)
else:
Path('candidate.js').write_text(code)
syntax=execute(['node','--check','candidate.js'],'',5)['exit_code']==0
if not syntax and kind=='dom':return {'syntax_success':False,'observations':[]}
observations=[]
def state(phase,observations=None,scenario=None,operation=None):
publish_state(phase,observations,scenario,operation,syntax_success=syntax)
state('browser_startup',operation='playwright_driver')
with sync_playwright() as p:
# Container namespace, seccomp, uid, cgroups and disabled networking are
# the mandatory boundary; no browser flag substitutes for that boundary.
state('browser_startup',operation='chromium_launch')
b=p.chromium.launch(headless=True,timeout=20000,args=['--disable-dev-shm-usage'])
try:
for index,scenario in enumerate(request['scenarios']):
state('fixture_setup',observations,index,'new_page')
page=b.new_page(viewport={'width':scenario.get('viewport',800),'height':600},java_script_enabled=kind=='dom')
page.set_default_timeout(request['timeout_seconds']*1000)
page.route('**/*',lambda route:route.abort())
actual=[];baseline=[];error=None
state('fixture_setup',observations,index,'fixture_document')
page.set_content(request['fixture'],wait_until='domcontentloaded')
if request.get('base_css'):
state('fixture_setup',observations,index,'base_css')
inject_css(page,request['base_css'])
state('fixture_setup',observations,index,'baseline_observations')
baseline=[observe(page,c) if c['kind']=='unchanged' else None for c in scenario['checks']]
state('candidate',observations,index,'candidate_execution')
try:
if kind=='html':page.set_content(code,wait_until='domcontentloaded')
elif kind=='css':inject_css(page,code)
else:
page.add_script_tag(content=code)
page.evaluate('() => setup()')
for step in scenario.get('steps',[]):
loc=page.locator(step['selector']);action=step['action']
if action=='fill':loc.fill(step['value'])
elif action=='click':loc.click()
elif action=='event':loc.dispatch_event(step['value'])
elif action=='set_value':loc.evaluate('(e,v)=>{e.value=v}',step['value'])
else:raise ValueError(action)
actual=[observe(page,c) for c in scenario['checks']]
except Exception as e:error=type(e).__name__+': '+str(e)[:500]
observations.append({'actual':actual,'baseline':baseline,'error':error})
state('candidate',observations[:-1],index,'page_close')
page.close()
state('fixture_setup',observations,index)
finally:
state('browser_cleanup',observations)
b.close()
return {'syntax_success':syntax,'observations':observations}
def main():
r=json.loads(Path(sys.argv[1]).read_text())
if r.get('diagnostic'):
result={}
for lang,(_,cmd,run) in COMMANDS.items():
import shutil
result[lang]=bool(shutil.which(cmd[0]) and (run[0].startswith('./') or shutil.which(run[0])))
probe=browser({'kind':'css','code':'#probe { color: rgb(10, 20, 30); }',
'fixture':'<p id="probe">Probe</p><p id="other">Other</p>',
'base_css':'p { color: rgb(0, 0, 0); }','timeout_seconds':3,
'scenarios':[{'checks':[{'kind':'style','selector':'#probe','property':'color'},
{'kind':'unchanged','selector':'#other','property':'color'}]}]})
if not probe['syntax_success'] or len(probe['observations'])!=1:
raise RuntimeError('CSS preflight produced incomplete observations')
observed=probe['observations'][0]
if observed['error'] or observed['actual']!=['rgb(10, 20, 30)','rgb(0, 0, 0)']:
raise RuntimeError('CSS preflight failed computed-style checks: '+json.dumps(observed))
result.update(html=True,css=True)
return {'runtimes':result,'browser_preflight':'passed'}
return browser(r) if r['kind'] in ('html','css','dom') else program(r)
if __name__=='__main__':
try:result=main()
except Exception as e:result={'infrastructure_error':type(e).__name__+': '+str(e)[:2000]}
print(json.dumps(result,allow_nan=False))
|