verify-db-212x.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #!/usr/bin/env python3
  2. """Integration checks for the database 2.12.0 alignment.
  3. Three things no unit test can show, because each needs a running stack:
  4. 1. consecutiveFailures is counted by the server, so two failures arriving at
  5. once both land. Read-modify-write lost one of them.
  6. 2. A database-change trigger does not retrigger on the workflow's own writes,
  7. while still firing on somebody else's.
  8. 3. A duplicate insert is reported as AlreadyExists rather than a generic
  9. database error, and from 2.12.1 a duplicate primary ID says so by name:
  10. reason "duplicate_id" and the id already holding it. Before 2.12.1 that
  11. case threw a bare runtime_error and reached clients as Internal.
  12. Run against a live webserver + runner:
  13. python3 scripts/verify-db-212x.py
  14. """
  15. import json
  16. import os
  17. import sys
  18. import time
  19. import urllib.error
  20. import urllib.request
  21. API = os.environ.get("SMARTBOTIC_API", "http://localhost:8090").rstrip("/") + "/api/v1"
  22. failures = []
  23. def call(method, path, token=None, body=None, raw=False):
  24. data = json.dumps(body).encode() if body is not None else None
  25. req = urllib.request.Request(API + path, data=data, method=method)
  26. req.add_header("Content-Type", "application/json")
  27. if token:
  28. req.add_header("Authorization", "Bearer " + token)
  29. try:
  30. with urllib.request.urlopen(req, timeout=60) as res:
  31. payload = res.read()
  32. return json.loads(payload) if payload else {}
  33. except urllib.error.HTTPError as e:
  34. if raw:
  35. return {"__status": e.code, "__body": e.read().decode()[:400]}
  36. raise SystemExit(f"{method} {path} failed: {e.code} {e.read().decode()[:300]}")
  37. def check(what, ok, detail=""):
  38. print((" ok " if ok else " FAIL ") + what)
  39. if not ok:
  40. failures.append(what)
  41. if detail:
  42. print(" " + detail)
  43. def main():
  44. token = call("POST", "/auth/login", body={"username": "admin", "password": "admin"})["accessToken"]
  45. project = call("GET", "/projects", token)["projects"][0]["_id"]
  46. # --- 1. the failure count is the server's, and survives concurrency -------
  47. wf = call("POST", "/workflows", token, {
  48. "name": "zz verify: failing workflow", "active": False, "projectId": project,
  49. "nodes": [
  50. {"id": "n1", "name": "Trigger", "type": "click-trigger",
  51. "position": {"x": 0, "y": 0}, "config": {}},
  52. {"id": "n2", "name": "Boom", "type": "code", "position": {"x": 0, "y": 100},
  53. "config": {"code": "throw new Error('planned failure');"}},
  54. ],
  55. "connections": [{"sourceNodeId": "n1", "sourceOutput": "main",
  56. "targetNodeId": "n2", "targetInput": "data"}],
  57. })
  58. wf_id = wf.get("id") or wf.get("_id")
  59. try:
  60. # Fired together on purpose: read-modify-write loses one of these.
  61. runs = [call("POST", f"/workflows/{wf_id}/execute", token, {})["executionId"]
  62. for _ in range(4)]
  63. # A just-dispatched execution is not queryable for a moment - the
  64. # record is written after the call returns - so a 404 here means "not
  65. # yet", not "gone". raw=True keeps it from aborting the run.
  66. def status_of(execution_id):
  67. got = call("GET", f"/executions/{execution_id}", token, raw=True)
  68. if got.get("__status"):
  69. return "pending"
  70. return got.get("status") or "pending"
  71. for _ in range(40):
  72. done = [status_of(r) for r in runs]
  73. if all(st not in ("running", "pending") for st in done):
  74. break
  75. time.sleep(2)
  76. time.sleep(3) # the count is written after the run finishes
  77. streak = call("GET", f"/workflows/{wf_id}", token).get("consecutiveFailures", 0)
  78. check(f"4 concurrent failures all counted (consecutiveFailures={streak})",
  79. streak == 4, "read-modify-write would report fewer than 4")
  80. finally:
  81. call("DELETE", f"/workflows/{wf_id}", token)
  82. # --- 2. a database-change trigger does not feed itself -------------------
  83. # Two workflows, which proves both halves at once:
  84. # A watches the collection AND writes to it. Its own writes must be
  85. # ignored, or it retriggers once per write for as long as it keeps
  86. # writing.
  87. # B only writes to the collection. Its writes are somebody else's and
  88. # must still trigger A - a watcher that ignored everything would pass
  89. # the first half and be useless.
  90. watched = "zz_verify_selftrigger"
  91. def writer(name):
  92. return call("POST", "/workflows", token, {
  93. "name": name, "active": False, "projectId": project,
  94. # Without an explicit grant a workflow may only write its own wf_
  95. # collection: "No write access to collection", and then nothing is
  96. # written, no event fires, and a watcher that is working perfectly
  97. # looks broken.
  98. "settings": {"storagePermissions": {"collections": {watched: "read-write"}}},
  99. "nodes": [
  100. {"id": "t", "name": "Go", "type": "click-trigger",
  101. "position": {"x": 0, "y": 0}, "config": {}},
  102. {"id": "w", "name": "Write", "type": "storage-insert",
  103. "position": {"x": 240, "y": 0},
  104. "config": {"collectionSource": "manual", "collectionManual": watched,
  105. "documentData": json.dumps({"from": name})}},
  106. ],
  107. "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
  108. "targetNodeId": "w", "targetInput": "data"}],
  109. })
  110. watcher = call("POST", "/workflows", token, {
  111. "name": "zz verify: watcher that writes back", "active": False, "projectId": project,
  112. "settings": {"storagePermissions": {"collections": {watched: "read-write"}}},
  113. "nodes": [
  114. {"id": "t", "name": "OnChange", "type": "database-change",
  115. "position": {"x": 0, "y": 0},
  116. "config": {"collection": watched, "eventTypes": ["insert", "update"],
  117. "emitOnFirstRun": False}},
  118. {"id": "w", "name": "WriteBack", "type": "storage-insert",
  119. "position": {"x": 240, "y": 0},
  120. "config": {"collectionSource": "manual", "collectionManual": watched,
  121. "documentData": json.dumps({"from": "the watcher itself"})}},
  122. ],
  123. "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
  124. "targetNodeId": "w", "targetInput": "data"}],
  125. })
  126. watcher_id = watcher.get("id") or watcher.get("_id")
  127. poker = writer("zz verify: outside writer")
  128. poker_id = poker.get("id") or poker.get("_id")
  129. def runs_of(wf):
  130. return len(call("GET", f"/executions?workflowId={wf}&pageSize=50",
  131. token).get("executions", []))
  132. try:
  133. call("POST", f"/workflows/{watcher_id}/activate", token, {})
  134. time.sleep(4) # let the subscription open
  135. before = runs_of(watcher_id)
  136. # Somebody else writes. This one must reach the watcher.
  137. call("POST", f"/workflows/{poker_id}/execute", token, {})
  138. # Long enough that an unbroken loop would be unmistakable: every run
  139. # writes once, so the count would climb for as long as we wait.
  140. time.sleep(25)
  141. grew = runs_of(watcher_id) - before
  142. check(f"an outside write reached the watcher (ran {grew} time(s))",
  143. grew >= 1,
  144. "the watcher never fired - it is now ignoring writes it should react to")
  145. check(f"the watcher did not feed itself (ran {grew} time(s), not a climbing count)",
  146. grew <= 3,
  147. "it is still retriggering on its own writes")
  148. finally:
  149. call("POST", f"/workflows/{watcher_id}/deactivate", token, {})
  150. call("DELETE", f"/workflows/{watcher_id}", token)
  151. call("DELETE", f"/workflows/{poker_id}", token)
  152. # --- 3. a duplicate is classified, not flattened -------------------------
  153. # Inserting the same document id twice. Before 2.12.0 the client dropped
  154. # the server's classification and this arrived as a generic database
  155. # error; it must now come back as a conflict, naming the id.
  156. dup_collection = "zz_verify_duplicate"
  157. dup_wf = call("POST", "/workflows", token, {
  158. "name": "zz verify: duplicate insert", "active": False, "projectId": project,
  159. "settings": {"storagePermissions": {"collections": {dup_collection: "read-write"}}},
  160. "nodes": [
  161. {"id": "t", "name": "Go", "type": "click-trigger",
  162. "position": {"x": 0, "y": 0}, "config": {}},
  163. {"id": "c", "name": "Twice", "type": "code", "position": {"x": 240, "y": 0},
  164. "config": {"code": (
  165. "var id = 'fixed-id-for-the-duplicate-check';\n"
  166. "smartbotic.storage.insert('" + dup_collection + "', { n: 1 }, id);\n"
  167. "var second = smartbotic.storage.insert('" + dup_collection + "', { n: 2 }, id);\n"
  168. "return { success: second.success === true, error: String(second.error || '') };")},
  169. },
  170. ],
  171. "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
  172. "targetNodeId": "c", "targetInput": "data"}],
  173. })
  174. dup_wf_id = dup_wf.get("id") or dup_wf.get("_id")
  175. try:
  176. run = call("POST", f"/workflows/{dup_wf_id}/execute", token, {})["executionId"]
  177. detail = {}
  178. for _ in range(30):
  179. got = call("GET", f"/executions/{run}", token, raw=True)
  180. if not got.get("__status") and got.get("status") not in ("running", "pending", None):
  181. detail = got
  182. break
  183. time.sleep(2)
  184. node = next((n for n in detail.get("nodeExecutions", []) if n.get("nodeId") == "c"), {})
  185. message = ((node.get("output") or {}).get("result") or {}).get("error", "") or node.get("error", "")
  186. # Looking for words like "exist" was too weak: 2.12.0 already said
  187. # "already exists" in a bare Internal error, so that check passed on the
  188. # version it was meant to distinguish. 2.12.1 made a duplicate primary
  189. # id a typed refusal, so the message can now be held to naming the
  190. # reason AND the id already holding it - neither of which 2.12.0 carried.
  191. low = message.lower()
  192. names_reason = "duplicate_id" in low
  193. names_id = "fixed-id-for-the-duplicate-check" in low
  194. check("a duplicate insert names the reason and the conflicting id",
  195. names_reason and names_id,
  196. f"reason={names_reason} id={names_reason and names_id}, message was: {message[:200]!r}")
  197. finally:
  198. call("DELETE", f"/workflows/{dup_wf_id}", token)
  199. print()
  200. if failures:
  201. print(f"FAILED {len(failures)} check(s)")
  202. return 1
  203. print("all checks passed")
  204. return 0
  205. if __name__ == "__main__":
  206. sys.exit(main())