All Projects → flexport → mutation-sentinel

flexport / mutation-sentinel

Licence: MIT license
Deeply detect object mutations at runtime

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to mutation-sentinel

Phunctional
⚡️ λ PHP functional library focused on simplicity and performance
Stars: ✭ 243 (+683.87%)
Mutual labels:  immutability
immutable-cursor
👊 Immutable cursors incorporating the Immutable.js interface over a Clojure-inspired atom
Stars: ✭ 58 (+87.1%)
Mutual labels:  immutability
Computational-Intelligence-Tutorials
This is the repository of codes written in class.
Stars: ✭ 36 (+16.13%)
Mutual labels:  mutations
dumbmutate
Simple mutation-testing
Stars: ✭ 32 (+3.23%)
Mutual labels:  mutations
universalmutator
Regexp based tool for mutating generic source code across numerous languages
Stars: ✭ 105 (+238.71%)
Mutual labels:  mutations
ftor
ftor enables ML-like type-directed, functional programming with Javascript including reasonable debugging.
Stars: ✭ 44 (+41.94%)
Mutual labels:  immutability
Ipmjs
Immutable Package Manager
Stars: ✭ 191 (+516.13%)
Mutual labels:  immutability
functional-js
Functional Programming in JavaScript
Stars: ✭ 18 (-41.94%)
Mutual labels:  immutability
php-validation-dsl
A DSL for validating data in a functional fashion
Stars: ✭ 47 (+51.61%)
Mutual labels:  immutability
Immutype
Immutability is easy!
Stars: ✭ 26 (-16.13%)
Mutual labels:  immutability
cerebra
A tool for fast and accurate summarizing of variant calling format (VCF) files
Stars: ✭ 55 (+77.42%)
Mutual labels:  mutations
graphql-cli-load
A graphql-cli data import plugin to call mutations with data from JSON/CSV files
Stars: ✭ 63 (+103.23%)
Mutual labels:  mutations
react-mlyn
react bindings to mlyn
Stars: ✭ 19 (-38.71%)
Mutual labels:  immutability
react-apollo-form
Build React forms based on GraphQL APIs.
Stars: ✭ 195 (+529.03%)
Mutual labels:  mutations
graphql-sequelize-generator
A Graphql API generator based on Sequelize.
Stars: ✭ 20 (-35.48%)
Mutual labels:  mutations
Paguro
Generic, Null-safe, Immutable Collections and Functional Transformations for the JVM
Stars: ✭ 231 (+645.16%)
Mutual labels:  immutability
Genetics
Genetics (Initialization, Selection, Crossover, Mutation)
Stars: ✭ 15 (-51.61%)
Mutual labels:  mutations
flutter built redux
Built_redux provider for Flutter.
Stars: ✭ 81 (+161.29%)
Mutual labels:  immutability
muton
A feature toggle tool with support for feature throttling and multivariance testing.
Stars: ✭ 15 (-51.61%)
Mutual labels:  mutations
shyft
⬡ Shyft is a server-side framework for building powerful GraphQL APIs 🚀
Stars: ✭ 56 (+80.65%)
Mutual labels:  mutations

Build Status codecov

Mutation Sentinel

Mutation Sentinel helps you deeply detect mutations at runtime and enforce immutability in your codebase.

Motivation

So you decided to optimize your React app with PureComponents, but you also know that mutations can cause stale rendering bugs when mixed with PureComponents. Mutation Sentinel allows you to incrementally detect and fix the mutations in your code, and enforce immutability along the way.

Installation

npm install --save mutation-sentinel

Usage

Wrap object (including arrays) and functions with makeSentinel to detect mutations. Calling makeSentinel with a value that cannot be wrapped will simply return the value itself.

import makeSentinel from "mutation-sentinel";
// const makeSentinel = require("mutation-sentinel").default;

const obj = {};
const wrappedObj = makeSentinel(obj);
wrappedObj.value = "oops";
// console: Mutation detected by a sentinel!

This also works with arrays:

const array = [];
const wrappedArray = makeSentinel(array);
wrappedArray.push("oops");
// console: Mutation detected by a sentinel!

And even deeply nested objects!

const obj = {array: [{}]};
const wrappedObj = makeSentinel(obj);
wrappedObj.array[0].value = "oops";
// console: Mutation detected by a sentinel!

Best of all, the stack trace gives you the exact line in the code where the mutation occurs 😲

function foo(obj) {
  bar(obj);
}

function bar(obj) {
  obj.value = "oops";
}

const obj = {};
const wrappedObj = makeSentinel(obj);
foo(wrappedObj);

// console: Mutation detected by a sentinel!
// Stack trace:
//   ...
//   bar         @ VM478:6  <-- Mutation
//   foo         @ VM478:2
//   (anonymous) @ VM478:11

Configuration

Your army of sentinels can be reconfigured globally at any time:

import {configureSentinels} from "mutation-sentinel";
// const configureSentinels = require("mutation-sentinel").configureSentinels;

configureSentinels({
  shouldIgnore: obj => {
    // return true to NOT wrap obj with a sentinel
  },
  mutationHandler: mutation => {
    // respond to the mutation however you want
  }
});

Here is an example configuration

The mutation object in mutationHandler has the following flow type:

type Mutation =
  | {|
      type: "defineProperty",
      target: Observable,
      property: string,
      descriptor: Object,
    |}
  | {|
      type: "deleteProperty",
      target: Observable,
      property: string,
    |}
  | {|
      type: "set",
      target: Observable,
      property: string,
      value: any,
    |}
  | {|
      type: "setPrototypeOf",
      target: Observable,
      property: "[[Prototype]]",
      prototype: ?Object,
    |};

// Only objects (including arrays) and functions will be wrapped by sentinels.
type Observable = {} | (() => mixed);

Browser Compatibility

This library relies on the Proxy object. For browsers that do not support Proxies, makeSentinel simply returns the original object and no mutation detection occurs.

Flexport's Use Case

Due to the size of Flexport’s app, we decided to purify our components incrementally. Since the sentinels can be reconfigured dynamically, we enabled and disabled the mutationHandler on a route by route basis.

Here is the general approach that we took:

  1. Wrap all of our flux store records with makeSentinel.
  2. For the route we want to purify, configure the mutationHandler to log mutations to the console in development, and Sentry (our error reporting service) in production.
  3. Deploy sentinels to production and fix the mutations as they are detected.
  4. Once all the mutations are fixed, change mutationHandler to throw in development and no-op in production.

To fix the mutations, we used a combination of array spreading, object spreading, and the immutability-helper library.

Limitations

  • Since the detection happens at runtime, sentinels can’t find mutations in code that isn’t executed. We left the detection on in production for about a month to catch as many mutations as possible.
  • It wasn’t feasible to wrap every object in our app with a sentinel, which means the unwrapped objects are still susceptible to undetected mutations.

Gotchas

  • While a sentinel behaves the same as the original object, it is not equal to it.
makeSentinel(myObj) !== myObj
  • Shallow copies of sentinels are not themselves sentinels…but the nested objects of the shallow copy are sentinels.
const obj = {nested: {}};
const wrappedObj = makeSentinel(obj);

// copiedObj is not a sentinel
const copiedObj = {...wrappedObj};
copiedObj.value = "oops"; // mutation is NOT detected

// copiedObj.nested is a sentinel because it was copied from wrappedObj
copiedObj.nested.value = "oops"; // MUTATION DETECTED!
  • Appending a File that is wrapped by a sentinel to FormData does not work properly (tested on Mac Chrome 60.0.3112.113). We got around this issue by ignoring File instances in shouldIgnore.
const file = new File(["some data"], "testfile");
const wrappedFile = makeSentinel(file);
const formData = new FormData();
formData.append("origFile", file);
formData.append("wrappedFile", wrappedFile);

formData.get("origFile");
// File {name: "testfile", …}
formData.get("wrappedFile");
// "[object File]" <--- ???

Alternatives

Another option is to use static analysis to detect mutations (e.g. eslint-plugin-immutable).

For us, this approach surfaced too many mutations and did not allow us to easily remove mutations on a route by route basis.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].