File size: 12,496 Bytes
caf8059
 
 
5ca3c16
 
caf8059
 
5ca3c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caf8059
 
 
5ca3c16
 
 
 
 
caf8059
 
 
5ca3c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
253a5d4
caf8059
 
 
 
5ca3c16
 
 
caf8059
 
 
5ca3c16
caf8059
 
5ca3c16
 
 
caf8059
 
 
5ca3c16
caf8059
 
 
5ca3c16
 
 
 
 
 
 
 
 
caf8059
5ca3c16
caf8059
 
 
 
5ca3c16
 
 
 
caf8059
 
5ca3c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
caf8059
5ca3c16
caf8059
 
 
 
 
5ca3c16
 
caf8059
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Owner- and artifact-bound Agent execution units; never a shared active preview."""
import json
import threading
import time
import uuid
from pathlib import Path
from src.adapters.sandbox.preview import PreviewSession
from src.modules.skill.domain.models import SkillError,digest


class VerifiedPageSession:
    """A page-only preview bound to existing real VM evidence and an opaque browser frame."""
    execution_mode='verified-static-page'

    def __init__(self, source, evidence):
        self.source=source;self.id=uuid.uuid4().hex;self.expires=time.time()+900
        self._status='ready';self.error=None;self.started_at=time.time()
        candidate=evidence['manifest']['candidate'];tested=evidence['manifest']['test']
        self.receipt={'source_digest':source['source_digest'],'image':candidate['image'],
            'config_digest':candidate['config_digest'],'classes_digest':candidate['classes_digest'],
            'tests':tested['passed_cases'],'verification':'existing-vm-evidence',
            'network':'none','host_mounts':[]}

    @property
    def status(self):
        if self._status=='ready' and time.time()>=self.expires:self._status='closed'
        return self._status

    def progress(self):
        return {'started_at':self.started_at,'server_time':time.time(),'elapsed_seconds':max(0,time.time()-self.started_at),
                'events':[{'at':self.started_at,'phase':'ready','detail':'已使用当前源码的隔离验证证据。'}],
                'process_alive':False}

    def request(self,*args,**kwargs):
        raise SkillError('PREVIEW_API_UNAVAILABLE','此网页应用没有服务端业务接口。',403)

    def close(self):self._status='closed'


class AgentSandboxPool:
    # Grace protects reload/navigation; timeout also covers a crashed browser.
    BROWSER_GRACE=8
    BROWSER_TIMEOUT=120

    def __init__(self, engine, capacity=3, factory=PreviewSession, *, clock=time.monotonic):
        if type(capacity) is not int or not 1<=capacity<=8:raise ValueError('Sandbox capacity must be 1..8')
        self.engine,self.capacity,self.factory=engine,capacity,factory
        self.lock=threading.RLock();self.units={};self.selected={};self.threads=[]
        self.clock=clock;self.stopping=threading.Event()
        self.reaper=threading.Thread(target=self._reap_loop,daemon=True,name='preview-browser-reaper')
        self.reaper.start()

    def _reap_loop(self):
        while not self.stopping.wait(2):
            with self.lock:self._reap_locked()

    def _reap_locked(self):
        now=self.clock()
        for unit in self.units.values():
            if unit['session'].status not in {'starting','ready'} or unit.get('prewarm'):continue
            clients=unit['clients']
            for key,seen in list(clients.items()):
                if now-seen>=self.BROWSER_TIMEOUT:clients.pop(key)
            if clients:continue
            if unit['browser_seen'] and unit['close_after'] is None:unit['close_after']=now+self.BROWSER_GRACE
            deadline=unit['close_after'] if unit['browser_seen'] else unit['claim_deadline']
            if deadline is not None and now>=deadline:
                unit['session'].close();unit['close_reason']='browser-disconnected';self._persist(unit)

    def browser_client(self, actor, preview_id, client_id, event):
        with self.lock:
            unit=self._authorized(actor,preview_id)
            self._reap_locked()
            session=unit['session'];clients=unit['clients']
            if session.status not in {'starting','ready'}:
                if event=='release':return {'status':session.status}
                raise SkillError('PREVIEW_NOT_READY','本次预览已结束,请从工作台重新打开。',409)
            if event=='attach':
                if client_id not in clients and len(clients)>=32:raise SkillError('PREVIEW_CLIENT_LIMIT','此应用打开的窗口过多。',429)
                clients[client_id]=self.clock();unit['browser_seen']=True;unit['close_after']=None
            elif event=='heartbeat':
                # A late in-flight heartbeat must never resurrect a closed document.
                if client_id not in clients:raise SkillError('PREVIEW_CLIENT_GONE','请重新打开此应用。',409)
                clients[client_id]=self.clock()
            elif event=='release':
                if client_id in clients:
                    clients.pop(client_id)
                    if not clients:unit['close_after']=self.clock()+self.BROWSER_GRACE
            else:raise SkillError('INVALID_INPUT','窗口状态不符合契约。',422)
            return {'status':session.status}

    def _authorized(self, actor, preview_id=None):
        key=preview_id or self.selected.get(actor.user_id)
        unit=self.units.get(key)
        if not unit or unit['owner']!=actor.user_id:
            raise SkillError('PREVIEW_NOT_FOUND','该应用预览不存在或已结束。',404)
        self.engine.spec(actor,unit['scenario'])
        return unit

    def _state(self, unit):
        session=unit['session']
        return dict(id=session.id,agent_id='agent-'+session.id,scenario=unit['scenario'],kind=unit['kind'],reference=unit['reference'],
                    status=session.status,error=session.error,expires_at=session.expires,receipt=session.receipt,
                    diagnostics=getattr(session,'diagnostics',None),
                    backend=getattr(session,'execution_mode','qemu'),progress=session.progress(),
                    url=getattr(self.engine,'preview_origin','')+'/preview-site/?lease='+session.id if session.status=='ready' else None)

    def state(self, actor, preview_id=None):
        with self.lock:
            self._reap_locked()
            return self._state(self._authorized(actor,preview_id))

    def find(self, actor, kind, reference):
        with self.lock:
            self._reap_locked()
            for unit in reversed(list(self.units.values())):
                if unit['owner']==actor.user_id and unit['kind']==kind and unit['reference']==reference and unit['session'].status in {'starting','ready'}:
                    if unit.get('prewarm'):
                        unit['prewarm']=False;unit['claim_deadline']=self.clock()+self.BROWSER_TIMEOUT
                        unit['session'].expires=time.time()+900;self.selected[actor.user_id]=unit['session'].id
                    return self._state(self._authorized(actor,unit['session'].id))
        raise SkillError('PREVIEW_NOT_FOUND','该应用尚未打开,请从对应工程启动。',404)

    def start(self, actor, kind, reference, *, prewarm=False):
        scenario,_,evidence=self.engine.evidence(actor,kind,reference)
        runtime=self.engine.runtimes[scenario];source=evidence['manifest']['source']
        runtime.harness.files({'files':source['files']},evidence['manifest']['snapshot']['framework'])
        candidate=evidence['manifest'].get('candidate',{})
        fast_page=(scenario=='webapp' and candidate.get('execution_mode') in {'qemu','docker'}
            and candidate.get('source_digest')==source['source_digest']
            and candidate.get('config_digest')==digest(runtime.sandbox.config)
            and candidate.get('image')==runtime.sandbox.config.image
            and evidence['manifest']['test'].get('suite_digest')==runtime.sandbox.suite_digest)
        if fast_page:
            runtime.harness.evidence(evidence['manifest']['test'],candidate,'test')
            runtime.harness.evidence(evidence['manifest']['preview'],candidate,'preview')
        with self.lock:
            self._reap_locked()
            for unit in self.units.values():
                session=unit['session']
                if (unit['owner']==actor.user_id and unit['kind']==kind and unit['reference']==reference
                        and session.source['source_digest']==source['source_digest'] and session.status in {'starting','ready'}):
                    if not prewarm:
                        if unit['prewarm']:unit['claim_deadline']=self.clock()+self.BROWSER_TIMEOUT
                        unit['prewarm']=False;session.expires=time.time()+900
                        self.selected[actor.user_id]=session.id
                    return self._state(unit)
            if sum(u['session'].status in {'starting','ready'} for u in self.units.values())>=self.capacity:
                idle=next((u for u in self.units.values() if u.get('prewarm') and u['session'].status in {'starting','ready'}),None)
                if prewarm:return None
                if idle:
                    idle['session'].close();idle['prewarm']=False;self._persist(idle)
                else:
                    if any(u['session'].status in {'starting','ready'} and u.get('close_after') is not None for u in self.units.values()):
                        raise SkillError('SANDBOX_RELEASING','正在释放已关闭的应用,请稍候。',409)
                    raise SkillError('SANDBOX_CAPACITY_EXCEEDED','并行应用已达到本机容量,请关闭一个不再使用的预览后重试。',409)
            session=VerifiedPageSession(source,evidence) if fast_page else self.factory(runtime.sandbox,source)
            # Reuse only evidence bound to the exact current source, image, configuration and suite.
            if not fast_page and isinstance(session,PreviewSession):
                test=evidence['manifest'].get('test',{})
                if (candidate.get('source_digest')==source['source_digest']
                    and candidate.get('config_digest')==digest(runtime.sandbox.config)
                    and candidate.get('image')==runtime.sandbox.config.image
                    and candidate.get('suite_digest')==runtime.sandbox.suite_digest
                    and test.get('suite_digest')==runtime.sandbox.suite_digest):
                    runtime.harness.evidence(test,candidate,'test')
                    session.tested_candidate=candidate;session.tested_evidence=test
            if prewarm:session.expires=min(session.expires,time.time()+180)
            unit={'owner':actor.user_id,'scenario':scenario,'kind':kind,'reference':reference,'session':session,'prewarm':prewarm,
                  'clients':{},'browser_seen':False,'close_after':None,'claim_deadline':self.clock()+self.BROWSER_TIMEOUT}
            self.units[session.id]=unit
            if not prewarm:self.selected[actor.user_id]=session.id
            if fast_page:
                self._persist(unit)
                return self._state(unit)
            def execute():
                try:session.start()
                finally:self._persist(unit)
            self._persist(unit)
            thread=threading.Thread(target=execute,daemon=True,name='agent-'+session.id);self.threads.append(thread);thread.start()
            return self._state(unit)

    def _persist(self, unit):
        with self.lock:
            folder=Path(self.engine.root)/'agent-sandboxes';folder.mkdir(exist_ok=True)
            state=self._state(unit);target=folder/(state['id']+'.json');temporary=target.with_suffix('.tmp')
            temporary.write_text(json.dumps({**state,'owner':unit['owner']},ensure_ascii=False,indent=2),encoding='utf-8');temporary.replace(target)

    def request(self, actor, preview_id, method, path, token, body=None):
        with self.lock:unit=self._authorized(actor,preview_id)
        return unit['session'].request(method,path,token,**({'body':body} if body is not None else {}))

    def close(self, actor, preview_id=None):
        with self.lock:unit=self._authorized(actor,preview_id)
        unit['session'].close();self._persist(unit)

    def list(self, actor):
        result=[]
        with self.lock:
            self._reap_locked()
            for key,unit in self.units.items():
                if unit['owner']!=actor.user_id or unit.get('prewarm'):continue
                try:result.append(self._state(self._authorized(actor,key)))
                except SkillError:continue
        return {'capacity':self.capacity,'active_total':sum(u['session'].status in {'starting','ready'} for u in self.units.values()),'items':result}

    def shutdown(self):
        self.stopping.set()
        if self.reaper is not threading.current_thread():self.reaper.join(timeout=3)
        with self.lock:units=list(self.units.values())
        for unit in units:
            unit['session'].close();self._persist(unit)
        for thread in self.threads:
            if thread is not threading.current_thread():thread.join(timeout=2)