"""C101 pull queue. No process-local state authorizes execution.""" import hashlib import time from fastapi import APIRouter, HTTPException, Request from fastapi.responses import JSONResponse from pydantic import Field from .common import no_cache from .credential_api import DeviceRequest from .crypto import canonical from .task_delivery import TaskRequest PROTOCOL = 'work-dispatch-v1' class Acceptance(TaskRequest): digest: str = Field(pattern=r'^[a-f0-9]{64}$') class TaskDispatch: def __init__(self, auth, state, broker): self.auth, self.state, self.broker = auth, state, broker self.db=state.db self.keyring=auth.broker.store.keyring with self.db: self.db.execute("""CREATE TABLE IF NOT EXISTS work_dispatch_v1 ( task_id TEXT PRIMARY KEY, digest TEXT NOT NULL, key_id TEXT NOT NULL, ciphertext TEXT NOT NULL, file_transfer INTEGER NOT NULL, accepted_at DOUBLE PRECISION)""") self.router=APIRouter() self.router.add_api_route('/work/v2/tasks/next',self.next_task,methods=['POST']) self.router.add_api_route('/work/v2/tasks/accept',self.accept,methods=['POST']) def _aad(self, task, digest, files): return canonical([PROTOCOL,*[task[k] for k in ('environment','app_id','owner','host_id', 'binding_generation','turn_id','chat_id','source_message_id')],digest,bool(files)]) def enqueue(self, owner, device, text, turn, *, chat_id, source_message_id, file_transfer): digest=hashlib.sha256(text.encode()).hexdigest() now=time.time();host=device['host_id'];generation=device['binding_generation'] with self.db: self.state._owner_lock(owner) if (self.broker.files and not file_transfer and self.broker.files.pending_count(owner,host,generation,chat_id)): raise ValueError('materials_require_file_capability') inserted=self.db.execute("INSERT INTO turns VALUES(?,?,?,?,?) ON CONFLICT(turn_id) DO NOTHING", (turn,owner,host,'queued',now)).rowcount if inserted!=1:return 'duplicate' count=self.db.execute("""SELECT COUNT(*) AS n FROM work_tasks_v2 WHERE environment=? AND app_id=? AND host_id=? AND binding_generation=? AND status='queued' AND deadline>?""", (self.state.environment,self.state.app_id,host,generation,now)).fetchone()['n'] if count>=min(self.broker.s.max_pending,20): raise HTTPException(503,'device_queue_full') task=self.state.create_task_locked(turn,owner,host,generation,'',self.broker.worker_id, now+self.broker.s.task_tracking_timeout,chat_id,source_message_id,status='queued') if file_transfer: self.broker.files.claim_locked(task) key,cipher=self.keyring.encrypt(text.encode(),self._aad(task,digest,file_transfer)) self.db.execute('INSERT INTO work_dispatch_v1 VALUES(?,?,?,?,?,NULL)', (turn,digest,key,cipher,int(file_transfer))) return 'queued' async def next_task(self,body:DeviceRequest,request:Request): await self.auth.authenticate(body,request) with self.db: self.state._owner_lock(body.binding_owner) self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation) row=self.db.execute("""SELECT t.*,q.digest,q.key_id,q.ciphertext,q.file_transfer FROM work_tasks_v2 t JOIN work_dispatch_v1 q ON q.task_id=t.turn_id WHERE t.environment=? AND t.app_id=? AND t.owner=? AND t.host_id=? AND t.binding_generation=? AND t.status='queued' AND t.deadline>? AND q.accepted_at IS NULL ORDER BY t.created_at,t.turn_id LIMIT 1 """, (self.state.environment,self.state.app_id,body.binding_owner,body.host_id, body.binding_generation,time.time())).fetchone() job=None if row: text=self.keyring.decrypt(row['key_id'],row['ciphertext'], self._aad(row,row['digest'],row['file_transfer'])).decode() if hashlib.sha256(text.encode()).hexdigest()!=row['digest']: raise HTTPException(409,'dispatch_integrity_failed') context={k:row[k] for k in ('environment','app_id','owner','host_id','binding_generation', 'chat_id','source_message_id','conversation_id')} context.update(task_id=row['turn_id'],channel='work-dm') job={'context':context,'text':text,'digest':row['digest'],'file_transfer':bool(row['file_transfer'])} return no_cache(JSONResponse({'protocol':PROTOCOL,'task':job})) async def accept(self,body:Acceptance,request:Request): await self.auth.authenticate(body,request) with self.db: self.state._owner_lock(body.binding_owner) self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation) task=self.state.task(body.task_id) if (not self.state.task_current(task) or (task['owner'],task['host_id'],task['binding_generation']) != (body.binding_owner,body.host_id,body.binding_generation) or task['status'] in {'unbound','revoked','expired','result_discarded'}): raise HTTPException(403,'task_not_recoverable') row=self.db.execute('SELECT digest,accepted_at FROM work_dispatch_v1 WHERE task_id=?', (body.task_id,)).fetchone() if not row: raise HTTPException(403,'task_not_recoverable') if row['digest']!=body.digest: raise HTTPException(409,'dispatch_digest_mismatch') if row['accepted_at'] is None: if task['status']!='queued': raise HTTPException(403,'task_not_recoverable') now=time.time() changed=self.db.execute("""UPDATE work_tasks_v2 SET status='inflight',worker_id=?,updated_at=? WHERE turn_id=? AND status='queued' AND deadline>?""", (self.broker.worker_id,now,body.task_id,now)).rowcount if changed!=1: raise HTTPException(403,'task_not_recoverable') self.db.execute("UPDATE turns SET status='inflight' WHERE turn_id=?",(body.task_id,)) self.db.execute("UPDATE work_dispatch_v1 SET accepted_at=?,ciphertext='' WHERE task_id=?", (now,body.task_id)) else: now=row['accepted_at'] return no_cache(JSONResponse({'protocol':PROTOCOL,'task_id':body.task_id, 'digest':body.digest,'accepted':True,'accepted_at':now})) def expire(self): now=time.time() scope=(self.state.environment,self.state.app_id) with self.db: self.db.execute("""UPDATE work_tasks_v2 SET status='expired',updated_at=? WHERE environment=? AND app_id=? AND status='queued' AND deadline<=?""",(now,*scope,now)) self.db.execute("""UPDATE work_dispatch_v1 SET ciphertext='' WHERE ciphertext<>'' AND task_id IN (SELECT turn_id FROM work_tasks_v2 WHERE environment=? AND app_id=? AND status IN ('expired','unbound','revoked'))""",scope)