Files
ecs-relay-service/deployable/tests/test_task_dispatch.py
T

101 lines
5.5 KiB
Python

import asyncio
import hashlib
import time
import httpx
import pytest
from relay.connector import create_app
from relay.device_lifecycle import DeviceLifecycle
from test_credential_api import env, wire
from test_device_lifecycle import device, routed, event, send_event
async def rpc(client, env, action, host='a'*32, **fields):
path='/work/v2/tasks/'+action
return await client.post(path,json=wire(env,path,host=host,**fields))
async def test_real_ingress_queued_task_survives_connector_reopen_without_receipt(routed):
env=routed
await device(env,durable_dispatch=True)
msg='om-durable-instruction'
text='synthetic restart request'
task_id='msg_'+hashlib.sha256(msg.encode()).hexdigest()
await send_event(env,event(env,msg,text))
for _ in range(200):
if env['store'].lifecycle.task(task_id):break
await asyncio.sleep(.01)
assert env['store'].lifecycle.task(task_id)['status']=='queued'
assert (await rpc(env['client'],env,'state',task_id=task_id)).json()['execution_state']=='queued'
queued=env['app'].state.dispatch_queue
assert queued.enqueue('ou_a',env['store'].device('a'*32),'/助手 '+text,task_id,chat_id='chat-a',
source_message_id=msg,file_transfer=False)=='duplicate'
old=await rpc(env['client'],env,'next')
job=old.json()['task']
assert job['context']['task_id']==task_id and job['text']=='/助手 '+text
assert text not in str(dict(env['store'].db.execute('SELECT * FROM work_dispatch_v1').fetchone()))
assert (await rpc(env['client'],env,'result',task_id=task_id,result='premature')).status_code==403
assert not env['platform'].replies
second=create_app(env['settings'],env['redis'],env['platform'])
try:
assert second.state.broker.worker_id!=env['app'].state.broker.worker_id
await env['redis'].delete('hn:task-worker:'+env['app'].state.broker.worker_id)
await DeviceLifecycle(second.state.store.lifecycle,env['redis'],second.state.broker).maintain()
async with httpx.AsyncClient(transport=httpx.ASGITransport(second),base_url='https://relay.example.test') as client:
assert (await rpc(client,env,'next')).json()['task']==job
assert (await rpc(client,env,'next',host='b'*32)).json()['task'] is None
fields={'task_id':task_id,'digest':job['digest']}
assert (await rpc(client,env,'accept',host='b'*32,**fields)).status_code==403
assert (await rpc(client,env,'accept',task_id=task_id,digest='0'*64)).status_code==409
first=(await rpc(client,env,'accept',**fields)).json()
assert first['accepted'] is True
assert (await rpc(client,env,'next')).json()['task'] is None
# The response may be lost after commit; retry returns the same receipt.
assert (await rpc(env['client'],env,'accept',**fields)).json()==first
assert (await rpc(client,env,'result',task_id=task_id,result='synthetic result')).status_code==200
assert (await rpc(client,env,'accept',**fields)).json()==first
await second.state.deliveries.flush()
await env['app'].state.deliveries.flush()
assert env['platform'].replies==[(msg,'synthetic result')]
assert second.state.store.db.execute('SELECT ciphertext FROM work_dispatch_v1').fetchone()['ciphertext']==''
finally:
second.state.store.close()
@pytest.mark.parametrize('invalidated',['expired','unbound'])
async def test_stale_queue_entries_cannot_be_recovered(env,invalidated):
api=env['app'].state.dispatch_queue
assert api.enqueue('ou_a',env['store'].device('a'*32),'/助手 synthetic','queued-test',
chat_id='chat-a',source_message_id='om-queued',file_transfer=False)=='queued'
if invalidated=='expired':
with api.db:api.db.execute('UPDATE work_tasks_v2 SET deadline=? WHERE turn_id=?',
(time.time()-1,'queued-test'))
assert (await rpc(env['client'],env,'next')).json()['task'] is None
assert (await rpc(env['client'],env,'accept',task_id='queued-test',
digest=hashlib.sha256('/助手 synthetic'.encode()).hexdigest())).status_code==403
else:
env['store'].unbind('ou_a')
assert (await rpc(env['client'],env,'next')).status_code==403
api.expire()
assert env['store'].lifecycle.task('queued-test')['status']==invalidated
assert api.db.execute('SELECT ciphertext FROM work_dispatch_v1').fetchone()['ciphertext']==''
@pytest.mark.parametrize('env',[True],indirect=True)
async def test_failed_queue_commit_rolls_back_task_and_material_assignment(env,monkeypatch):
from test_work_files import fake_platform
fake_platform(env,monkeypatch)
files=env['app'].state.files
await files.receive('ou_a','chat-a','om-material',{'file_name':'sample.txt','file_key':'test-file'})
api=env['app'].state.dispatch_queue
def interrupted(*args,**kwargs):raise RuntimeError('synthetic encryption failure')
monkeypatch.setattr(api.keyring,'encrypt',interrupted)
with pytest.raises(RuntimeError):
api.enqueue('ou_a',env['store'].device('a'*32),'/助手 synthetic','queue-rollback',
chat_id='chat-a',source_message_id='om-queued',file_transfer=True)
assert not env['store'].lifecycle.task('queue-rollback')
assert api.db.execute('SELECT status FROM turns WHERE turn_id=?',('queue-rollback',)).fetchone() is None
assert dict(api.db.execute('SELECT task_id,status FROM work_files_v1').fetchone())=={'task_id':'','status':'staged'}