README.md

bx-storage-cache

Lightweight background data synchronization library for browser extensions with built-in exponential backoff and jitter.

Features

  • 🔄 Automated Background Sync: Leverages browser.alarms for periodic updates.
  • 📉 Resilient Retries: Implements Equal Jitter strategy to prevent thundering herd problems during API failures.
  • 🛠 Lifecycle Management: Auto-initializes on extension install or update.

Installation

npm install @daisy-petal/bx-storage-cache
yarn add @daisy-petal/bx-storage-cache
pnpm add @daisy-petal/bx-storage-cache
bun add @daisy-petal/bx-storage-cache

Quick Start

  1. Add permissions to your manifest.json:
{
  "permissions": ["storage", "alarms"]
}
  1. Register your cache in the background script:
import { registerBxStorageCache } from '@daisy-petal/bx-storage-cache'

interface PriceData {
	price: number
	currency: string
}

const priceCache = registerBxStorageCache<PriceData>(
	{ price: 0, currency: 'USD' },
	'price',
	async () => {
		const data = await fetch('https://api.example.com')
		return data.json()
	},
	{
		periodInMin: 30,
		retryDelayInMs: {
			base: 2 * 1000,
			max: 10 * 60 * 1000
		}
	}
);

// To get the value later:
// const { price } = await browser.storage.local.get('price');

How it works

  1. Initialization: On runtime.onInstalled, init() is called to set the default state.
  2. Sync Cycle: The onAlarm handler triggers your getActualValue function.
  3. Error Recovery: If the fetcher throws an error:
    1. It calculates a retry delay using exponential backoff.
    2. Adds “Equal Jitter” to the delay to spread out server load.
    3. Persists the attempt count in storage to survive background page suspensions.
  4. Storage Keys: id: Contains the cached data. @daisy-petal/bx-storage-cache:${id}: Internal metadata for managing retry state.

API Reference

registerBxStorageCache<Value>(initValue, id, getActualValue, options)

The primary entry point. It instantiates the class and attaches necessary listeners to browser.alarms and browser.runtime.

BxStorageCache<Value> Class

  • forceSync(): Clears existing alarms and triggers an immediate update.
  • destroy(): Wipes data from storage and cancels all scheduled alarms.
  • init(value): Resets the cache to a specific value and clears retry metadata.
Описание
Lightweight background data synchronization library for browser extensions with built-in exponential backoff and jitter.
Конвейеры
0 успешных
0 с ошибкой
Разработчики