87 lines
3.0 KiB
Python
87 lines
3.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""严格提交日志(对齐安卓版 StrictSubmitJournal / 铁律 4、5)。
|
|
|
|
- begin(record):写前落盘,失败 = 调用方不得发送请求
|
|
- conclude(operation_id, state):只有明确结论才结束待核实
|
|
- 状态机:sending → unknown → succeeded | rejected
|
|
- 恢复:启动时扫描非终态记录 → 进入"待核实"锁(禁止新提交)
|
|
- 归属校验:用户/服务器任一未核实即视为不匹配(不猜)
|
|
"""
|
|
import os
|
|
import time
|
|
|
|
from core.storage import atomic
|
|
|
|
JOURNAL_DIR = 'data/journal'
|
|
STATE_SENDING = 'sending'
|
|
STATE_UNKNOWN = 'unknown'
|
|
STATE_SUCCEEDED = 'succeeded'
|
|
STATE_REJECTED = 'rejected'
|
|
TERMINAL = (STATE_SUCCEEDED, STATE_REJECTED)
|
|
|
|
|
|
class StrictSubmitJournal:
|
|
def __init__(self):
|
|
self.unresolved = {} # operation_id -> record
|
|
self.load()
|
|
|
|
def load(self):
|
|
self.unresolved = {}
|
|
if not os.path.isdir(JOURNAL_DIR):
|
|
return
|
|
for fn in os.listdir(JOURNAL_DIR):
|
|
if not fn.endswith('.json'):
|
|
continue
|
|
rec = atomic.read_json(os.path.join(JOURNAL_DIR, fn))
|
|
if rec and rec.get('state') not in TERMINAL:
|
|
self.unresolved[rec['operationId']] = rec
|
|
|
|
def has_unresolved(self):
|
|
return bool(self.unresolved)
|
|
|
|
def begin(self, operation_id, kind, target_id, qty, weight, unit):
|
|
rec = {
|
|
'operationId': operation_id,
|
|
'kind': kind, # picking | inspection
|
|
'targetId': target_id,
|
|
'qty': qty, 'weight': weight, 'unit': unit,
|
|
'accountUserId': '', # 提交时由 pipeline 填
|
|
'apiBaseUrl': '',
|
|
'state': STATE_SENDING,
|
|
'queryAttempts': 0,
|
|
'createdAt': time.strftime('%Y-%m-%d %H:%M:%S'),
|
|
}
|
|
if not atomic.write_json(os.path.join(
|
|
JOURNAL_DIR, operation_id + '.json'), rec):
|
|
return None
|
|
self.unresolved[operation_id] = rec
|
|
return rec
|
|
|
|
def update(self, operation_id, **fields):
|
|
rec = self.unresolved.get(operation_id)
|
|
if not rec:
|
|
return False
|
|
rec.update(fields)
|
|
return atomic.write_json(os.path.join(
|
|
JOURNAL_DIR, operation_id + '.json'), rec)
|
|
|
|
def conclude(self, operation_id, state, message=''):
|
|
rec = self.unresolved.get(operation_id)
|
|
if not rec:
|
|
return False
|
|
rec['state'] = state
|
|
rec['message'] = message
|
|
rec['concludedAt'] = time.strftime('%Y-%m-%d %H:%M:%S')
|
|
ok = atomic.write_json(os.path.join(
|
|
JOURNAL_DIR, operation_id + '.json'), rec)
|
|
if ok and state in TERMINAL:
|
|
self.unresolved.pop(operation_id, None)
|
|
return ok
|
|
|
|
def owner_matches(self, rec, user_id, base_url):
|
|
uid = rec.get('accountUserId', '')
|
|
base = rec.get('apiBaseUrl', '')
|
|
if not uid or not base:
|
|
return False # 空值不是通配符:不匹配、不猜
|
|
return uid == user_id and base == base_url
|