feat(work): stage authenticated remote approvals with scoped execution fencing

This commit is contained in:
ex_tianzy
2026-11-17 11:43:33 +08:00
parent d2881b82b0
commit c80c6a0d27
19 changed files with 1586 additions and 25 deletions
+48 -1
View File
@@ -4,6 +4,7 @@ import logging
import os
import threading
import time
from concurrent.futures import ThreadPoolExecutor,TimeoutError as FutureTimeout
import httpx
import redis
@@ -51,7 +52,52 @@ def main():
raise RuntimeError("connector did not accept event")
print(json.dumps({"event": "platform_event_accepted", "type": data.get("header", {}).get("event_type")}), flush=True)
handler = lark.EventDispatcherHandler.builder("", "").register_p2_im_message_receive_v1(received).build()
builder = lark.EventDispatcherHandler.builder("", "").register_p2_im_message_receive_v1(received)
callback_pool=None
if s.work_remote_approvals_enabled:
from lark_oapi.event.callback.model.p2_card_action_trigger import P2CardActionTriggerResponse
callback_pool=ThreadPoolExecutor(max_workers=2,thread_name_prefix='work-card-callback')
callback_slots=threading.BoundedSemaphore(2)
def forward_card(raw):
deadline=time.monotonic()+2.1
# Own this client until the worker ends. The SDK response deadline
# does not imply an in-flight authenticated decision was rolled back.
with httpx.Client(base_url=url,trust_env=False,follow_redirects=False,
timeout=httpx.Timeout(.8,connect=.2,pool=.1))as callback_http:
with callback_http.stream('POST','/internal/approval-callback',content=raw,
headers={'X-Internal-Secret':s.internal_secret,'Content-Type':'application/json'})as response:
if response.status_code!=200:raise ValueError()
body=bytearray()
for chunk in response.iter_bytes():
body.extend(chunk)
if len(body)>4096 or time.monotonic()>deadline:raise ValueError()
return json.loads(body)
def decision(event):
# Same authenticated SDK connection/lease, no second consumer.
# Never log callback bodies or the card-update credential.
fallback={'toast':{'type':'warning','content':'确认结果待核对,请查看原任务状态。'}}
try:
raw=lark.JSON.marshal(event).encode('utf-8')
if len(raw)>65536:return P2CardActionTriggerResponse(fallback)
if not callback_slots.acquire(blocking=False):return P2CardActionTriggerResponse(fallback)
try:future=callback_pool.submit(forward_card,raw)
except BaseException:
callback_slots.release()
raise
def settled(completed):
callback_slots.release()
if not completed.cancelled():completed.exception()
future.add_done_callback(settled)
try:payload=future.result(timeout=2.3)
except FutureTimeout:return P2CardActionTriggerResponse(fallback)
toast=payload.get('toast')if isinstance(payload,dict)else None
if (not isinstance(toast,dict)or toast.get('type')not in {'info','success','warning','error'}
or not isinstance(toast.get('content'),str)or len(toast['content'])>200):
return P2CardActionTriggerResponse(fallback)
return P2CardActionTriggerResponse({'toast':toast})
except Exception:return P2CardActionTriggerResponse(fallback)
builder=builder.register_p2_card_action_trigger(decision)
handler=builder.build()
class ObservableClient(lark.ws.Client):
async def _connect(self):
try:
@@ -69,6 +115,7 @@ def main():
finally:
done.set()
client.close()
if callback_pool:callback_pool.shutdown(wait=False,cancel_futures=True)
try:
lease.release()
except redis.exceptions.LockError: