jchiatt/react-chaos
关于
面向 React 应用的混沌工程。
网站与应用开发实测星标增长
- 24小时
- +2
- 7天
- +2
- 15天
- +2
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文🔥🐒💥 React Chaos
Chaos engineering for your React apps.
React Chaos makes chosen components throw while they render, so you can see what your error boundaries really do before your users do. Each decision is seeded: the same seed breaks the same components every time, so any failure can be replayed, and a new seed rolls again. It is off unless you turn it on.
Demo: react-chaos.netlify.app (still the 2019 build until it is redeployed; the new demo is in demo/)
Install
npm install --save-dev react-chaos
React 18 or 19. Ships ESM, CommonJS and TypeScript types.
Usage
Chaos does nothing until something turns it on. The usual switch is a provider at the top of your app:
import { ChaosProvider } from 'react-chaos';
<ChaosProvider enabled seed="checkout-1">
<App />
</ChaosProvider>;
Then mark what may fail in one of three ways. Each takes the same options.
withChaos(Component, options) wraps a component:
import { withChaos } from 'react-chaos';
const ChaoticProfile = withChaos(Profile, { id: 'profile', level: 3 });
<Chaos> wraps any part of a tree:
import { Chaos } from 'react-chaos';
<Chaos id="feed" probability={0.5}>
<Feed />
</Chaos>;
useChaos(options) goes inside your own component and throws during its render:
import { useChaos } from 'react-chaos';
function Cart() {
useChaos({ id: 'cart', probability: 0.3 });
return <CartItems />;
}
Options
| Option | Meaning |
|---|---|
id |
A stable name for the decision. Required for <Chaos> and useChaos. withChaos falls back to the component's name. |
probability |
Chance of failing, 0 to 1. Wins over level. |
level |
Chance of failing as 1 to 10, read as level / 10. |
message |
Message for the thrown error. |
enabled |
true or false overrides the provider here. withChaos(C, { enabled: false }) returns C itself. |
Without probability or level, a component uses the provider's probability, or 0.5.
Give every component an explicit id if chaos will run in a production build. Minifiers rename components, so a name like Profile becomes something like fe, which can change between builds and can clash with other components. A component with neither a name nor an id gets the id anonymous, shared with every other such component; once chaos is on, withChaos warns about it in development builds that define process.env.NODE_ENV.
The thrown error
React Chaos throws a ChaosError, a subclass of Error that carries seed, id and probability. Your boundaries and error reporting can tell it apart from a real bug:
import { ChaosError } from 'react-chaos';
if (error instanceof ChaosError) {
console.info(
`chaos in ${error.id}, replay with ?chaos=${encodeURIComponent(error.seed)}`,
);
}
Turning it on
<ChaosProvider seed probability enabled> sets the switch, the seed and a default probability for everything below it. Nested providers inherit what they do not set. Chaos is off unless enabled is true on a provider or on the component itself.
To let QA turn chaos on in a preview deploy without a rebuild, read the seed from the page:
import { ChaosProvider, readChaosSeedFromLocation } from 'react-chaos';
const seed = readChaosSeedFromLocation();
<ChaosProvider enabled={seed !== undefined} seed={seed}>
<App />
</ChaosProvider>;
readChaosSeedFromLocation() returns the value of ?chaos=<seed> in the URL, or else localStorage.chaos, or undefined. Open https://preview.example.com/?chaos=qa-1 to turn chaos on for one visit, or run localStorage.setItem('chaos', 'qa-1') in the console to keep it on across pages. localStorage.removeItem('chaos') turns it off again. An empty value is still a seed: ?chaos= turns chaos on with the seed ''.
Only call it where you are happy for anyone with the link to turn chaos on, such as preview or staging builds. The library never reads the URL by itself.
Seeds and replay
Whether a component fails is a pure function of the seed, its id and the probability:
import { shouldFail } from 'react-chaos';
shouldFail({ seed: 'qa-1', id: 'cart', probability: 0.3 }); // the same answer every time
A probability outside 0 to 1, or NaN, throws a RangeError, from shouldFail and from the components alike.
- The same seed replays the same failures, on every render, every reload and every machine. The error's message and its
seedfield tell you which seed to replay. - A new seed rolls again.
- Re-renders do not roll again. A component that rendered fine will not break because some unrelated state changed.
- React's retries agree with the first render. When a component throws, React renders it again before it shows a fallback, and StrictMode renders twice in development. 0.1 flipped a fresh coin on every render, so a lone component at level 5 showed its fallback about 24% of the time instead of 50% (about 56% under StrictMode). With a seed every render gets the same answer, and the share that fails is the probability you asked for.
Without a seed, React Chaos picks one at random per page load, so reloading rolls again. If you render on the server, pass a seed so the server and the browser agree.
All instances of a component share one decision, so if Card fails, every Card fails, much as a real bug in Card would. To vary it per instance, give each one its own id: <Chaos id={card-${item.id}}>. React's useId is not used for this. Its values depend on where a component sits in the tree, so they would change when unrelated code changed and could not be replayed across builds.
Using this with error boundaries
React Chaos only shows you where your boundaries are. Where they should go is the question Brandon Dail asked in Fault Tolerance (2019 copy), the post this library came from:
If this component crashes, should its siblings also crash?
One boundary at the top of the app is too few: one broken widget blanks the whole page. A boundary around every component is too many, because half-broken UI is full-broken UX. His example is a checkout form whose card input crashed while the Pay button stayed on screen. The right boundaries sit around features: the parts that should live or die together.
A way to use React Chaos for this:
- Pick a page and write down which parts should survive when another part fails. For example: if recommendations fail, checkout must still work, and the card input and the Pay button fail together.
- Wrap each part with
<Chaos id="…">and turn chaos on with a seed. - Try seeds until each part has failed at least once, and check every failure against your list. Each wrong answer is a boundary to add, move or remove.
- Keep the seed of any surprise.
?chaos=<seed>replays it exactly while you fix it.
React Chaos does not ship its own boundary. Use react-error-boundary: it is small and well maintained, works with hooks, and its resetKeys let a boundary recover when something changes, such as the seed.
import { ErrorBoundary } from 'react-error-boundary';
import { Chaos, ChaosProvider } from 'react-chaos';
<ChaosProvider enabled={seed !== undefined} seed={seed}>
<Header />
<ErrorBoundary
fallback={<p>Recommendations are unavailable.</p>}
resetKeys={[seed]}
>
<Chaos id="recommendations">
<Recommendations />
</Chaos>
</ErrorBoundary>
<ErrorBoundary
fallback={<p>Checkout failed. Your card was not charged.</p>}
resetKeys={[seed]}
>
<Chaos id="checkout">
<CardInput />
<PayButton />
</Chaos>
</ErrorBoundary>
</ChaosProvider>;
Migrating from 0.1 or 1.0
2.0 changes the API. The 2019 releases (1.0.2–1.0.6, then 0.1.0) share the old API; the 0.1 package on npm could not be installed at all (#10), so few apps should need to migrate.
| 0.1 / 1.0 | 2.0 |
|---|---|
import withChaos from 'react-chaos' |
import { withChaos } from 'react-chaos' (named exports only) |
withChaos(C, level, message, runInProduction) |
withChaos(C, { level, message, enabled }) |
| On in development, off in production | Off everywhere until enabled is set on a ChaosProvider or an option |
runInProduction: true |
enabled: true, or <ChaosProvider enabled>; no warning is logged on each wrap |
| A new coin flip on every render | One seeded decision per seed and id |
| Level 10 meant 95%, and levels really failed less often | Level 10 means 100%; each level is exactly level / 10 |
Throws Error |
Throws ChaosError, with seed, id and probability |
| Default level 5 | Default probability 0.5, or the provider's probability |
A 0.1 or 1.0 call such as withChaos(Profile, 3, 'boom') becomes:
<ChaosProvider enabled={import.meta.env.DEV}>
<App />
</ChaosProvider>;
const ChaoticProfile = withChaos(Profile, {
id: 'profile',
level: 3,
message: 'boom',
});
What is chaos engineering?
Chaos engineering is the practice of injecting failures into a system on purpose to test how well it copes. You can read more about it on Wikipedia.
Inspiration
- Brandon Dail, Fault Tolerance, which asks: "What if we had something like
React.ChaosModethat let you test fault tolerance by randomly breaking some component(s)?" - Brian Holt, Chaos Monkeys in Your Browser: What Chaos Engineering Means for the Front End, React Rally 2018.
- J.C. Hiatt, Introducing React Chaos (2019 copy).
- Also, watching Jurassic Park the night before writing it.
Roadmap
Network, language and time chaos, experiments for Playwright, and other ideas are tracked in #67.
Contributing
See CONTRIBUTING.md.
探索相关项目
加载中…