|
|
@@ -0,0 +1,224 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
+"""Integration checks for the database 2.12.0 alignment.
|
|
|
+
|
|
|
+Three things no unit test can show, because each needs a running stack:
|
|
|
+
|
|
|
+ 1. consecutiveFailures is counted by the server, so two failures arriving at
|
|
|
+ once both land. Read-modify-write lost one of them.
|
|
|
+ 2. A database-change trigger does not retrigger on the workflow's own writes,
|
|
|
+ while still firing on somebody else's.
|
|
|
+ 3. A duplicate insert is reported as AlreadyExists rather than a generic
|
|
|
+ database error.
|
|
|
+
|
|
|
+Run against a live webserver + runner:
|
|
|
+
|
|
|
+ python3 scripts/verify-db-2120.py
|
|
|
+"""
|
|
|
+import json
|
|
|
+import os
|
|
|
+import sys
|
|
|
+import time
|
|
|
+import urllib.error
|
|
|
+import urllib.request
|
|
|
+
|
|
|
+API = os.environ.get("SMARTBOTIC_API", "http://localhost:8090").rstrip("/") + "/api/v1"
|
|
|
+failures = []
|
|
|
+
|
|
|
+
|
|
|
+def call(method, path, token=None, body=None, raw=False):
|
|
|
+ data = json.dumps(body).encode() if body is not None else None
|
|
|
+ req = urllib.request.Request(API + path, data=data, method=method)
|
|
|
+ req.add_header("Content-Type", "application/json")
|
|
|
+ if token:
|
|
|
+ req.add_header("Authorization", "Bearer " + token)
|
|
|
+ try:
|
|
|
+ with urllib.request.urlopen(req, timeout=60) as res:
|
|
|
+ payload = res.read()
|
|
|
+ return json.loads(payload) if payload else {}
|
|
|
+ except urllib.error.HTTPError as e:
|
|
|
+ if raw:
|
|
|
+ return {"__status": e.code, "__body": e.read().decode()[:400]}
|
|
|
+ raise SystemExit(f"{method} {path} failed: {e.code} {e.read().decode()[:300]}")
|
|
|
+
|
|
|
+
|
|
|
+def check(what, ok, detail=""):
|
|
|
+ print((" ok " if ok else " FAIL ") + what)
|
|
|
+ if not ok:
|
|
|
+ failures.append(what)
|
|
|
+ if detail:
|
|
|
+ print(" " + detail)
|
|
|
+
|
|
|
+
|
|
|
+def main():
|
|
|
+ token = call("POST", "/auth/login", body={"username": "admin", "password": "admin"})["accessToken"]
|
|
|
+ project = call("GET", "/projects", token)["projects"][0]["_id"]
|
|
|
+
|
|
|
+ # --- 1. the failure count is the server's, and survives concurrency -------
|
|
|
+ wf = call("POST", "/workflows", token, {
|
|
|
+ "name": "zz verify: failing workflow", "active": False, "projectId": project,
|
|
|
+ "nodes": [
|
|
|
+ {"id": "n1", "name": "Trigger", "type": "click-trigger",
|
|
|
+ "position": {"x": 0, "y": 0}, "config": {}},
|
|
|
+ {"id": "n2", "name": "Boom", "type": "code", "position": {"x": 0, "y": 100},
|
|
|
+ "config": {"code": "throw new Error('planned failure');"}},
|
|
|
+ ],
|
|
|
+ "connections": [{"sourceNodeId": "n1", "sourceOutput": "main",
|
|
|
+ "targetNodeId": "n2", "targetInput": "data"}],
|
|
|
+ })
|
|
|
+ wf_id = wf.get("id") or wf.get("_id")
|
|
|
+ try:
|
|
|
+ # Fired together on purpose: read-modify-write loses one of these.
|
|
|
+ runs = [call("POST", f"/workflows/{wf_id}/execute", token, {})["executionId"]
|
|
|
+ for _ in range(4)]
|
|
|
+ # A just-dispatched execution is not queryable for a moment - the
|
|
|
+ # record is written after the call returns - so a 404 here means "not
|
|
|
+ # yet", not "gone". raw=True keeps it from aborting the run.
|
|
|
+ def status_of(execution_id):
|
|
|
+ got = call("GET", f"/executions/{execution_id}", token, raw=True)
|
|
|
+ if got.get("__status"):
|
|
|
+ return "pending"
|
|
|
+ return got.get("status") or "pending"
|
|
|
+
|
|
|
+ for _ in range(40):
|
|
|
+ done = [status_of(r) for r in runs]
|
|
|
+ if all(st not in ("running", "pending") for st in done):
|
|
|
+ break
|
|
|
+ time.sleep(2)
|
|
|
+ time.sleep(3) # the count is written after the run finishes
|
|
|
+ streak = call("GET", f"/workflows/{wf_id}", token).get("consecutiveFailures", 0)
|
|
|
+ check(f"4 concurrent failures all counted (consecutiveFailures={streak})",
|
|
|
+ streak == 4, "read-modify-write would report fewer than 4")
|
|
|
+ finally:
|
|
|
+ call("DELETE", f"/workflows/{wf_id}", token)
|
|
|
+
|
|
|
+ # --- 2. a database-change trigger does not feed itself -------------------
|
|
|
+ # Two workflows, which proves both halves at once:
|
|
|
+ # A watches the collection AND writes to it. Its own writes must be
|
|
|
+ # ignored, or it retriggers once per write for as long as it keeps
|
|
|
+ # writing.
|
|
|
+ # B only writes to the collection. Its writes are somebody else's and
|
|
|
+ # must still trigger A - a watcher that ignored everything would pass
|
|
|
+ # the first half and be useless.
|
|
|
+ watched = "zz_verify_selftrigger"
|
|
|
+
|
|
|
+ def writer(name):
|
|
|
+ return call("POST", "/workflows", token, {
|
|
|
+ "name": name, "active": False, "projectId": project,
|
|
|
+ # Without an explicit grant a workflow may only write its own wf_
|
|
|
+ # collection: "No write access to collection", and then nothing is
|
|
|
+ # written, no event fires, and a watcher that is working perfectly
|
|
|
+ # looks broken.
|
|
|
+ "settings": {"storagePermissions": {"collections": {watched: "read-write"}}},
|
|
|
+ "nodes": [
|
|
|
+ {"id": "t", "name": "Go", "type": "click-trigger",
|
|
|
+ "position": {"x": 0, "y": 0}, "config": {}},
|
|
|
+ {"id": "w", "name": "Write", "type": "storage-insert",
|
|
|
+ "position": {"x": 240, "y": 0},
|
|
|
+ "config": {"collectionSource": "manual", "collectionManual": watched,
|
|
|
+ "documentData": json.dumps({"from": name})}},
|
|
|
+ ],
|
|
|
+ "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
|
|
|
+ "targetNodeId": "w", "targetInput": "data"}],
|
|
|
+ })
|
|
|
+
|
|
|
+ watcher = call("POST", "/workflows", token, {
|
|
|
+ "name": "zz verify: watcher that writes back", "active": False, "projectId": project,
|
|
|
+ "settings": {"storagePermissions": {"collections": {watched: "read-write"}}},
|
|
|
+ "nodes": [
|
|
|
+ {"id": "t", "name": "OnChange", "type": "database-change",
|
|
|
+ "position": {"x": 0, "y": 0},
|
|
|
+ "config": {"collection": watched, "eventTypes": ["insert", "update"],
|
|
|
+ "emitOnFirstRun": False}},
|
|
|
+ {"id": "w", "name": "WriteBack", "type": "storage-insert",
|
|
|
+ "position": {"x": 240, "y": 0},
|
|
|
+ "config": {"collectionSource": "manual", "collectionManual": watched,
|
|
|
+ "documentData": json.dumps({"from": "the watcher itself"})}},
|
|
|
+ ],
|
|
|
+ "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
|
|
|
+ "targetNodeId": "w", "targetInput": "data"}],
|
|
|
+ })
|
|
|
+ watcher_id = watcher.get("id") or watcher.get("_id")
|
|
|
+ poker = writer("zz verify: outside writer")
|
|
|
+ poker_id = poker.get("id") or poker.get("_id")
|
|
|
+
|
|
|
+ def runs_of(wf):
|
|
|
+ return len(call("GET", f"/executions?workflowId={wf}&pageSize=50",
|
|
|
+ token).get("executions", []))
|
|
|
+
|
|
|
+ try:
|
|
|
+ call("POST", f"/workflows/{watcher_id}/activate", token, {})
|
|
|
+ time.sleep(4) # let the subscription open
|
|
|
+ before = runs_of(watcher_id)
|
|
|
+
|
|
|
+ # Somebody else writes. This one must reach the watcher.
|
|
|
+ call("POST", f"/workflows/{poker_id}/execute", token, {})
|
|
|
+
|
|
|
+ # Long enough that an unbroken loop would be unmistakable: every run
|
|
|
+ # writes once, so the count would climb for as long as we wait.
|
|
|
+ time.sleep(25)
|
|
|
+ grew = runs_of(watcher_id) - before
|
|
|
+
|
|
|
+ check(f"an outside write reached the watcher (ran {grew} time(s))",
|
|
|
+ grew >= 1,
|
|
|
+ "the watcher never fired - it is now ignoring writes it should react to")
|
|
|
+ check(f"the watcher did not feed itself (ran {grew} time(s), not a climbing count)",
|
|
|
+ grew <= 3,
|
|
|
+ "it is still retriggering on its own writes")
|
|
|
+ finally:
|
|
|
+ call("POST", f"/workflows/{watcher_id}/deactivate", token, {})
|
|
|
+ call("DELETE", f"/workflows/{watcher_id}", token)
|
|
|
+ call("DELETE", f"/workflows/{poker_id}", token)
|
|
|
+
|
|
|
+ # --- 3. a duplicate is classified, not flattened -------------------------
|
|
|
+ # Inserting the same document id twice. Before 2.12.0 the client dropped
|
|
|
+ # the server's classification and this arrived as a generic database
|
|
|
+ # error; it must now come back as a conflict, naming the id.
|
|
|
+ dup_collection = "zz_verify_duplicate"
|
|
|
+ dup_wf = call("POST", "/workflows", token, {
|
|
|
+ "name": "zz verify: duplicate insert", "active": False, "projectId": project,
|
|
|
+ "settings": {"storagePermissions": {"collections": {dup_collection: "read-write"}}},
|
|
|
+ "nodes": [
|
|
|
+ {"id": "t", "name": "Go", "type": "click-trigger",
|
|
|
+ "position": {"x": 0, "y": 0}, "config": {}},
|
|
|
+ {"id": "c", "name": "Twice", "type": "code", "position": {"x": 240, "y": 0},
|
|
|
+ "config": {"code": (
|
|
|
+ "var id = 'fixed-id-for-the-duplicate-check';\n"
|
|
|
+ "smartbotic.storage.insert('" + dup_collection + "', { n: 1 }, id);\n"
|
|
|
+ "var second = smartbotic.storage.insert('" + dup_collection + "', { n: 2 }, id);\n"
|
|
|
+ "return { success: second.success === true, error: String(second.error || '') };")},
|
|
|
+ },
|
|
|
+ ],
|
|
|
+ "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
|
|
|
+ "targetNodeId": "c", "targetInput": "data"}],
|
|
|
+ })
|
|
|
+ dup_wf_id = dup_wf.get("id") or dup_wf.get("_id")
|
|
|
+ try:
|
|
|
+ run = call("POST", f"/workflows/{dup_wf_id}/execute", token, {})["executionId"]
|
|
|
+ detail = {}
|
|
|
+ for _ in range(30):
|
|
|
+ got = call("GET", f"/executions/{run}", token, raw=True)
|
|
|
+ if not got.get("__status") and got.get("status") not in ("running", "pending", None):
|
|
|
+ detail = got
|
|
|
+ break
|
|
|
+ time.sleep(2)
|
|
|
+ node = next((n for n in detail.get("nodeExecutions", []) if n.get("nodeId") == "c"), {})
|
|
|
+ message = ((node.get("output") or {}).get("result") or {}).get("error", "") or node.get("error", "")
|
|
|
+ # The point is that the message now says what the objection WAS, rather
|
|
|
+ # than only that a write failed.
|
|
|
+ classified = any(word in message.lower()
|
|
|
+ for word in ("exist", "duplicate", "conflict", "unique"))
|
|
|
+ check("a duplicate insert says it is a duplicate",
|
|
|
+ classified, f"message was: {message[:160]!r}")
|
|
|
+ finally:
|
|
|
+ call("DELETE", f"/workflows/{dup_wf_id}", token)
|
|
|
+
|
|
|
+ print()
|
|
|
+ if failures:
|
|
|
+ print(f"FAILED {len(failures)} check(s)")
|
|
|
+ return 1
|
|
|
+ print("all checks passed")
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ sys.exit(main())
|