feat(dashboard): push manual batch start/stop to zenai_nano_fcp peer
ci / smoke (push) Canceled after 0s
ci / smoke (push) Canceled after 0s
- src/peer_sync.py: stdlib urllib client, 2 attempts 0.5s apart, fail-soft - counter_dashboard.py: hooks in api_batch_start/api_batch_stop, peer_sync in JSON - operator/monitoring templates: warn operator when the peer call fails - .env: PEER_API_URL (empty = disabled) / PEER_API_TOKEN / PEER_API_TIMEOUT - docs/peer_sync_handoff.md: contract for the zenai side (not implemented there yet)
This commit is contained in:
1 parent
af65d971c4
commit
b5e5f72d27
11 files changed
+519
-2
No files matched your search
@@ -35,6 +35,13 @@ MOTIONEYE_CLIP_PAD=3 # seconds trimmed before/after th
|
||||
MOTIONEYE_OSD_ALIGN=1 # 1 = OCR-correct OSD clock drift at cut points, 0 = filename-based offsets only
|
||||
MOTIONEYE_CLIP_TIMEOUT=600 # ffmpeg timeout per piece in seconds (default 600)
|
||||
|
||||
# --- Peer batch sync (zenai_nano_fcp counter, RK3588 device) ---
|
||||
# Empty PEER_API_URL disables peer sync: FCP then counts alone.
|
||||
# PEER_API_TOKEN is optional; when set it is sent as X-API-Key header.
|
||||
PEER_API_URL=
|
||||
PEER_API_TOKEN=
|
||||
PEER_API_TIMEOUT=5
|
||||
|
||||
# --- Deprecated: model pipeline mode now lives in config.yaml models.active_mode.
|
||||
# Dashboard switches persist there (atomic write, comments preserved) and apply
|
||||
# on next `karung-counter` restart. Only set this to temporarily override.
|
||||
|
||||
@@ -16,7 +16,8 @@ Indonesian (`karung`=sack, `truk`=truck); YOLO class names are English
|
||||
Model modes are DATA in `config.yaml` `models.modes` (engines + class filters
|
||||
only; conf/iou/min_bbox in `models.detection_params`):
|
||||
A=combined only; B=v4 truck + yolo11n sack+box; C=A + yolo11n box-only (default);
|
||||
D=v4 truck + best sack-only + yolo11n box-only; E=single unified yolo11n sack+box+truck. New modes need no code change.
|
||||
D=v4 truck + best sack-only + yolo11n box-only; E=single unified yolo11n sack+box+truck;
|
||||
F=single unified yolo8n sack+box+truck (imgsz 320). New modes need no code change.
|
||||
All modes load `.engine` files (2-3 coexist, ~24 MB peak); never mix load
|
||||
order assumptions — PyTorch `.pt` must load before TensorRT `.engine`.
|
||||
- `src/` = shared library (detection/tracking/counting/batch). `python -m src.main`
|
||||
@@ -90,6 +91,13 @@ Indonesian (`karung`=sack, `truk`=truck); YOLO class names are English
|
||||
- **Office history batch delete** (`/api/batch/delete`, `:5721` only): removes a
|
||||
batch + its DO rows, fixes `daily_summaries`, and rewrites the two CSVs.
|
||||
Intended for testing/cleanup, not production data repair.
|
||||
- **Peer sync (zenai_nano_fcp)**: manual/do_manual batch start+stop is pushed to
|
||||
the peer counter via `src/peer_sync.py` (stdlib urllib, 2 attempts, 0.5s backoff,
|
||||
fail-soft — peer outage never blocks the FCP batch). Config `.env` only:
|
||||
`PEER_API_URL` (empty = disabled), `PEER_API_TOKEN` (→ `X-API-Key`),
|
||||
`PEER_API_TIMEOUT`. Reply with `success:false` = failure; stop reply
|
||||
"No active batch" = already stopped → ok. zenai side is NOT implemented yet
|
||||
(single-label batches) — see `docs/peer_sync_handoff.md`.
|
||||
- **Don't commit state**: `.gitignore` excludes `*.engine` (rebuildable),
|
||||
`*.mp4/*.jpg/*.png`, `*.db`, `.env`, `batch_history_folder/`. Videos and local
|
||||
DBs already sit untracked in the working tree — leave them alone.
|
||||
|
||||
@@ -134,4 +134,5 @@ Script-by-script reference: [`docs/scripts.md`](docs/scripts.md).
|
||||
- [`ERD.md`](ERD.md) — SQLite ERD (Mermaid): batches / delivery_orders / daily_summaries
|
||||
- [`docs/operator-tiles-history-plan.md`](docs/operator-tiles-history-plan.md) — operator tiles + history cleanup plan
|
||||
- [`docs/scripts.md`](docs/scripts.md) — entry points & utility scripts
|
||||
- [`docs/peer_sync_handoff.md`](docs/peer_sync_handoff.md) — FCP → zenai_nano_fcp batch sync contract (zenai side still TODO)
|
||||
- [`CHANGELOG.md`](CHANGELOG.md) — release history
|
||||
+46
-1
@@ -87,6 +87,7 @@ from src.do_batch import (
|
||||
should_purge_counting_date,
|
||||
start_gate_errors,
|
||||
)
|
||||
from src.peer_sync import notify as peer_notify
|
||||
|
||||
# Runtime DO settings (require_plate/do + ocr_engine) — separate from config.yaml seed.
|
||||
if os.name == "nt":
|
||||
@@ -432,6 +433,39 @@ def get_next_batch_number(counting_date):
|
||||
return 1
|
||||
|
||||
|
||||
PEER_SOURCE = "fcp-semarang"
|
||||
PEER_LABELS = ["sack", "box"]
|
||||
|
||||
|
||||
def _peer_start_payload(batch_state):
|
||||
"""Body posted to the peer counter when an FCP batch starts."""
|
||||
return {
|
||||
"source": PEER_SOURCE,
|
||||
"object_label": PEER_LABELS[0],
|
||||
"object_labels": list(PEER_LABELS),
|
||||
"fcp_batch_number": batch_state.get("batch_number"),
|
||||
"counting_date": batch_state.get("counting_date"),
|
||||
"plate": batch_state.get("plate") or "",
|
||||
"do_numbers": batch_state.get("do_numbers") or [],
|
||||
"expected_sack": int(batch_state.get("expected_sack") or 0),
|
||||
"expected_box": int(batch_state.get("expected_box") or 0),
|
||||
"started_at": batch_state.get("start_time"),
|
||||
}
|
||||
|
||||
|
||||
def _peer_stop_payload(batch_state, net_sack, net_box, ended_at):
|
||||
"""Body posted to the peer counter when an FCP batch stops."""
|
||||
return {
|
||||
"source": PEER_SOURCE,
|
||||
"fcp_batch_number": batch_state.get("batch_number"),
|
||||
"counting_date": batch_state.get("counting_date"),
|
||||
"plate": batch_state.get("plate") or "",
|
||||
"net_sack": int(net_sack or 0),
|
||||
"net_box": int(net_box or 0),
|
||||
"ended_at": ended_at,
|
||||
}
|
||||
|
||||
|
||||
@app.route("/api/batch/start", methods=["POST"])
|
||||
def api_batch_start():
|
||||
try:
|
||||
@@ -455,6 +489,7 @@ def api_batch_start():
|
||||
"batch_number": curr.get("batch_number"),
|
||||
"counting_date": curr.get("counting_date"),
|
||||
"start_time": curr.get("start_time"),
|
||||
"peer_sync": peer_notify("start", _peer_start_payload(curr)),
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
@@ -595,6 +630,10 @@ def api_batch_start():
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Peer counter (zenai_nano_fcp) follows the same batch. Fail-soft:
|
||||
# a peer outage never blocks the FCP batch.
|
||||
peer_result = peer_notify("start", _peer_start_payload(batch_state))
|
||||
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"message": f"Batch #{batch_num} started",
|
||||
@@ -605,6 +644,7 @@ def api_batch_start():
|
||||
"do_numbers": do_numbers,
|
||||
"expected_sack": expected_sack,
|
||||
"expected_box": expected_box,
|
||||
"peer_sync": peer_result,
|
||||
})
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
@@ -772,6 +812,10 @@ def api_batch_stop():
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Peer counter gets the same stop. Fail-soft: FCP batch already closed.
|
||||
peer_result = peer_notify(
|
||||
"stop", _peer_stop_payload(curr, net_sack, net_box, end_time_iso))
|
||||
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"message": f"Batch #{batch_num} stopped" + (
|
||||
@@ -783,7 +827,8 @@ def api_batch_stop():
|
||||
"net_box": net_box,
|
||||
"discarded": discarded,
|
||||
"start_time": start_time_iso,
|
||||
"end_time": end_time_iso
|
||||
"end_time": end_time_iso,
|
||||
"peer_sync": peer_result,
|
||||
})
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
@@ -28,6 +28,7 @@ SRC_MODULES = [
|
||||
"logger.py",
|
||||
"main.py",
|
||||
"persistence.py",
|
||||
"peer_sync.py",
|
||||
"pipeline.py",
|
||||
"stabilizer.py",
|
||||
"tracking.py",
|
||||
|
||||
@@ -107,6 +107,9 @@ when set.
|
||||
| `MODEL_PATH` | — (deprecated) | Single-file v4 override, folded into `models.paths` |
|
||||
| `MODEL_MODE` | — (deprecated) | One-run override of `models.active_mode` (warned) |
|
||||
| `BATCH_MERGE_THRESHOLD_SECONDS` | `300` | Merge window for adjacent batches |
|
||||
| `PEER_API_URL` | `""` | Peer counter base URL (zenai_nano_fcp, e.g. `http://10.38.250.21:7000`). Empty = peer sync disabled. Manual batch start/stop is pushed there (fail-soft). See `docs/peer_sync_handoff.md`. |
|
||||
| `PEER_API_TOKEN` | `""` | Optional shared secret sent as `X-API-Key` header to the peer |
|
||||
| `PEER_API_TIMEOUT` | `5` | Per-request timeout (seconds) for peer calls; 2 attempts, 0.5 s apart |
|
||||
|
||||
On Windows dev machines these resolve to `d:/Belajar/menghitung karung/...`.
|
||||
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
# Handoff: FCP → zenai_nano_fcp batch sync
|
||||
|
||||
Status: **FCP side is DONE and shipped. zenai side is NOT done yet.**
|
||||
|
||||
FCP (Feedmill Counting Platform, Jetson 192.168.192.96) is the source of truth for
|
||||
counts. Since this handoff, FCP pushes every **manual** batch start/stop to the
|
||||
zenai counter (RK3588 device, `/opt/feedmill`, dashboard port 7000) so both sides
|
||||
count the same load.
|
||||
|
||||
Until the zenai work below is implemented, FCP already sends the requests and
|
||||
zenai answers with its **single-label** behaviour. FCP detects that and shows the
|
||||
operator a warning (`Peer hanya menerima satu label (sack) …`).
|
||||
|
||||
## 1. What FCP sends
|
||||
|
||||
Base URL from FCP `.env`:
|
||||
|
||||
```
|
||||
PEER_API_URL=http://<zenai-host>:7000 # empty => peer sync disabled
|
||||
PEER_API_TOKEN=<shared secret> # optional -> X-API-Key header
|
||||
PEER_API_TIMEOUT=5 # seconds, per request
|
||||
```
|
||||
|
||||
Requests are plain JSON POSTs. Headers: `Content-Type: application/json`,
|
||||
optional `X-API-Key`.
|
||||
|
||||
### 1.1 Start — `POST {PEER_API_URL}/api/batch/start`
|
||||
|
||||
```json
|
||||
{
|
||||
"source": "fcp-semarang",
|
||||
"object_label": "sack",
|
||||
"object_labels": ["sack", "box"],
|
||||
"fcp_batch_number": 12,
|
||||
"counting_date": "2026-11-13",
|
||||
"plate": "B 1234 XYZ",
|
||||
"do_numbers": ["DO-2026-0011"],
|
||||
"expected_sack": 40,
|
||||
"expected_box": 10,
|
||||
"started_at": "2026-11-13T09:12:03"
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2 Stop — `POST {PEER_API_URL}/api/batch/stop`
|
||||
|
||||
```json
|
||||
{
|
||||
"source": "fcp-semarang",
|
||||
"fcp_batch_number": 12,
|
||||
"counting_date": "2026-11-13",
|
||||
"plate": "B 1234 XYZ",
|
||||
"net_sack": 38,
|
||||
"net_box": 9,
|
||||
"ended_at": "2026-11-13T10:04:57"
|
||||
}
|
||||
```
|
||||
|
||||
`net_sack` / `net_box` are FCP's final numbers — **reference only**. zenai keeps
|
||||
its own counts; FCP stays authoritative for reporting.
|
||||
|
||||
## 2. What FCP expects back
|
||||
|
||||
FCP accepts the **existing** zenai reply shape, no change required:
|
||||
|
||||
```json
|
||||
{"success": true, "message": "Started Batch #7 (SACK)", "batch_number": 7,
|
||||
"object_label": "sack", "status": "running"}
|
||||
```
|
||||
|
||||
Rules FCP applies to the reply:
|
||||
|
||||
| Reply | FCP reaction |
|
||||
|---|---|
|
||||
| HTTP 200 + `success: true` | ok |
|
||||
| HTTP 200 + `success: false`, error contains `No active batch` (stop only) | ok — peer was already stopped |
|
||||
| HTTP 200 + `success: false`, other error | failed, warning shown |
|
||||
| HTTP 4xx | failed, no retry |
|
||||
| HTTP 5xx / timeout / refused | failed after 2 attempts (0.5 s apart), warning shown |
|
||||
|
||||
Peer failures never block the FCP batch (fail-soft):
|
||||
- **start failed** → zenai counts 0 for that batch; operator informed.
|
||||
- **stop failed** → zenai keeps counting; operator must stop zenai manually.
|
||||
|
||||
FCP also raises a warning when it asked for several labels (`object_labels`) but
|
||||
the reply only carries a single `object_label` — that means the peer still
|
||||
counts one class only.
|
||||
|
||||
## 3. Work on the zenai side (not yet done)
|
||||
|
||||
Repo: `/home/jetson/Feedmill_Semarang_Project/zenai_nano_fcp` (device path
|
||||
`/opt/feedmill`).
|
||||
|
||||
### 3.1 Multi-label batches (required)
|
||||
|
||||
Today `batch_store.py` is single-label:
|
||||
- `_normalize_batch_label()` accepts only `sack` / `box`.
|
||||
- `start_new_batch()` stores one `object_label` and one `count`.
|
||||
- `record_counted_object_crossing()` **ignores** any crossing whose label does
|
||||
not equal the active batch label.
|
||||
|
||||
Needed: one batch that counts `sack` and `box` separately.
|
||||
|
||||
- `_normalize_batch_label` → normalise a **list** of labels
|
||||
(`object_labels: ["sack", "box"]`), keep the old single `object_label` field
|
||||
working for the zenai UI (it may send `object_label: "sack"`).
|
||||
- Batch state: keep `counts: {"sack": N, "box": M}` (total = `sum(counts.values())`).
|
||||
Migrate the old `count` int for backward compatibility.
|
||||
- `record_counted_object_crossing(track_id, object_label)`: count the crossing
|
||||
when the label is in the active batch's label set; keep per-label counters.
|
||||
The counted-event dedup key must include the label
|
||||
(`f"{label}:{track_id}"`), otherwise sack and box IDs collide.
|
||||
- `end_batch()` must persist per-label counts (DB migration needed for the
|
||||
`batches` table: add `counts_json` or `box_count`/`sack_count` columns).
|
||||
- Batch discard rule ("discard when 0 counted") must consider the **total**.
|
||||
|
||||
### 3.2 Forward the request body (required)
|
||||
|
||||
`counter_dashboard.py::_send_counter_command()` posts an **empty body**, so the
|
||||
JSON FCP sends is dropped before it reaches `counter_control.py`.
|
||||
|
||||
- `api_batch_start` must forward the full JSON body to
|
||||
`http://127.0.0.1:5000/api/batch/start` (and `api_batch_stop` likewise).
|
||||
- `counter_control.py` must read the body: `object_labels` (list) or
|
||||
`object_label` (single), plus the metadata (`source`, `fcp_batch_number`,
|
||||
`counting_date`, `plate`, `do_numbers`, `expected_sack`, `expected_box`).
|
||||
- Store the metadata on the zenai batch row (new columns or a JSON blob) so
|
||||
zenai history can be joined with FCP history by `source` + `fcp_batch_number`.
|
||||
|
||||
### 3.3 Optional API key (recommended)
|
||||
|
||||
- Accept `X-API-Key` on `/api/batch/start` and `/api/batch/stop`.
|
||||
- Validate **only when the header is present**, so the zenai dashboard UI keeps
|
||||
working unchanged.
|
||||
- Reject with HTTP 401 + `{"success": false, "error": "unauthorized"}` when the
|
||||
header is present but wrong. FCP treats 4xx as failed (no retry) and warns.
|
||||
|
||||
### 3.4 Idempotency (recommended)
|
||||
|
||||
- Start when a batch is already active → return the existing batch, HTTP 200
|
||||
(`status: "running"`). Already the case in `counter_control.py`; keep it.
|
||||
- Stop with no active batch → HTTP 200 `{"success": false, "error": "No active
|
||||
batch to stop"}`. Already the case; keep it (FCP treats it as success).
|
||||
- FCP re-sends a start when the operator presses "Mulai" twice; the peer must
|
||||
not create a second batch.
|
||||
|
||||
### 3.5 Reply shape (optional but recommended)
|
||||
|
||||
When the peer supports several labels it should answer with both:
|
||||
|
||||
```json
|
||||
{"success": true, "batch_number": 7, "object_labels": ["sack", "box"],
|
||||
"counts": {"sack": 12, "box": 3}, "status": "running"}
|
||||
```
|
||||
|
||||
FCP stops warning when `object_labels` is present in the reply.
|
||||
|
||||
## 4. Verification checklist (zenai side)
|
||||
|
||||
```bash
|
||||
# start (multi-label + metadata + api key)
|
||||
curl -s -X POST http://127.0.0.1:7000/api/batch/start \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H 'X-API-Key: <shared secret>' \
|
||||
-d '{"source":"fcp-semarang","object_label":"sack","object_labels":["sack","box"],
|
||||
"fcp_batch_number":12,"counting_date":"2026-11-13","plate":"B 1234 XYZ",
|
||||
"do_numbers":["DO-2026-0011"],"expected_sack":40,"expected_box":10,
|
||||
"started_at":"2026-11-13T09:12:03"}'
|
||||
|
||||
# stop
|
||||
curl -s -X POST http://127.0.0.1:7000/api/batch/stop \
|
||||
-H 'Content-Type: application/json' -H 'X-API-Key: <shared secret>' \
|
||||
-d '{"source":"fcp-semarang","fcp_batch_number":12,"counting_date":"2026-11-13",
|
||||
"plate":"B 1234 XYZ","net_sack":38,"net_box":9,"ended_at":"2026-11-13T10:04:57"}'
|
||||
```
|
||||
|
||||
Check:
|
||||
1. Reply has `success: true` and `object_labels: ["sack","box"]`.
|
||||
2. A sack crossing and a box crossing both raise the **total** count, and the
|
||||
per-label counters differ.
|
||||
3. The stored batch row keeps `source` / `fcp_batch_number` / plate / DO numbers.
|
||||
4. Stop replies with per-label counts and the row is persisted.
|
||||
|
||||
FCP side (from the Jetson, `PEER_API_URL` set):
|
||||
|
||||
```bash
|
||||
# manual batch start/stop in the operator UI -> watch the FCP log
|
||||
journalctl -u karung-counter-dashboard | grep PEER
|
||||
```
|
||||
|
||||
## 5. Where the FCP code lives
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `src/peer_sync.py` | outbound client (stdlib urllib, retry, fail-soft) |
|
||||
| `counter_dashboard.py` | hooks in `api_batch_start` / `api_batch_stop` |
|
||||
| `templates/operator.html`, `templates/monitoring.html` | operator warning |
|
||||
| `tests/test_peer_sync.py` | mock-peer tests |
|
||||
| `docs/configuration.md` | env keys |
|
||||
|
||||
FCP sends only for **manual** and **do_manual** batch modes; `auto` mode is not
|
||||
synced (auto batches are started by the pipeline, not by the operator).
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Outbound peer batch sync (FCP -> zenai_nano_fcp).
|
||||
|
||||
FCP is the count source of truth. When a manual batch starts/stops here the
|
||||
same event is pushed to the peer counter so both sides count the same load.
|
||||
|
||||
Fail-soft: a peer outage must never block an FCP batch. Callers get a
|
||||
structured result they can surface as an operator warning.
|
||||
|
||||
Env (deployment scope, .env — not config.yaml):
|
||||
PEER_API_URL peer base URL, e.g. http://10.38.250.21:7000
|
||||
empty (default) => peer sync disabled
|
||||
PEER_API_TOKEN optional shared secret, sent as X-API-Key header
|
||||
PEER_API_TIMEOUT per-request timeout seconds (default 5)
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
PATHS = {"start": "/api/batch/start", "stop": "/api/batch/stop"}
|
||||
ATTEMPTS = 2
|
||||
BACKOFF_SECONDS = 0.5
|
||||
DEFAULT_TIMEOUT = 5.0
|
||||
|
||||
|
||||
def peer_config(env=None):
|
||||
env = os.environ if env is None else env
|
||||
url = (env.get("PEER_API_URL") or "").strip().rstrip("/")
|
||||
token = (env.get("PEER_API_TOKEN") or "").strip()
|
||||
try:
|
||||
timeout = float(env.get("PEER_API_TIMEOUT") or DEFAULT_TIMEOUT)
|
||||
except (TypeError, ValueError):
|
||||
timeout = DEFAULT_TIMEOUT
|
||||
return {"url": url, "token": token, "timeout": timeout}
|
||||
|
||||
|
||||
def notify(action, payload, env=None):
|
||||
"""POST a batch event to the peer. Never raises."""
|
||||
cfg = peer_config(env)
|
||||
if action not in PATHS:
|
||||
return _result(action, "disabled", True, 0, None, "unknown action")
|
||||
if not cfg["url"]:
|
||||
return _result(action, "disabled", True, 0, None, None)
|
||||
|
||||
url = cfg["url"] + PATHS[action]
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if cfg["token"]:
|
||||
headers["X-API-Key"] = cfg["token"]
|
||||
|
||||
last_error = None
|
||||
attempts = 0
|
||||
for attempt in range(1, ATTEMPTS + 1):
|
||||
attempts = attempt
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=cfg["timeout"]) as resp:
|
||||
raw = resp.read().decode("utf-8", "replace")
|
||||
try:
|
||||
peer_body = json.loads(raw) if raw.strip() else {}
|
||||
except ValueError:
|
||||
peer_body = {"raw": raw[:200]}
|
||||
return _finalize(action, payload, peer_body, attempts)
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
body = e.read().decode("utf-8", "replace")[:200]
|
||||
except Exception:
|
||||
body = ""
|
||||
last_error = f"HTTP {e.code} {body}".strip()
|
||||
if e.code < 500:
|
||||
break # 4xx will not fix itself
|
||||
except Exception as e: # timeout, refused, DNS, ...
|
||||
last_error = f"{type(e).__name__}: {e}"
|
||||
if attempt < ATTEMPTS:
|
||||
time.sleep(BACKOFF_SECONDS)
|
||||
|
||||
warning = f"Peer {action} gagal: {last_error}"
|
||||
print(f"[PEER] {warning}")
|
||||
return _result(action, "failed", False, attempts, None, warning, last_error)
|
||||
|
||||
|
||||
def _finalize(action, payload, peer_body, attempts):
|
||||
"""Map a peer reply to ok/failed. Peer says success=false -> failure."""
|
||||
if peer_body.get("success") is False:
|
||||
err = str(peer_body.get("error") or "unknown error")
|
||||
if action == "stop" and "no active batch" in err.lower():
|
||||
# Peer already stopped -> nothing to do, treat as done.
|
||||
return _result(action, "ok", True, attempts, peer_body, None)
|
||||
warning = f"Peer {action} gagal: {err}"
|
||||
print(f"[PEER] {warning}")
|
||||
return _result(action, "failed", False, attempts, peer_body, warning, err)
|
||||
|
||||
warning = None
|
||||
labels = payload.get("object_labels") or []
|
||||
if len(labels) > 1 and peer_body.get("object_label") and not peer_body.get("object_labels"):
|
||||
one = peer_body.get("object_label")
|
||||
warning = (f"Peer hanya menerima satu label ({one}) — peer kemungkinan "
|
||||
"hanya menghitung satu kelas.")
|
||||
print(f"[PEER] {warning}")
|
||||
return _result(action, "ok", True, attempts, peer_body, warning)
|
||||
|
||||
|
||||
def _result(action, status, ok, attempts, peer_body, warning, error=None):
|
||||
return {
|
||||
"action": action,
|
||||
"status": status,
|
||||
"ok": ok,
|
||||
"attempts": attempts,
|
||||
"warning": warning,
|
||||
"error": error,
|
||||
"peer": peer_body,
|
||||
}
|
||||
@@ -618,6 +618,9 @@
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
await pollCurrentBatch();
|
||||
if (data.peer_sync && data.peer_sync.warning) {
|
||||
alert('Peringatan sinkronisasi device counterpart: ' + data.peer_sync.warning);
|
||||
}
|
||||
} else {
|
||||
alert('Gagal memulai batch: ' + (data.error || 'Terjadi kesalahan'));
|
||||
}
|
||||
@@ -633,6 +636,9 @@
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
await pollCurrentBatch();
|
||||
if (data.peer_sync && data.peer_sync.warning) {
|
||||
alert('Peringatan sinkronisasi device counterpart: ' + data.peer_sync.warning);
|
||||
}
|
||||
} else {
|
||||
alert('Gagal mengakhiri batch: ' + (data.error || 'Terjadi kesalahan'));
|
||||
}
|
||||
|
||||
@@ -821,6 +821,9 @@
|
||||
if (data.success) {
|
||||
await pollStatus();
|
||||
await loadStagedDos();
|
||||
if (data.peer_sync && data.peer_sync.warning) {
|
||||
alert('Peringatan sinkronisasi device counterpart: ' + data.peer_sync.warning);
|
||||
}
|
||||
} else {
|
||||
alert('Gagal memulai batch: ' + (data.error || 'Terjadi kesalahan'));
|
||||
}
|
||||
@@ -847,6 +850,9 @@
|
||||
if (data.success) {
|
||||
await pollStatus();
|
||||
await loadStagedDos();
|
||||
if (data.peer_sync && data.peer_sync.warning) {
|
||||
alert('Peringatan sinkronisasi device counterpart: ' + data.peer_sync.warning);
|
||||
}
|
||||
} else {
|
||||
alert('Gagal mengakhiri batch: ' + (data.error || 'Terjadi kesalahan'));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Tests for outbound peer batch sync (src/peer_sync.py). Stdlib only."""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from src.peer_sync import notify, peer_config
|
||||
|
||||
|
||||
class _Peer(BaseHTTPRequestHandler):
|
||||
"""Mock peer API: records requests, replays scripted replies."""
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", "0") or "0")
|
||||
raw = self.rfile.read(length).decode("utf-8") if length else "{}"
|
||||
body = json.loads(raw or "{}")
|
||||
self.server.received.append({
|
||||
"path": self.path,
|
||||
"body": body,
|
||||
"api_key": self.headers.get("X-API-Key"),
|
||||
})
|
||||
status, payload = self.server.replies.pop(0)
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def peer():
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Peer)
|
||||
srv.received = []
|
||||
srv.replies = []
|
||||
t = threading.Thread(target=srv.serve_forever, daemon=True)
|
||||
t.start()
|
||||
yield srv
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def _env(peer, **extra):
|
||||
env = {
|
||||
"PEER_API_URL": f"http://127.0.0.1:{peer.server_address[1]}",
|
||||
"PEER_API_TIMEOUT": "2",
|
||||
}
|
||||
env.update(extra)
|
||||
return env
|
||||
|
||||
|
||||
def test_peer_config_defaults():
|
||||
cfg = peer_config({})
|
||||
assert cfg["url"] == ""
|
||||
assert cfg["token"] == ""
|
||||
assert cfg["timeout"] == 5.0
|
||||
|
||||
|
||||
def test_notify_disabled_when_url_empty():
|
||||
res = notify("start", {"fcp_batch_number": 1}, env={})
|
||||
assert res["status"] == "disabled"
|
||||
assert res["ok"] is True
|
||||
assert res["warning"] is None
|
||||
|
||||
|
||||
def test_start_posts_expected_body_and_path(peer):
|
||||
peer.replies.append((200, {"success": True, "batch_number": 7,
|
||||
"object_label": "sack"}))
|
||||
payload = {"source": "fcp-semarang", "fcp_batch_number": 3,
|
||||
"object_labels": ["sack", "box"]}
|
||||
res = notify("start", payload, env=_env(peer))
|
||||
|
||||
assert res["status"] == "ok"
|
||||
assert res["ok"] is True
|
||||
assert res["attempts"] == 1
|
||||
sent = peer.received[0]
|
||||
assert sent["path"] == "/api/batch/start"
|
||||
assert sent["body"]["fcp_batch_number"] == 3
|
||||
assert sent["body"]["object_labels"] == ["sack", "box"]
|
||||
|
||||
|
||||
def test_api_key_header_sent_when_token_set(peer):
|
||||
peer.replies.append((200, {"success": True}))
|
||||
notify("start", {}, env=_env(peer, PEER_API_TOKEN="s3cret"))
|
||||
assert peer.received[0]["api_key"] == "s3cret"
|
||||
|
||||
|
||||
def test_stop_treats_no_active_batch_as_success(peer):
|
||||
peer.replies.append((200, {"success": False,
|
||||
"error": "No active batch to stop"}))
|
||||
res = notify("stop", {"fcp_batch_number": 3}, env=_env(peer))
|
||||
assert res["status"] == "ok"
|
||||
assert res["ok"] is True
|
||||
assert peer.received[0]["path"] == "/api/batch/stop"
|
||||
|
||||
|
||||
def test_single_label_reply_warns_for_multilabel_request(peer):
|
||||
peer.replies.append((200, {"success": True, "object_label": "sack"}))
|
||||
res = notify("start", {"object_labels": ["sack", "box"]}, env=_env(peer))
|
||||
assert res["status"] == "ok"
|
||||
assert res["warning"] and "sack" in res["warning"]
|
||||
|
||||
|
||||
def test_retries_once_then_succeeds(peer):
|
||||
peer.replies.append((500, {"success": False, "error": "boom"}))
|
||||
peer.replies.append((200, {"success": True}))
|
||||
res = notify("start", {}, env=_env(peer))
|
||||
assert res["status"] == "ok"
|
||||
assert res["attempts"] == 2
|
||||
assert len(peer.received) == 2
|
||||
|
||||
|
||||
def test_connection_refused_fails_soft(peer):
|
||||
env = _env(peer)
|
||||
peer.shutdown()
|
||||
peer.server_close() # port closed -> connection refused
|
||||
res = notify("start", {}, env=env)
|
||||
assert res["status"] == "failed"
|
||||
assert res["ok"] is False
|
||||
assert res["warning"]
|
||||
Reference in new issue
Block a user