Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 2x 2x 2x 2x 406x 406x 406x 406x 406x 406x 2x 2x 406x 406x 406x 406x 406x 406x 406x 4x 4x 4x 4x 4x 406x 406x 406x 406x 406x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 406x 406x 406x 406x 406x 406x 406x 1025x 1023x 36x 36x 36x 36x 36x 36x 36x 1023x 1023x 1023x 1023x 1025x 406x 406x 406x 406x 406x 406x 331x 331x 331x 331x 331x 406x 406x 406x 406x 1354x 1354x 435x 435x 434x 435x 435x 1354x 406x 406x 406x 406x 406x 406x 406x 406x 705x 705x 705x 406x 406x 406x 406x 406x 406x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 406x 406x 406x 406x 406x 406x 406x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 1018x 4x 4x 4x 4x 4x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1018x 36x 36x 36x 1014x 1014x 1014x 1018x 1018x 1014x 36x 36x 1014x 1014x 1014x 1014x 1018x 53x 53x 1018x 432x 432x 432x 432x 432x 331x 331x 331x 331x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 406x 406x 406x 406x 406x 406x 406x 406x 282x 3x 3x 3x 279x 279x 279x 279x 282x | const queue = [];
/**
* Membership index for {@link queue}.
*
* Deduplication used to be `queue.includes(job)`, a linear scan on every
* enqueue. That was unnoticeable when a queue held one job per updating
* component. Fine-grained rendering puts one job per *binding* in it, so a
* component with 500 bound values turned a flush into 125,000 comparisons
* before running a single job. The set is kept exactly in step with the array:
* anything that removes from one removes from the other.
* @type {Set<Function>}
*/
const queued = new Set();
const flushCallbacks = [];
let isPending = false;
let isFlushing = false;
import { logger } from '../runtime/AvenxLogger.js';
import { AvenxErrorCodes, formatMessage } from '../runtime/AvenxError.js';
import { tracer } from '../trace/tracer.js';
/**
* Maximum recursive flush depth allowed before triggering reactive deadlock abort.
* Defaults to 25 to accommodate deep legitimate multi-pass updates while stopping infinite cycles.
* @type {number}
*/
let maxFlushCount = 25;
/**
* Recursion depth of the currently executing flush.
*
* Incremented once per {@link flushJobs} invocation, not once per job: a flush
* pass legitimately drains arbitrarily many jobs (one per updating component),
* so only *re-entry* — a pass whose jobs queued yet more work — indicates a
* potential runaway update chain.
* @type {number}
*/
let flushDepth = 0;
/**
* Execution count of individual jobs in the current flush cycle.
* Keyed by job or job.id.
* @type {Map<any, number>}
*/
const jobExecutionCounts = new Map();
/**
* Jobs quarantined for the rest of the current top-level flush.
*
* A job that re-queues itself past the frequency limit is a reactive cycle. It
* is dropped, and only it: the queue holds pending updates for unrelated
* components, and clearing them left parts of the page showing stale state with
* nothing logged about them.
* @type {Set<Function>}
*/
const suppressedJobs = new Set();
/**
* Ordered log of jobs executed during the current flush for deadlock cycle diagnosis.
* @type {Array<{id: any, name: string, job: Function}>}
*/
const executionHistory = [];
/**
* Registered deadlock event callbacks.
* @type {Set<Function>}
*/
const deadlockHandlers = new Set();
/**
* Configures the maximum allowed flush cycle count.
* @param {number} count - Maximum flush iterations.
*/
export function setSchedulerMaxFlushCount(count) {
if (typeof count === 'number' && count > 0) {
maxFlushCount = count;
}
}
/**
* Returns the currently configured maximum flush cycle count.
* @returns {number}
*/
export function getSchedulerMaxFlushCount() {
return maxFlushCount;
}
/**
* Registers a global callback for scheduler deadlock events.
* @param {function({cyclePath: string, jobs: Function[], boundary: any}): void} handler
* @returns {Function} Unsubscribe function.
*/
export function onSchedulerDeadlock(handler) {
if (typeof handler === 'function') {
deadlockHandlers.add(handler);
return () => deadlockHandlers.delete(handler);
}
return () => {};
}
/**
* Resets the scheduler state (primarily used in testing).
*/
export function resetScheduler() {
queue.length = 0;
queued.clear();
flushCallbacks.length = 0;
isPending = false;
isFlushing = false;
flushDepth = 0;
jobExecutionCounts.clear();
suppressedJobs.clear();
executionHistory.length = 0;
}
/**
* Queues a job (update callback) to be executed in the next microtask.
* Deduplicates multiple calls to the same job.
* @param {Function} job - The callback to run.
*/
export function queueJob(job) {
if (!queued.has(job)) {
if (tracer.on) {
// Component updates are batched into a microtask, so by the time this job
// runs the causal stack is empty and the resulting DOM patch would look
// like an unexplained root. Stamping the job with whatever queued it lets
// the flush below resume that scope. A job already in the queue keeps its
// first cause: that is the mutation that actually scheduled the work.
job.__avenxTraceCause = tracer.current();
}
queue.push(job);
queued.add(job);
queueFlush();
}
}
/**
* Queues a callback to run after the current flush cycle has finished.
* @param {Function} cb - The callback to run.
*/
export function queueFlushCallback(cb) {
if (!flushCallbacks.includes(cb)) {
flushCallbacks.push(cb);
queueFlush();
}
}
/**
* Schedules a flush cycle in a deferred microtask.
*/
function queueFlush() {
if (!isPending && !isFlushing) {
isPending = true;
Promise.resolve().then(() => {
Promise.resolve().then(flushJobs);
});
}
}
/**
* Orders jobs by their `id` ascending so parent components (lower uid) update
* before their children.
* @param {Function} a
* @param {Function} b
* @returns {number}
*/
function byJobId(a, b) {
return (a.id || 0) - (b.id || 0);
}
/**
* Reconstructs the circular dependency chain from the execution history.
* @param {any} recurringId - The job ID that repeated excessively.
* @returns {string} Formatted cycle string (e.g. "Counter -> Stats -> Counter").
*/
function extractCycleChain(recurringId) {
const ids = executionHistory.map((item) => String(item.name || item.id || 'anonymous'));
const targetName = String(recurringId);
const firstIdx = ids.indexOf(targetName);
if (firstIdx !== -1) {
const cycleSub = ids.slice(firstIdx);
if (!cycleSub.endsWith || cycleSub[cycleSub.length - 1] !== targetName) {
cycleSub.push(targetName);
}
return cycleSub.join(' -> ');
}
// Fallback: take last 4 execution steps
const recent = ids.slice(-4);
if (recent.length > 0) {
return recent.join(' -> ');
}
return String(recurringId);
}
/**
* Handles a detected reactive deadlock: logs diagnostics, notifies handlers, and
* quarantines the jobs that were looping.
*
* Only the offending jobs are dropped. The queue also holds pending updates for
* unrelated components, and clearing it left those parts of the page stale with
* nothing logged about them.
* @param {any} [triggeringJobId] - The job ID that triggered the cycle.
* @param {Function[]} [offendingJobs] - The jobs to quarantine for this flush.
*/
function handleDeadlock(triggeringJobId, offendingJobs = []) {
const cycleStr = extractCycleChain(triggeringJobId || 'reactive-loop');
const boundaryInfo = '';
const diagnosticMsg = formatMessage(
AvenxErrorCodes.REACTIVE_DEADLOCK_DETECTED,
boundaryInfo,
` ${cycleStr}\n\nExecution aborted to prevent browser freeze.`
);
logger.error(diagnosticMsg);
// Notify any registered deadlock handlers
const eventPayload = {
cyclePath: cycleStr,
triggeringJobId,
executionHistory: [...executionHistory],
};
for (const handler of deadlockHandlers) {
try {
handler(eventPayload);
} catch (e) {
logger.error('Error executing deadlock handler:', e);
}
}
// Quarantine only what is looping. Clearing the queue here used to drop every
// unrelated component's pending update along with the cycle, which left those
// parts of the page stale and reported nothing about them.
for (const job of offendingJobs) {
if (typeof job !== 'function') continue;
suppressedJobs.add(job);
if (queued.has(job)) {
queued.delete(job);
const at = queue.indexOf(job);
if (at !== -1) {
queue.splice(at, 1);
}
}
}
}
/**
* Flushes all queued jobs in a loop until the queue is completely empty.
* Jobs are strictly ordered by their `id` property ascending (e.g. component uid)
* to ensure parent components update before their child components.
* After jobs are flushed, all queued flush callbacks (e.g. nextTick) are executed.
*/
function flushJobs() {
isPending = false;
isFlushing = true;
if (flushDepth === 0) {
jobExecutionCounts.clear();
executionHistory.length = 0;
}
flushDepth++;
try {
// Guard 1: Overall flush recursion ceiling. Only re-entry is counted here —
// draining many jobs in a single pass is normal for an application with
// many components reacting to the same tick and must never be aborted.
if (flushDepth > maxFlushCount) {
// Mutual recursion across several jobs. Quarantine the ones that took
// part, not the whole queue.
handleDeadlock(
'MAX_FLUSH_COUNT_EXCEEDED',
executionHistory.map((entry) => entry.job),
);
return;
}
// 1. Flush jobs first.
// Sort jobs by their id ascending (e.g. parent uid < child uid).
queue.sort(byJobId);
while (queue.length > 0) {
const job = queue.shift();
queued.delete(job);
if (suppressedJobs.has(job)) {
// Quarantined earlier in this flush; it re-queued itself again.
continue;
}
const jobId = job.id !== undefined ? job.id : job;
const jobName = job.name || (typeof jobId === 'string' || typeof jobId === 'number' ? `Job#${jobId}` : 'anonymous');
// Frequency is counted per job *function*, not per `job.id`.
//
// `id` orders a flush so a parent component updates before its children,
// and every binding job in one component shares that component's id. If
// the counter were keyed by id, a component with more than ten bound
// values would trip the cycle guard on its very first render -- ten
// unrelated bindings doing their one job each would look identical to one
// job running ten times. Identity is what the guard actually means.
const currentCount = (jobExecutionCounts.get(job) || 0) + 1;
jobExecutionCounts.set(job, currentCount);
executionHistory.push({ id: jobId, name: jobName, job });
// Guard 2: Single job frequency limit. A job re-entering the queue many
// times within one flush session is the real signature of a circular
// update chain (e.g. component A updates B which updates A again).
const perJobLimit = Math.min(10, maxFlushCount);
if (currentCount > perJobLimit) {
// Stop this job, then carry on draining the rest of the queue: the
// other jobs in it belong to unrelated components.
handleDeadlock(jobName, [job]);
continue;
}
const pendingBefore = queue.length;
// Jobs are stable per-component function objects, so the stamp is read
// and cleared rather than left behind, where it would mis-attribute a
// later run to a cause that has nothing to do with it.
let causeToken = -1;
if (tracer.on && job.__avenxTraceCause !== undefined) {
causeToken = tracer.continueFrom(job.__avenxTraceCause);
job.__avenxTraceCause = undefined;
}
try {
job();
} catch (error) {
logger.error('Error executing scheduled job:', error);
} finally {
if (causeToken >= 0) {
tracer.leave(causeToken);
}
}
// Jobs queued while this one ran must be ordered into the remaining drain
// so parents still update before their children.
if (queue.length > pendingBefore) {
queue.sort(byJobId);
}
}
// 2. Flush callbacks
const callbacks = flushCallbacks.slice();
flushCallbacks.length = 0;
for (const cb of callbacks) {
try {
cb();
} catch (error) {
logger.error('Error executing flush callback:', error);
}
}
// 3. Re-flush if executing callbacks or jobs queued more jobs or callbacks.
// The recursion ceiling above stops a runaway chain on re-entry.
if (queue.length > 0 || flushCallbacks.length > 0) {
flushJobs();
}
} finally {
flushDepth--;
if (flushDepth === 0) {
isFlushing = false;
jobExecutionCounts.clear();
suppressedJobs.clear();
executionHistory.length = 0;
// Work left over after an aborted chain still deserves a fresh flush
// rather than sitting in the queue until the next unrelated mutation.
if (queue.length > 0 || flushCallbacks.length > 0) {
queueFlush();
}
}
}
}
/**
* Executes a callback (or resolves a Promise) after all currently queued
* jobs in the scheduler queue have finished flushing.
* @param {Function} [callback] - Optional callback to invoke after the flush.
* @returns {Promise<void>|void} A promise resolving after the flush, if no callback was given.
*/
export function nextTick(callback) {
if (callback) {
queueFlushCallback(callback);
return;
}
return new Promise((resolve) => {
queueFlushCallback(resolve);
});
}
|