verify-db-2120.py 10 KB

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