Skip to content

Fix/update request with tab windows - #157

Open
Kirrrusha wants to merge 18 commits into
mainfrom
fix/update-request-with-tab-windows
Open

Fix/update request with tab windows#157
Kirrrusha wants to merge 18 commits into
mainfrom
fix/update-request-with-tab-windows

Conversation

@Kirrrusha

Copy link
Copy Markdown
Collaborator

Summary

Исправляет Windows-специфичную гонку, когда при переключении вкладок и редактировании заголовков могли применяться устаревшие значения (старый снапшот из storage), перезаписывая актуальную конфигурацию.

Changes

  • Атомарное обновление DNR-правил: применяем declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules }) одним вызовом, чтобы избежать гонки remove→add.
  • Сериализация применения в background: добавлена очередь (single-flight), которая склеивает параллельные триггеры и гарантирует "latest wins".
  • Строгая версия конфигурации: сохраняем headersConfigMetaV1 (seq, монотонный updatedAt) и в background пропускаем устаревшие снапшоты, даже если события приходят не по порядку.
  • Убрано лишнее применение на смене вкладки: DNR-правила глобальные, поэтому пересборка на tabs.onActivated только увеличивала вероятность гонок.
  • Убран legacy reload-путь: удалены updateOverrideHeaders/runtime reload message; обновления теперь идут через storage.onChanged.

Why this works

На Windows из-за другой латентности и планирования событий чаще происходили перекрывающиеся триггеры применения правил. Версионирование + очередь не позволяют применить старую конфигурацию "после" новой.

Test plan

  • pnpm test:unit
  • Ручная проверка (Windows):
    • Менять значения заголовков в popup и быстро переключать вкладки (несколько раз).
    • Проверить, что запросы уходят с последними значениями заголовков.
    • В логах background убедиться, что устаревшие снапшоты пропускаются (Apply skipped (stale meta)), а применения идут последовательно.

Notes

  • seq — best-effort при конкурентных записях; updatedAt принудительно монотонный и используется как tie-breaker.

@Kirrrusha
Kirrrusha requested a review from AndreyTheWeb as a code owner August 5, 2026 12:58
github-actions Bot pushed a commit that referenced this pull request Aug 5, 2026
github-actions Bot pushed a commit that referenced this pull request Aug 5, 2026
Kirill Lebedenko and others added 17 commits August 5, 2026 16:26
- Add retry logic (3 attempts with exponential backoff) for transient
  DNR updateDynamicRules errors ("Internal error while updating dynamic rules")
- Re-throw errors from setBrowserHeaders to prevent queue state from updating
  when rules fail to apply
- Add detailed diagnostic logging for debugging header toggle issues
…start MV3 service workers are killed by Chrome after ~30 s of inactivity and restarted on demand Dynamic DNR rules persist across SW sessions but neither onStartup nor onInstalled fires on a plain SW restart so stale rules from a previous session eg for headers that were later disabled would stay active — meaning disabled headers kept being injected into requests until the user made a storage change Fix call applyHeadersFromStorageQueue'sw-init' at module load time so every SW restart reconciles DNR state with storage The existing meta/fingerprint deduplication prevents redundant applies when the state has not changed eg when onStartup also fires on browser start Add e2e tests in sw-restartspects that simulate the scenario by injecting a stale DNR rule directly triggering chromeruntimereload and asserting the rule is cleared by sw-init in the new worker session
…romeruntimereload is not usable in launchPersistentContext after calling it Playwright stops tracking the new service worker and the extension URL becomes permanently unreachable Instead the tests now simulate the same apply path applyHeadersFromStorageQueue which sw-init also calls by toggling isPausedV1 in storage This changes the storage fingerprint and forces a genuine apply without needing an actual SW restart Two separate storage writes are serialised via an explicit waitForRulesCount barrier between them to prevent the queue from collapsing both changes into a single apply that would see the original fingerprint Also fixes the storage key the correct key for the paused flag is 'isPausedV1' not 'isPaused'
…y After a plain SW restart (e.g. computer unlock), disabled headers from the previous session remain active as stale DNR dynamic rules until the full sw-init apply completes (~ ms). During that window, disabled headers are still injected into requests. Fix by adding clearDynamicRulesOnSwInit() that removes all dynamic rules immediately on SW boot before the apply reads storage. This reduces the window of incorrect behaviour from ~400 ms to ~5-10 ms (a single getDynamicRules round-trip). If the pre-clear fails, the apply handles cleanup as before — no regression. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…When Chrome's dynamic rules API is broken Internal error the session fallback was removing ALL session rules including counteracting ones id >= 1_000_000_000 This left stuck dynamic rules with no counterpart causing disabled headers to be transmitted until the next apply Fix exclude counteracting rule IDs from the session fallback removal list They are cleaned up later in the same apply once stuck rules are reconciled Adds regression test covering the exact scenario from the debug logs
…nteracting session rules to override Chrome's dynamic > session ordering Chrome uses static > dynamic > session - Route onInstalled/onStartup through applyHeadersFromStorageQueue to fix race condition with clearDynamicRulesOnSwInit - Always clean up stale counteracting session rules even when stuckRuleIdslength === 0 - Add retry logic with exponential backoff to clearDynamicRulesOnSwInit - Update tests verify priority2 un-skip stale cleanup test add new cases
@Kirrrusha
Kirrrusha force-pushed the fix/update-request-with-tab-windows branch from 9882193 to 8751d6c Compare August 5, 2026 13:26
github-actions Bot pushed a commit that referenced this pull request Aug 5, 2026
@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

PR tester build for a208d36 has been published:

Artifact folder: https://github.com/cloud-ru-tech/cloudhood/tree/artifacts/pull-requests/157

Commit: a208d3631a1fb8405638a95511c40c61780e9fd7

Comment on lines +22 to +37
browser.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== 'local') return;
if (!(BrowserStorageKey.DnrHealth in changes)) return;

const newValue = changes[BrowserStorageKey.DnrHealth]?.newValue;
if (!newValue || typeof newValue !== 'object') {
dnrHealthUpdated(null);
return;
}
const raw = newValue as Record<string, unknown>;
dnrHealthUpdated({
ok: Boolean(raw.ok),
stuckRuleIds: Array.isArray(raw.stuckRuleIds) ? (raw.stuckRuleIds as number[]) : [],
updatedAt: typeof raw.updatedAt === 'number' ? raw.updatedAt : 0,
});
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

сорямба что влез, тут бы эффект, далее связать через sample

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не, не, не отлично!! Спасибо!!

github-actions Bot pushed a commit that referenced this pull request Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants