move_detect/edge/alert.py
유창욱 3f2823a764 refactor: rename cloud/ to server/ (cafe24 is web hosting, not cloud)
The PHP app runs on Cafe24 shared web hosting -- calling it 'cloud'
was misleading. Renames the directory, the edge client module, and
every doc/script/identifier that used the term.

- cloud/ -> server/ (incl. server/deploy/build_cafe24_package.sh paths)
- edge/cloudclient.py -> edge/serverclient.py, CloudClient -> ServerClient
- cloud/docs/cloud-deploy.md -> server/docs/server-deploy.md
- CLOUD_* env/config keys -> SERVER_*
- tests renamed to match

Tests: PHP 109 pass (4 skipped), pytest 167 pass. dist/ regenerated.
2026-07-20 11:30:52 +09:00

79 lines
3.4 KiB
Python

import base64
import hashlib
import hmac
import json
from enum import Enum
from edge.events import Event
# Shared-hosting WAFs (cafe24) frequently block the default "python-requests/x.y" User-Agent
# with an HTML 403 while curl passes — so every event would silently 403 with a correct HMAC
# and URL. Send an explicit UA on every request. ServerClient imports this too.
USER_AGENT = "move-detect-edge/1.0"
class SendResult(Enum):
"""Outcome of one upload attempt. The offline queue must tell a transient outage (retry
forever — a real fall alert has to survive an overnight internet outage) apart from a
permanent rejection (poison — count toward the drop cap), which a bare bool cannot express.
DELIVERED is the only truthy value, so `if client.send(...)` keeps working unchanged."""
DELIVERED = "delivered"
REJECTED = "rejected" # a definite 4xx (not 429): the server will never accept this event
TRANSIENT = "transient" # network error / timeout / 429 / 5xx — connectivity or server hiccup
def __bool__(self) -> bool:
return self is SendResult.DELIVERED
def sign(secret: str, nonce: str, ts: str, body: str | bytes) -> str:
if isinstance(body, str):
body = body.encode()
msg = nonce.encode() + ts.encode() + body
return hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()
class PostClient:
def __init__(self, url: str, device_id: str, secret: str,
nonce_fn, now_fn, http_post=None, timeout: float = 5.0):
self.url = url
self.device_id = device_id
self.secret = secret
self.nonce_fn = nonce_fn
self.now_fn = now_fn
self.timeout = timeout
if http_post is None:
import requests
http_post = requests.post
self._post = http_post
def send(self, event: Event, snapshots: list[bytes]) -> SendResult:
payload = event.to_payload(self.device_id)
payload["snapshots"] = [base64.b64encode(s).decode() for s in snapshots]
body = json.dumps(payload, sort_keys=True)
nonce = self.nonce_fn()
ts = str(self.now_fn())
headers = {
"Content-Type": "application/json",
"User-Agent": USER_AGENT,
"X-Nonce": nonce,
"X-Timestamp": ts,
"X-Signature": sign(self.secret, nonce, ts, body.encode()),
}
try:
# allow_redirects=False: the .htaccess http->https 302 must not silently become a
# GET (405/404). A redirect is a CAFE24_URL misconfiguration to surface, not follow.
resp = self._post(self.url, data=body, headers=headers, timeout=self.timeout,
allow_redirects=False)
except Exception:
# Connection refused / DNS / timeout — the server is unreachable, not rejecting us.
return SendResult.TRANSIENT
code = resp.status_code
if 200 <= code < 300:
return SendResult.DELIVERED
# Transient — "back off and retry", NOT a permanent verdict on the event: all 5xx plus the
# 4xx codes that explicitly mean try-again (408 Request Timeout, 425 Too Early, 429 Too
# Many Requests). Counting these toward the poison drop cap would delete real events during
# a proxy/server hiccup. Only a definite "bad request" 4xx is a permanent rejection.
if code in (408, 425, 429) or code >= 500:
return SendResult.TRANSIENT
return SendResult.REJECTED