"""Run a signed webhook and local workflow branches on a temporary loopback server."""
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
from hashlib import sha256
import hmac
from importlib.metadata import version
import json
import re
import sqlite3
from threading import Thread
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener
from flask import Flask, jsonify, request
from werkzeug.serving import WSGIRequestHandler, make_server
from lab_tools import run_exercise
NOW = 1_780_000_000
FIXTURE_SECRET = b"offline-workflow-fixture"
OUTPUTS = {
"终端无法保存": {"kind":"bug","sentiment":"negative","priority":"high","summary":"终端保存失败。"},
"希望新增筛选": {"kind":"feature","sentiment":"neutral","priority":"normal","summary":"请求增加筛选。"},
"谢谢支持": {"kind":"thanks","sentiment":"positive","priority":"normal","summary":"感谢技术支持。"},
"如何打开旧档案": {"kind":"question","sentiment":"neutral","priority":"normal","summary":"询问旧档案入口。"},
"模拟异常输出": {"kind":"bug","sentiment":"negative","priority":"unknown","summary":"状态未确认。"},
}
def signature(timestamp, raw):
return hmac.new(FIXTURE_SECRET, timestamp.encode("ascii") + b"." + raw, sha256).hexdigest()
def unique_fields(pairs):
data = {}
for key, value in pairs:
if key in data:
raise ValueError("duplicate_key")
data[key] = value
return data
def result_for(text):
value = OUTPUTS.get(text)
if value is None:
return None
if (value["kind"] not in {"bug","feature","question","thanks"} or
value["sentiment"] not in {"negative","neutral","positive"} or
value["priority"] not in {"high","normal"} or
not isinstance(value["summary"],str) or not 1 <= len(value["summary"]) <= 100):
return None
route = "technical_review" if value["sentiment"]=="negative" and value["priority"]=="high" else "service_review"
return {**value,"route":route,"status":"queued_locally"}
def initialize(db_path):
with closing(sqlite3.connect(db_path)) as db, db:
db.execute("CREATE TABLE event_queue (event_id TEXT PRIMARY KEY, body_hash TEXT NOT NULL, result TEXT NOT NULL)")
def save_once(db_path, event_id, body_hash, result):
with closing(sqlite3.connect(db_path,timeout=5)) as db, db:
db.execute("BEGIN IMMEDIATE")
earlier = db.execute("SELECT body_hash, result FROM event_queue WHERE event_id=?",(event_id,)).fetchone()
if earlier:
if earlier[0] != body_hash:
return 409, {"error":"event_id_conflict"}
return 200, {**json.loads(earlier[1]),"status":"duplicate"}
db.execute("INSERT INTO event_queue VALUES (?,?,?)",(event_id,body_hash,json.dumps(result,ensure_ascii=False)))
return 201, result
def create_app(db_path, now):
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 2048
@app.errorhandler(413)
def too_large(_error):
return jsonify(error="body_limit"), 413
@app.post("/webhook")
def webhook():
if request.mimetype != "application/json":
return jsonify(error="expected_json"), 415
stamp = request.headers.get("X-Event-Time","")
provided = request.headers.get("X-Event-Signature","")
if not re.fullmatch(r"[0-9]{10}",stamp) or not re.fullmatch(r"[0-9a-f]{64}",provided):
return jsonify(error="invalid_signature"), 401
raw = request.get_data()
if not hmac.compare_digest(signature(stamp,raw),provided):
return jsonify(error="invalid_signature"), 401
if abs(now-int(stamp)) > 300:
return jsonify(error="outside_time_window"), 401
try:
event = json.loads(raw,object_pairs_hook=unique_fields)
except (ValueError, UnicodeDecodeError):
return jsonify(error="invalid_json"), 400
if (type(event) is not dict or set(event)!={"id","content"} or
type(event["id"]) is not str or not re.fullmatch(r"[a-z0-9-]{1,48}",event["id"]) or
type(event["content"]) is not str or not 1 <= len(event["content"].strip()) <= 500):
return jsonify(error="invalid_event"), 400
result = result_for(event["content"])
if result is None:
return jsonify(error="invalid_model_result"), 502
status, payload = save_once(db_path,event["id"],sha256(raw).hexdigest(),result)
return jsonify(payload),status
return app
class QuietHandler(WSGIRequestHandler):
def log(self, *_args, **_kwargs):
pass
def exercise(checks, workspace):
expect = checks.expect
db_path = workspace/"queue.sqlite3"
initialize(db_path)
server = make_server("127.0.0.1",0,create_app(db_path,NOW),threaded=True,request_handler=QuietHandler)
worker = Thread(target=server.serve_forever)
worker.start()
url = f"http://127.0.0.1:{server.server_port}/webhook"
def post(raw, *, timestamp=NOW, mime="application/json", signed=True):
stamp = str(timestamp)
auth = signature(stamp,raw) if signed else "0" * 64
wire = Request(url,data=raw,method="POST",headers={
"Content-Type":mime,"X-Event-Time":stamp,"X-Event-Signature":auth})
opener = build_opener(ProxyHandler({}))
try:
response = opener.open(wire,timeout=5)
except HTTPError as error:
response = error
with response:
return response.status, json.loads(response.read())
def event(event_id, text):
return json.dumps({"id":event_id,"content":text},ensure_ascii=False).encode()
try:
urgent = event("event-1","终端无法保存")
normal = event("event-2","希望新增筛选")
unknown = event("event-bad","模拟异常输出")
wire_errors = [
post(urgent,signed=False),post(urgent,timestamp=NOW-301),post(urgent,timestamp=NOW+301),
post(b"content=example",mime="application/x-www-form-urlencoded"),
post(b'{"id":"x","id":"y","content":"test"}'),post(b"["),post(b'{"id":"x","content":null}'),
post(b" " * 2049),post(unknown),
]
expect("workflow_intro_wire_errors",["unsigned","stale","future","form","duplicate_key","syntax","shape","body_limit","bad_output"],
"Send real loopback requests and reject invalid wire formats, events and fixed model output",
[[401,"invalid_signature"],[401,"outside_time_window"],[401,"outside_time_window"],[415,"expected_json"],
[400,"invalid_json"],[400,"invalid_json"],[400,"invalid_event"],[413,"body_limit"],[502,"invalid_model_result"]],
[[status,data["error"]] for status,data in wire_errors])
expect("workflow_intro_feedback",["urgent bug","normal feature","thanks","question"],
"Route four accepted events and retain the validated one-sentence summary",
[[201,"technical_review","bug","终端保存失败。"],[201,"service_review","feature","请求增加筛选。"],
[201,"service_review","thanks","感谢技术支持。"],[201,"service_review","question","询问旧档案入口。"]],
[[status,data["route"],data["kind"],data["summary"]] for status,data in
[post(urgent),post(normal),post(event("event-3","谢谢支持")),post(event("event-4","如何打开旧档案"))]])
repeat,changed = post(urgent),post(event("event-1","谢谢支持"))
expect("workflow_intro_replay",["same bytes","changed bytes with same ID"],
"Return a replay result or reject an ID conflict without another write",
[200,"duplicate",409,"event_id_conflict"],
[repeat[0],repeat[1]["status"],changed[0],changed[1]["error"]])
fifth = event("event-5","谢谢支持")
with ThreadPoolExecutor(max_workers=2) as pool:
concurrent = sorted((status,data["status"]) for status,data in pool.map(post,[fifth,fifth]))
expect("workflow_intro_concurrent",["event-5","event-5"],"Issue two concurrent deliveries and write one receipt",
[(200,"duplicate"),(201,"queued_locally")],concurrent)
corrected = post(event("event-bad","谢谢支持"))
expect("workflow_intro_retry_corrected","prior invalid result","Permit a corrected delivery after a rejected output",
[201,"thanks"],[corrected[0],corrected[1]["kind"]])
with closing(sqlite3.connect(db_path)) as db:
ids = [row[0] for row in db.execute("SELECT event_id FROM event_queue ORDER BY event_id")]
expect("workflow_intro_persisted","database reopened","Read persisted event IDs after the actual HTTP run",
["event-1","event-2","event-3","event-4","event-5","event-bad"],ids)
finally:
server.shutdown()
worker.join(timeout=10)
server.server_close()
expect("workflow_intro_environment","isolated local runtime","Verify service shutdown and dependency versions",
[False,"3.1.3"],[worker.is_alive(),version("flask")])
if __name__ == "__main__":
run_exercise(exercise)
本例需在 CPython 3.12.14、Flask 3.1.3、SQLite 与本机 n8n 2.46.7;固定数据和环回请求。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、Flask 3.1.3、SQLite 与本机 n8n 2.46.7;固定数据和环回请求。
入口文件:projects/ai-workflow/workflow_hook.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
workflow_hook.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、Flask 3.1.3、SQLite 与本机 n8n 2.46.7;固定数据和环回请求。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a31.zip