mirror of
https://github.com/penpot/penpot.git
synced 2026-11-17 07:30:35 +00:00
* ♻️ Wait on signals instead of event-loop turns `wait-for` counted its budget in event-loop turns (50 x `setTimeout 0`, about 54 ms idle), so a delivery that travelled through the RxJS async scheduler could arrive after the wait gave up. It now accepts a `:signal`: the predicate is re-checked on every emission and the wait resolves on the event that changes the state. The ceiling (5000 ms) only bounds failure when a signal is given, and stays a poll budget for the waits that have nothing to listen to. `wait-for-store` wraps the store's input stream, which notifies its subscribers after applying the update. The five explicit `:max-ticks` sites move to `:timeout-ms` in the same change, so the old option never lives in a state where destructuring silently ignores it. New `frontend-tests.helpers.async-test` pins the contract: a late delivery resolves, a store signal resolves on the event without a poll, an already-true predicate does not yield, a never-true predicate records one failure within the ceiling, and a resolved wait stops listening. AI-assisted-by: deepseek-v4.1-flash * ♻️ Wait for the persistence requests on their own stream The persistence tests waited for `(= N (count @requests))` by polling the atom at every event-loop turn. The mocked transport now pushes each request into a `requests$` subject, and those 59 waits pass it as `:signal`, so they resolve on the request that makes the count true. The two predicates that mix the request count with the store state merge both signals. The wait that flaked (`the other file's edit is sent next`, in the rollback test) is one of these: it no longer depends on a turn budget, and it cannot lose the delivery. AI-assisted-by: deepseek-v4.1-flash * ♻️ Wait for the store event in the store backed tests 153 waits whose predicate reads the store now go through `wait-for-store`, so they resolve on the store event that changes the state instead of polling at every event-loop turn. The count is 153, not the 162 the plan estimated: nine of them read the store through a helper (`fill-color`, `shape-name`, `copy-children`) rather than `@store`. The five sites that carried an explicit ceiling drop it, since with an event the ceiling only bounds failure. Resolving on the event exposes the places where the poll was really a pause for a side effect to advance: - `tokens-source-test` emitted `unlink-file-from-library`, a watch that chains a second `rp/cmd!` after an async hop. The store signal fires before the chain runs (the event itself dissocs the library), so the mock scope closed in flight and the second call reached the real HTTP layer. The test now waits for that second call, through the mock. - `persistence-rollback-test` drives the persistence pipeline step by step; two of its waits are the pause before the next emit, not an effect, so they keep the poll. AI-assisted-by: deepseek-v4.1-flash * 📚 Document the wait contract and what still polls `mem:frontend/testing` described `wait-for` as an immediate check plus a bounded poll. It now waits on a signal, and the ceiling only bounds failure; `wait-for-store` and the persistence `requests$` subject are how a wait resolves on the event that changes the state. The waits with nothing to listen to keep the poll, and the memory names them. The two traps that cost a red suite are recorded too: a wait that means "the side effect advanced" has no event and keeps the poll, and a store-state wait can close the mock scope before the flow it observes ends, so the chain's last RPC call has to be awaited through the mock. AI-assisted-by: deepseek-v4.1-flash * ♻️ Give the wait wrapper a single signal `wait-for-store` built its options with `assoc`, so it replaced the `:signal` a caller passed. The two waits whose predicate reads both the store and the request counter relied on a merged signal that was being discarded; they now pass it to `wait-for` themselves, and the wrapper takes no options. That merge was the safety net for a request counted after the store event, and it was inert. The helper also reports why a wait failed (ceiling, ended signal, or an error with its cause) instead of calling all three a timeout, counts the predicate evaluations in the late-delivery case to prove the signal path does not poll, reads the clock through `app.common.time` in the helper and the test, and the test's turn probe cancels its timer. The copyright header of `helpers/async.cljs` stays as the previous commit left it, matching the majority spelling. AI-assisted-by: deepseek-v4.1-flash * ♻️ Give the cycle counter a signal too Two waits in the retry tests read the store and the `cycles` atom, which the `slow-cycle-timer` double fills inside the persistence watch. They passed only the store signal, so a counter change could not wake them: the same latent race the previous commit removed from the request count. The double now also emits each new cycle into a `cycles$` subject, and both waits pass the merged signal to `wait-for`. The public `wait-for` docstring names the three failure reasons, and the message for a failed signal bounds the cause text: the exception message when there is one, otherwise the printed value inside a try, cut at 500 characters. AI-assisted-by: deepseek-v4.1-flash * ♻️ Stop the error handlers flooding the test log Four tests in `main-errors-test` run a real error handler end to end. Those handlers print the cause with `ex/print-throwable` before notifying, which is what a developer wants in the app; in a test it only writes console noise. One of them replays 10,000 offline errors, so a run carried 10,006 dumps: 190,010 of its 192,682 lines, 13.8 MB, well past the ~4 MB where GitHub truncates a step log and takes the summary and any failing assertion with it. The tests stub `ex/print-throwable` with a no-op for the duration of their mock scope. The handlers still run, the assertions do not change, and the 10,000-error loop still proves the governor emits once. A full run now logs 2,583 lines and 384 KB. The single block that remains comes from the re-entrancy guard, which prints its own notice on purpose. AI-assisted-by: deepseek-v4.1-flash * ♻️ Silence the deliberate WASM panic in its test `get-svg-markup` logs a WASM panic with `console.error` before returning empty, and `get-svg-markup-swallows-wasm-errors` sends two panics through it on purpose. That was two 35-line dumps in which the exception printed its own `data`, `arr` and protocol masks, and it reads like a failure that the suite is hiding. The test replaces `(.-error js/console)` for its body and restores it in a `finally`. The assertions and the helper stay as they are: the same panic answered with a different stack would still show up, because only this test silences the console. AI-assisted-by: deepseek-v4.1-flash * 🐛 Use real timer for wait-poll ceiling wait-poll read the app clock (ct/now), so tests freezing that clock never reached the deadline and hung instead of failing. Track expiry with a real setTimeout flag, pass timeout-ms through wait-signal and wait-for, and cover the frozen-clock case with a regression test. AI-assisted-by: muse-spark-1.3-contributor
190 lines
7.2 KiB
Clojure
190 lines
7.2 KiB
Clojure
;; This Source Code Form is subject to the terms of the Mozilla Public
|
|
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
;;
|
|
;; Copyright (c) KALEIDOS SUBSIDIARY SL
|
|
|
|
(ns frontend-tests.helpers.async
|
|
"Async-first plumbing for ClojureScript tests.
|
|
|
|
Lets a test read sequentially while presupposing asynchronous APIs:
|
|
triggers run, effects are awaited as promises, and `done` always runs
|
|
at the end. Relies on two platform properties:
|
|
|
|
- `cljs.test` keeps its env in a `set!` var, so assertions inside
|
|
deferred ticks are still counted.
|
|
- RxJS delivers `observe-on :async` notifications in scheduling (FIFO)
|
|
order, so awaiting the last scheduled delivery observes every effect
|
|
scheduled before it."
|
|
(:require
|
|
[beicon.v2.core :as rx]
|
|
[cljs.test :as t :include-macros true]
|
|
[potok.v2.core :as ptk]))
|
|
|
|
(defn ->promise
|
|
"Coerces a single-value observable into a js/Promise that resolves
|
|
with its first value (or rejects on error)."
|
|
[ob]
|
|
(js/Promise. (fn [resolve reject] (rx/subs! resolve reject ob))))
|
|
|
|
(defn ^:async await-response
|
|
"Pushes `value` into the `response` subject and resolves once the last
|
|
recorded request completes, delivery included.
|
|
|
|
The promise subscribes BEFORE pushing: subscribing after the push
|
|
would never resolve. Request entries are maps holding the request
|
|
observable under `:req`."
|
|
[requests response value]
|
|
(let [p (->promise (:req (last @requests)))]
|
|
(rx/push! response value)
|
|
(await p)))
|
|
|
|
(defn settle
|
|
"Resolves on the next macrotask, letting scheduled deliveries land.
|
|
Await it before asserting absence: silence is only meaningful once the
|
|
queue had a chance to deliver."
|
|
[]
|
|
(js/Promise. (fn [resolve] (js/setTimeout resolve 0))))
|
|
|
|
(defn observe
|
|
"Subscribes to `ob` forcing asynchronous delivery through `observe-on
|
|
:async` — even when the source is synchronous — and returns a promise
|
|
resolving once the stream terminates.
|
|
|
|
Keyword args: `:on-next` per value, `:on-error` (handled errors resolve;
|
|
unhandled reject), `:on-complete` on clean termination, `:timeout-ms`
|
|
(default 2000). Asserts the stream is provided: resolving nil would let
|
|
a test pass without observing anything. Rejects on timeout instead of
|
|
hanging."
|
|
[ob & {:keys [on-next on-error on-complete timeout-ms]
|
|
:or {timeout-ms 2000}}]
|
|
(assert (some? ob) "observe requires an observable stream")
|
|
(js/Promise.
|
|
(fn [resolve reject]
|
|
(let [timer (js/setTimeout
|
|
#(reject (ex-info "Stream did not terminate in time" {}))
|
|
timeout-ms)
|
|
settle (fn [f v]
|
|
(js/clearTimeout timer)
|
|
(f v))]
|
|
(->> ob
|
|
(rx/observe-on :async)
|
|
(rx/subs!
|
|
(fn [v] (when on-next (on-next v)))
|
|
(fn [e]
|
|
(if on-error
|
|
(do (on-error e) (settle resolve nil))
|
|
(settle reject e)))
|
|
(fn []
|
|
(when on-complete (on-complete))
|
|
(settle resolve nil))))))))
|
|
|
|
(def ^:private default-timeout-ms
|
|
"Ceiling of a wait, in real milliseconds. With a signal it only bounds
|
|
the failure: a wait that resolves on an event never reaches it. Without
|
|
a signal it is the poll budget."
|
|
5000)
|
|
|
|
(defn- ^:async poll
|
|
[pred msg expired?]
|
|
(cond
|
|
(pred) nil
|
|
@expired? (t/is false (str "Timed out waiting for: " msg))
|
|
:else (do (await (settle))
|
|
(await (poll pred msg expired?)))))
|
|
|
|
(defn- ^:async wait-poll
|
|
[pred msg timeout-ms]
|
|
(let [expired? (atom false)
|
|
timer (js/setTimeout #(reset! expired? true) timeout-ms)]
|
|
(await (poll pred msg expired?))
|
|
(js/clearTimeout timer)))
|
|
|
|
(defn- cause-text
|
|
"Readable, bounded text for a signal error: its message when it has one,
|
|
otherwise the printed value inside a `try` (a cyclic value would not print),
|
|
and never more than 500 characters."
|
|
[cause]
|
|
(let [text (or (ex-message cause)
|
|
(try
|
|
(pr-str cause)
|
|
(catch :default _ "#<unprintable>")))]
|
|
(if (> (count text) 500)
|
|
(str (subs text 0 500) "…")
|
|
text)))
|
|
|
|
(defn- wait-signal
|
|
"Resolves when `pred` holds, re-checking it on every emission of `signal`.
|
|
|
|
The timeout only bounds failure: it records the failure and resolves, so
|
|
the caller never hangs. A signal that ends or fails without the predicate
|
|
holding is reported with its own reason. The subscription is disposed on
|
|
every path."
|
|
[pred msg signal timeout-ms]
|
|
(js/Promise.
|
|
(fn [resolve]
|
|
(let [done? (atom false)
|
|
sub* (atom nil)
|
|
timer* (atom nil)
|
|
stop (fn []
|
|
(when-let [s @sub*] (rx/dispose! s))
|
|
(when-let [t @timer*] (js/clearTimeout t)))
|
|
fail (fn [text]
|
|
(when-not @done?
|
|
(reset! done? true)
|
|
(stop)
|
|
(t/is false text)
|
|
(resolve nil)))
|
|
finish (fn []
|
|
(when-not @done?
|
|
(reset! done? true)
|
|
(stop)
|
|
(resolve nil)))]
|
|
(reset! timer*
|
|
(js/setTimeout #(fail (str "Timed out waiting for: " msg))
|
|
timeout-ms))
|
|
(reset! sub*
|
|
(rx/subs!
|
|
(fn [_] (when (pred) (finish)))
|
|
(fn [cause]
|
|
(if (pred)
|
|
(finish)
|
|
(fail (str "Signal failed while waiting for: " msg ": "
|
|
(cause-text cause)))))
|
|
(fn []
|
|
(if (pred)
|
|
(finish)
|
|
(fail (str "Signal ended while waiting for: " msg))))
|
|
signal))
|
|
;; A source that emits while subscribing already settled the wait.
|
|
(when @done?
|
|
(rx/dispose! @sub*))
|
|
nil))))
|
|
|
|
(defn ^:async wait-for
|
|
"Resolves once `pred` holds, checking immediately and then re-checking it
|
|
on every emission of `:signal` (or once per macrotask when no signal is
|
|
given), up to `:timeout-ms` of real time (default 5000).
|
|
|
|
With a signal the ceiling bounds failure only: the wait resolves on the
|
|
event that changes the state, not after a number of event-loop turns.
|
|
Without one it is a poll budget, and turns are not a unit of time (50
|
|
turns are ~54 ms idle and much less ground under load). Records a single
|
|
failure instead of hanging: `Timed out waiting for: <msg>` when the ceiling
|
|
expires, or the signal's own reason when it ends or fails (see
|
|
`wait-signal`)."
|
|
[pred msg & [{:keys [signal timeout-ms]
|
|
:or {timeout-ms default-timeout-ms}}]]
|
|
(when-not (pred)
|
|
(if (some? signal)
|
|
(await (wait-signal pred msg signal timeout-ms))
|
|
(await (wait-poll pred msg timeout-ms)))))
|
|
|
|
(defn wait-for-store
|
|
"Resolves once `pred` holds over `store`, re-checking it on every store
|
|
event. The store notifies its subscribers after applying the update, so the
|
|
predicate already sees the new state. One signal only: a predicate that also
|
|
reads another source passes a merged signal to `wait-for` itself."
|
|
[store pred msg]
|
|
(wait-for pred msg {:signal (ptk/input-stream store)}))
|