├── .npmignore
├── .travis.yml
├── images
├── react-ssr-logo.png
└── react-renderToString-cpu-profile.png
├── .eslintrc-node
├── .gitignore
├── .eslintrc-test
├── package.json
├── lib
└── index.js
├── LICENSE
├── README.md
└── test
└── spec
└── index.spec.js
/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | demo/
3 | test/
4 | images/
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 |
3 | node_js:
4 | - v6
5 |
6 | script:
7 | - npm run check
8 |
--------------------------------------------------------------------------------
/images/react-ssr-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/walmartlabs/react-ssr-optimization/HEAD/images/react-ssr-logo.png
--------------------------------------------------------------------------------
/images/react-renderToString-cpu-profile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/walmartlabs/react-ssr-optimization/HEAD/images/react-renderToString-cpu-profile.png
--------------------------------------------------------------------------------
/.eslintrc-node:
--------------------------------------------------------------------------------
1 | ---
2 | extends:
3 | - "eslint-config-defaults/configurations/walmart/es6-node"
4 | ecmaFeatures:
5 | modules: false
6 | rules:
7 | "filenames/filenames": 0
8 | "func-style":
9 | - 0
10 | - declaration
11 | "object-shorthand":
12 | - 0
13 | "no-extra-parens":
14 | - 0
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 |
5 | # Runtime data
6 | pids
7 | *.pid
8 | *.seed
9 |
10 | # Directory for instrumented libs generated by jscoverage/JSCover
11 | lib-cov
12 |
13 | # Coverage directory used by tools like istanbul
14 | coverage
15 |
16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
17 | .grunt
18 |
19 | # node-waf configuration
20 | .lock-wscript
21 |
22 | # Compiled binary addons (http://nodejs.org/api/addons.html)
23 | build/Release
24 |
25 | build/
26 | public/
27 |
28 | # Dependency directory
29 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
30 | node_modules/
31 |
--------------------------------------------------------------------------------
/.eslintrc-test:
--------------------------------------------------------------------------------
1 | ---
2 | extends:
3 | - "eslint-config-defaults/configurations/walmart/es6-node"
4 | - "eslint-config-defaults/configurations/walmart/es6-test"
5 |
6 | globals:
7 | expect: false
8 | sandbox: false
9 | sinon: false
10 |
11 | rules:
12 | "no-invalid-this": 0
13 | "no-unused-expressions": 0 # for `chai.expect`
14 | "max-len": [2, 150, 2, {ignorePattern: "^\\s*(?:it|describe)\\(.*"}]
15 | "max-statements": 0
16 | "filenames/filenames": 0
17 | "max-nested-callbacks": 0
18 | "prefer-arrow-callback": 0
19 | "func-style":
20 | - 0
21 | - declaration
22 | "object-shorthand":
23 | - 0
24 | "no-magic-numbers":
25 | - 0
26 | "no-console":
27 | - 0
28 |
29 | env:
30 | mocha: true
31 |
32 | # Turning off modules so that we can use `"use strict";` in tests for things
33 | # like scoped `let`, etc.
34 | "ecmaFeatures":
35 | "modules": false
36 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-ssr-optimization",
3 | "version": "0.0.7",
4 | "description": "React server-side rendering optimization with component memoization and templatization",
5 | "main": "lib/index.js",
6 | "scripts": {
7 | "test": "istanbul test _mocha -- -R spec --recursive test/spec",
8 | "test-cov": "istanbul cover _mocha -- -R spec --recursive test/spec",
9 | "lint": "npm run lint-lib && npm run lint-test",
10 | "lint-lib": "eslint -c .eslintrc-node lib --color",
11 | "lint-test": "eslint -c .eslintrc-test test --color",
12 | "check": "npm run lint && npm run test-cov"
13 | },
14 | "repository": {
15 | "type": "git",
16 | "url": "git@github.com:walmartlabs/react-ssr-optimization.git"
17 | },
18 | "keywords": [
19 | "react",
20 | "server-side",
21 | "optimization",
22 | "memoization",
23 | "templatization",
24 | "cache",
25 | "caching"
26 | ],
27 | "author": "Naga Malepati, Maxime Najim, Seth Benjamin",
28 | "license": "Apache-2.0",
29 | "dependencies": {
30 | "lodash": "^4.12.0",
31 | "lru-cache": "^4.0.1"
32 | },
33 | "devDependencies": {
34 | "babel-eslint": "^6.0.4",
35 | "chai": "^3.5.0",
36 | "eslint": "^1.10.3",
37 | "eslint-config-defaults": "^8.0.1",
38 | "eslint-plugin-filenames": "^1.1.0",
39 | "intercept-stdout": "^0.1.2",
40 | "istanbul": "^0.4.3",
41 | "mocha": "^2.4.5",
42 | "react": "^15.0.0 || ^0.14.8",
43 | "react-dom": "^15.0.0 || ^0.14.8"
44 | },
45 | "peerDependencies": {
46 | "react": "^15.0.0 || ^0.14.8"
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/lib/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | const get = require("lodash/get");
4 | const set = require("lodash/set");
5 | const wrap = require("lodash/wrap");
6 | const template = require("lodash/template");
7 | const mapKeys = require("lodash/mapKeys");
8 | const isArray = require("lodash/isArray");
9 | const isObject = require("lodash/isObject");
10 | const isPlainObject = require("lodash/isPlainObject");
11 | const Module = require("module");
12 | const InstantiateReactComponent = require("react-dom/lib/instantiateReactComponent");
13 | const escapeTextContentForBrowser = require("react-dom/lib/escapeTextContentForBrowser");
14 |
15 | const require_ = Module.prototype.require;
16 | const cache = require("lru-cache");
17 |
18 | const MILLISECONDS_IN_ONE_SECOND = 1000;
19 | const SECONDS_IN_ONE_MINUTE = 60;
20 | const DEFAULT_MINUTES_TO_CACHE = 60;
21 |
22 | const DEFAULT_LRU_CONFIG = {
23 | max: 500, //The maximum size of the cache
24 | maxAge: DEFAULT_MINUTES_TO_CACHE * SECONDS_IN_ONE_MINUTE * MILLISECONDS_IN_ONE_SECOND
25 | };
26 |
27 | const EMPTY_ID = -1;
28 |
29 | const defaultCacheKeyFunction = () => {
30 | return "_defaultKey";
31 | };
32 |
33 | const genAttrBasedKeyFunction = (attrs) => {
34 | return ((props) => {
35 | let key = "";
36 | attrs.forEach((attr) => {
37 | const val = get(props, attr);
38 | key += isObject(val) ? JSON.stringify(val) : val;
39 | });
40 | return key;
41 | });
42 | };
43 |
44 | class InstantiateReactComponentOptimizer {
45 |
46 | constructor(config) {
47 | if (process.env.NODE_ENV !== "production") {
48 | console.info( // eslint-disable-line no-console
49 | "Caching is disabled in non-production environments."
50 | );
51 | } else {
52 | this.config = config;
53 | this.componentsToCache = config.components ? Object.keys(config.components) : [];
54 | this.componentsToCache.forEach((cmpName) => {
55 | let cacheConfig = config.components[cmpName];
56 | if (cacheConfig instanceof Function) {
57 | cacheConfig = config.components[cmpName] = {
58 | cacheKeyGen: cacheConfig
59 | };
60 | }
61 | if (isObject(cacheConfig) && !cacheConfig.cacheKeyGen) {
62 | cacheConfig.cacheKeyGen = cacheConfig.cacheAttrs && cacheConfig.cacheAttrs.length
63 | ? genAttrBasedKeyFunction(cacheConfig.cacheAttrs)
64 | : defaultCacheKeyFunction;
65 | }
66 | }, this);
67 | /* eslint-disable no-nested-ternary */
68 | this.lruCache = (config.cacheImpl) ? config.cacheImpl :
69 | (config.lruCacheSettings) ? cache(config.lruCacheSettings) : cache(DEFAULT_LRU_CONFIG);
70 | this.enabled = !(config.disabled === true);
71 | this.eventCallback = config.eventCallback;
72 | this.shouldCollectLoadTimeStats = config.collectLoadTimeStats;
73 | this.wrapInstantiateReactComponent();
74 | }
75 | }
76 |
77 | wrapInstantiateReactComponent() {
78 | const self = this;
79 |
80 | function eventCallback(event) {
81 | if (self.eventCallback) {
82 | process.nextTick(() => {
83 | self.eventCallback(event);
84 | });
85 | }
86 | }
87 |
88 | /* eslint-disable max-params, no-console, prefer-template*/
89 |
90 | const restoreAttr = (origProps, lookupPropTable, propKey, arrNotaKey, propValue) => {
91 | if (isPlainObject(propValue)) {
92 | mapKeys(propValue, (value, key) => {
93 | restoreAttr(origProps, lookupPropTable, `${propKey}.${key}`,
94 | `${propKey}["${key}"]`, value);
95 | });
96 | } else if (isArray(propValue)) {
97 | for (let i = 0; i < propValue.length; i++) {
98 | restoreAttr(origProps, lookupPropTable, `${propKey}.${i}`, `${propKey}[${i}]`,
99 | propValue[i]);
100 | }
101 | } else {
102 | const _attrKey = propKey.replace(/_/gi, "__").replace(/\./gi, "_");
103 | set(origProps, arrNotaKey, lookupPropTable[_attrKey]);
104 | }
105 | };
106 |
107 | const templatizeAttr = (origProps, lookupPropTable, propKey, arrNotaKey,
108 | propValue, addlCacheForArr) => {
109 | if (isPlainObject(propValue)) {
110 | mapKeys(propValue, (value, key) => {
111 | templatizeAttr(origProps, lookupPropTable, `${propKey}.${key}`, `${propKey}["${key}"]`,
112 | value, addlCacheForArr);
113 | });
114 | } else if (isArray(propValue)) {
115 | addlCacheForArr.push(propKey + "_" + propValue.length);
116 | for (let i = 0; i < propValue.length; i++) {
117 | templatizeAttr(origProps, lookupPropTable, `${propKey}.${i}`, `${propKey}[${i}]`,
118 | propValue[i], addlCacheForArr);
119 | }
120 | } else {
121 | const _attrKey = propKey.replace(/_/gi, "__").replace(/\./gi, "_");
122 | lookupPropTable[_attrKey] = escapeTextContentForBrowser(propValue);
123 | set(origProps, arrNotaKey, "${" + _attrKey + "}");
124 | }
125 | };
126 |
127 | const restorePropsAndProcessTemplate = (compiled, templateAttrs, templateAttrValues, curEl) => {
128 | templateAttrs.forEach((attrKey) => {
129 | const value = get(curEl.props, attrKey);
130 | restoreAttr({a: curEl.props}, templateAttrValues, `a.${attrKey}`, `a.${attrKey}`,
131 | value);
132 | });
133 | return compiled(templateAttrValues);
134 | };
135 | /* eslint-enable max-params, no-console*/
136 |
137 | const shouldComponentBeCached = function (curEl) {
138 | return curEl && curEl.type &&
139 | (self.componentsToCache.indexOf(curEl.type.displayName) > EMPTY_ID ||
140 | self.componentsToCache.indexOf(curEl.type.name) > EMPTY_ID);
141 | };
142 |
143 | const WrappedInstantiateReactComponent = wrap(InstantiateReactComponent,
144 | function (instantiate) {
145 | const component = instantiate.apply(
146 | instantiate, [].slice.call(arguments, 1));
147 | if (component._instantiateReactComponent
148 | && (!component._instantiateReactComponent.__wrapped)) {
149 | component._instantiateReactComponent = WrappedInstantiateReactComponent;
150 | }
151 | if (self.enabled) {
152 | const curEl = component._currentElement;
153 | if (shouldComponentBeCached(curEl)) {
154 | /* eslint-disable max-statements */
155 | component.mountComponent = wrap(
156 | component.mountComponent,
157 | function (mount) {
158 | const cmpName = (curEl.type.displayName || curEl.type.name);
159 | const generatedKey = self.config.components[cmpName].cacheKeyGen(curEl.props);
160 | if (generatedKey === null) {
161 | return mount.apply(component, [].slice.call(arguments, 1));
162 | }
163 | const addlCacheForArr = [];
164 | const rootID = arguments[1];
165 | const templateAttrs = self.config.components[cmpName].templateAttrs || [];
166 | const templateAttrValues = {};
167 | templateAttrs.forEach((attrKey) => {
168 | const value = get(curEl.props, attrKey);
169 | templatizeAttr({a: curEl.props}, templateAttrValues, `a.${attrKey}`,
170 | `a.${attrKey}`, value, addlCacheForArr);
171 | });
172 | const cacheKey = `${cmpName}:${generatedKey}:${addlCacheForArr}`;
173 | const cachedObj = self.lruCache.get(cacheKey);
174 | if (cachedObj) {
175 | eventCallback({type: "cache", event: "hit", cmpName: cmpName});
176 | const cacheMarkup = templateAttrs.length ?
177 | restorePropsAndProcessTemplate(cachedObj.compiled, templateAttrs,
178 | templateAttrValues, curEl)
179 | : cachedObj.markup;
180 | /* eslint-disable quotes */
181 | return cacheMarkup.replace(
182 | new RegExp(`data-reactid="${cachedObj.rootId}`, "g"),
183 | `data-reactid="${rootID}`);
184 | }
185 |
186 | const markUpGenerateStartTime = self.shouldCollectLoadTimeStats ?
187 | process.hrtime() : 0;
188 | const markup = mount.apply(component, [].slice.call(arguments, 1));
189 | const compiledMarkup = templateAttrs.length ? template(markup) : null;
190 | const markUpGenerateEndTime = self.shouldCollectLoadTimeStats ?
191 | process.hrtime(markUpGenerateStartTime) : 0;
192 | eventCallback({type: "cache", event: "miss", cmpName: cmpName,
193 | loadTimeNS: (markUpGenerateEndTime[1])});
194 | self.lruCache.set(cacheKey, {
195 | markup: markup, compiled: compiledMarkup, rootId: rootID
196 | });
197 | return templateAttrs.length ? restorePropsAndProcessTemplate(
198 | compiledMarkup, templateAttrs, templateAttrValues, curEl)
199 | : markup;
200 | });
201 |
202 | /* eslint-enable max-statements */
203 | }
204 | }
205 | return component;
206 | }
207 | );
208 |
209 | WrappedInstantiateReactComponent.__wrapped = true;
210 |
211 | Module.prototype.require = function (path) {
212 | const m = require_.apply(this, arguments);
213 |
214 | if (path === "./instantiateReactComponent") {
215 | return WrappedInstantiateReactComponent;
216 | }
217 |
218 | return m;
219 | };
220 | }
221 |
222 | enable(enableFlag) {
223 | this.enabled = enableFlag;
224 | }
225 |
226 | cacheDump() {
227 | return this.lruCache.dump();
228 | }
229 |
230 | cacheLength() {
231 | return this.lruCache.length;
232 | }
233 |
234 | cacheReset() {
235 | return this.lruCache.reset();
236 | }
237 | }
238 |
239 | module.exports = (config) => new InstantiateReactComponentOptimizer(config);
240 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2016 WalmartLabs
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
React Server-Side Rendering Optimization Library
2 |
3 | This React Server-side optimization library is a configurable ReactJS extension for memoizing react component markup on the server. It also supports component templatization to further caching of rendered markup with more dynamic data. This server-side module intercepts React's instantiateReactComponent module by using a `require()` hook and avoids forking React.
4 |
5 | [](https://travis-ci.org/walmartlabs/react-ssr-optimization)
6 | [](https://www.npmjs.org/package/react-ssr-optimization)
7 | [](https://github.com/walmartlabs/react-ssr-optimization/blob/master/LICENSE)
8 |
9 | ## Why we built it
10 | React is a best-of-breed UI component framework allowing us to build higher level components that can be shared and reused across pages and apps. React's Virtual DOM offers an excellent development experience, freeing us up from having to manage subtle DOM changes. Most importantly, React offers us a great out-of-the-box isomorphic/universal JavaScript solution. React's `renderToString(..)` can fully render the HTML markup of a page to a string on the server. This is especially important for initial page load performance (particularly for mobile users with low bandwidth) and search engine indexing and ranking — both for SEO (search engine optimization) and SEM (search engine marketing).
11 |
12 | However, it turns out that React’s server-side rendering can become a performance bottleneck for pages requiring many virtual DOM nodes. On large pages, `ReactDOMServer.renderToString(..)` can monopolize the CPU, block node’s event-loop and starve out incoming requests to the server. That’s because for every page request, the entire page needs to be rendered, even fine-grained components — which given the same props, always return the same markup. CPU time is wasted in unnecessarily re-rendering the same components for every page request. Similar to pure functions in functional programing a pure component will always return the same HTML markup given the same props. Which means it should be possible to memoize (or cache) the rendered results to speed up rendering significantly after the first response.
13 |
14 | We also wanted the ability to memoize any pure component, not just those that implement a certain interface. So we created a configurable component caching library that accepts a map of component name to a cacheKey generator function. Application owners can opt into this optimization by specifying the component's name and referencing a cacheKey generator function. The cacheKey generator function returns a string representing all inputs into the component's rendering that is then used to cache the rendered markup. Subsequent renderings of the component with the same name and the same props will hit the cache and return the cached result. This optimization lowers CPU time for each page request and allows more concurrent requests that are not blocked on synchronous `renderToString` calls. The CPU profiles we took after before and after applying these optimizations show significant reduction no CPU utilization for each request.
15 |
16 |
17 |
18 | ### YouTube: Hastening React SSR with Component Memoization and Templatization
19 | To learn more about why we built this library, check out a talk from the Full Stack meetup from July 2016:
20 |
21 |
22 |
23 | As well as another (lower quality) recording from the San Diego Web Performance meetup from August 2016:
24 |
25 |
26 |
27 | Slide Deck: [Hastening React SSR with component memoization and templatization](https://speakerdeck.com/maxnajim/hastening-react-ssr-with-component-memoization-and-templatization)
28 |
29 |
30 | ## How we built it
31 | After peeling through the React codebase we discovered React’s mountComponent function. This is where the HTML markup is generated for a component. We knew that if we could intercept React's instantiateReactComponent module by using a `require()` hook we could avoid the need to fork React and inject our optimization. We keep a Least-Recently-Used (LRU) cache that stores the markup of rendered components (replacing the data-reactid appropriately).
32 |
33 | We also implemented an enhancement that will templatize the cached rendered markup to allow for more dynamic props. Dynamic props are replaced with template delimiters (i.e. ${ prop_name }) during the react component rendering cycle. The template is them compiled, cached, executed and the markup is handed back to React. For subsequent requests the component's render(..) call is short-circuited with an execution of the cached compiled template.
34 |
35 | ## How you install it
36 |
37 | ```
38 | npm install --save react-ssr-optimization
39 | ```
40 |
41 | ## How you use it
42 |
43 | You should load the module in the first script that's executed by Node, typically `index.js`.
44 |
45 | In `index.js` you will have code that looks something like this:
46 |
47 | ```js
48 | "use strict";
49 |
50 | var componentOptimization = require("react-ssr-optimization");
51 |
52 | var keyGenerator = function (props) {
53 | return props.id + ":" + props.name;
54 | };
55 |
56 | var componentOptimizationRef = componentOptimization({
57 | components: {
58 | 'Component1': keyGenerator,
59 | 'Component2': {
60 | cacheKeyGen: keyGenerator,
61 | },
62 | },
63 | lruCacheSettings: {
64 | max: 500, //The maximum size of the cache
65 | }
66 | });
67 | ```
68 |
69 | With the cache reference you can also execute helpful operational functions like these:
70 |
71 | ```js
72 | //can be turned off and on dynamically by calling the enable function.
73 | componentOptimizationRef.enable(false);
74 | // Return an array of the cache entries
75 | componentOptimizationRef.cacheDump();
76 | // Return total length of objects in cache taking into account length options function.
77 | componentOptimizationRef.cacheLength();
78 | // Clear the cache entirely, throwing away all values.
79 | componentOptimizationRef.cacheReset();
80 | ```
81 | ### How you use component templatization
82 |
83 | Even though pure components ‘should’ always render the same markup structure there are certain props that might be more dynamic than others. Take for example the following simplified product react component.
84 |
85 | ```js
86 | var React = require('react');
87 |
88 | var ProductView = React.createClass({
89 | render: function() {
90 | return (
91 |
92 |
93 |
94 |
{this.props.product.name}
95 |
{this.props.product.description}
96 |
Price: ${this.props.selected.price}
97 |
100 |
101 |
102 | );
103 | }
104 | });
105 |
106 | module.exports = ProductView;
107 | ```
108 | This component takes props like product image, name, description, price. If we were to apply the component memoization described above, we’d need a cache large enough to hold all the products. Moreover, less frequently accessed products would likely to have more cache misses. This is why we also added the component templatization feature. This feature requires classifying properties in two different groups:
109 |
110 | * Template Attributes: Set of properties that can be templatized. For example in a component, the url and label are template attributes since the structure of the markup does not change with different url and label values.
111 | * Cache Key Attributes: Set of properties that impact the rendered markup. For example, availabilityStatus of a item impacts the resulting markup from generating a ‘Add To Cart’ button to ‘Get In-stock Alert’ button along with pricing display etc.
112 |
113 | These attributes are configured in the component caching library, but instead of providing a cacheKey generator function you’d pass in the templateAttrs and cacheAttrs instead. It looks something like this:
114 |
115 | ```js
116 | var componentOptimization = require("react-ssr-optimization");
117 |
118 | componentOptimization({
119 | components: {
120 | "ProductView": {
121 | templateAttrs: ["product.image", "product.name", "product.description", "product.price"],
122 | cacheAttrs: ["product.inventory"]
123 | },
124 | "ProductCallToAction": {
125 | templateAttrs: ["url"],
126 | cacheAttrs: ["availabilityStatus", "isAValidOffer", "maxQuantity", "preorder", "preorderInfo.streetDateType", "puresoi", "variantTypes", "variantUnselectedExp"]
127 | }
128 | }
129 | });
130 | ```
131 | Notice that the template attributes for ProductView are all the dynamic props that would be different for each product. In this example, we also used product.inventory prop as a cache key attribute since the markup changes based on inventory logic to enable the add to cart button. Here is the same product component from above cached as a template.
132 |
133 | ```html
134 |
135 |
136 |
137 |
${product_name}
138 |
${product_description}
139 |
Price: ${selected_price}
140 |
143 |
144 |
145 | ```
146 | For the given component name, the cache key attributes are used to generate a cache key for the template. For subsequent requests the component’s render is short-circuited with a call to the compiled template.
147 |
148 | ### How you configure it
149 |
150 | Here are a set of option that can be passed to the `react-ssr-optimization` library:
151 |
152 | - `components`: A _required_ map of components that will be cached and the corresponding function to generate its cache key.
153 | - `key`: a _required_ string name identifying the component. This can be either the name of the component when it extends `React.Component` or the `displayName` variable.
154 | - `value`: a _required_ function/object which generates a string that will be used as the component's CacheKey. If an object, it can contain the following attributes
155 | - `cacheKeyGen`: an _optional_ function which generates a string that will be used as the component's CacheKey. If cacheKeyGen and cacheAttrs are not set, then only one element for the component will exist in the cache
156 | - `templateAttrs`: an _optional_ array of strings corresponding to attribute name/key in props that need to be templatized. Each value can have deep paths ex: x.y.z
157 | - `cacheAttrs`: an _optional_ array of attributes to be used for generating a cache key. Can be used in place of `cacheKeyGen`.
158 | - `lruCacheSettings`: By default, this library uses a Least Recently Used (LRU) cache to store rendered markup of cached components. As the name suggests, LRU caches will throw out the data that was least recently used. As more components are put into the cache other rendered components will fall out of the cache. Configuring the LRU cache properly is essential for server optimization. Here are the LRU cache configurations you should consider setting:
159 | - `max`: an _optional_ number indicating the maximum size of the cache, checked by applying the length function to all values in the cache. Default value is `Infinity`.
160 | - `maxAge`: an _optional_ number indicating the maximum age in milliseconds. Default value is `Infinity`.
161 | - `length`: an _optional_ function that is used to calculate the length of stored items. The default is `function(){return 1}`.
162 | - `cacheImpl`: an _optional_ config that allows the usage of a custom cache implementation. This will take precedence over the `lruCacheSettings` option.
163 | - `disabled`: an _optional_ config indicating that the component caching feature should be disabled after instantiation.
164 | - `eventCallback`: an _optional_ function that is executed for interesting events like cache miss and hits. The function should take an event object `function(e){...}`. The event object will have the following properties:
165 | - `type`: the type of event, e.g. "cache".
166 | - `event`: the kind of event, e.g. "miss" for cache events.
167 | - `cmpName`: the component name that this event transpired on, e.g. "Hello World" component.
168 | - `loadTimeNS`: the load time spent loading/generating a value for a cache miss, in nanoseconds. This only returns a value when `collectLoadTimeStats` option is enabled.
169 | - `collectLoadTimeStats`: an _optional_ config indicating enabling the `loadTimeNS` stat to be calculated and returned in the `eventCallback` cache miss events.
170 |
171 | ## Other Performance Approaches
172 |
173 | It is important to note that there are several other independent projects that are endeavoring to solve the React server-side rendering bottleneck. Projects like [react-dom-stream](https://github.com/aickin/react-dom-stream) and [react-server](https://github.com/redfin/react-server) attempt to deal with the synchronous nature of ReactDOM.renderToString by rendering React pages asynchronously and in separate chunks. Streaming and chunking react rendering helps on the server by preventing synchronous render processing from starving out other concurrent requests. Streaming the initial HTML markup also means that browsers can start painting pages earlier (without having to wait for the entire response).
174 |
175 | These approaches help improve user perceived performance since content can be painted sooner on the screen. But whether rendering is done synchronously or asynchronously, the total CPU time remains the same since the same amount of work still needs to be done. In contrast, component memoization and templatization reduces the total amount of CPU time for subsequent requests that re-render the same components again. These rendering optimizations can be used in conjunction with other performance enhancements like asynchronous rendering.
176 |
--------------------------------------------------------------------------------
/test/spec/index.spec.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | //Library is restricted to work in production node environment
4 | process.env.NODE_ENV = "production";
5 |
6 | const chai = require("chai");
7 | const expect = chai.expect;
8 | const reactComponentCache = require("../..");
9 | const intercept = require("intercept-stdout");
10 |
11 | const clearRequireCache = function () {
12 | Object.keys(require.cache).forEach(
13 | function (key) {
14 | delete require.cache[key];
15 | }
16 | );
17 | };
18 |
19 | describe("react-component-cache", function () {
20 | it("should be loaded", () => {
21 | reactComponentCache({});
22 | expect(reactComponentCache).to.be.ok;
23 | });
24 |
25 | it("should cache components", () => {
26 | let renderCount = 0;
27 | reactComponentCache({
28 | components: {"HelloWorld": function (props) {return props.text;}}});
29 |
30 | const React = require("react");
31 | const ReactDomServer = require("react-dom/server");
32 | class HelloWorld extends React.Component {
33 | render() {
34 | renderCount++;
35 | return React.DOM.div(null, this.props.text);
36 | }
37 | }
38 |
39 | // Cache Miss
40 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}));
41 | expect(renderCount).to.equal(1);
42 | // Cache Hit
43 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}));
44 | expect(renderCount).to.equal(1);
45 | // Cache Hit
46 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}));
47 | expect(renderCount).to.equal(1);
48 | // Cache Miss
49 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World Y!"}));
50 | expect(renderCount).to.equal(2);
51 | });
52 |
53 | it("should accept attributes to generate key", () => {
54 | clearRequireCache();
55 | let renderCount = 0;
56 | /* eslint-disable max-params, no-console*/
57 | reactComponentCache({
58 | components: {
59 | "HelloWorld": {
60 | cacheAttrs: ["text"]
61 | }
62 | }
63 | });
64 | /* eslint-enable max-params, no-console*/
65 | const React = require("react");
66 | const ReactDomServer = require("react-dom/server");
67 | class HelloWorld extends React.Component {
68 | render() {
69 | renderCount++;
70 | return React.DOM.div(null, this.props.text);
71 | }
72 | }
73 |
74 | // Cache Miss
75 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}));
76 | expect(renderCount).to.equal(1);
77 | // Cache Miss - Not cached
78 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World Y!"}));
79 | expect(renderCount).to.equal(2);
80 | // Cache Hit
81 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}));
82 | expect(renderCount).to.equal(2);
83 | // Cache Hit
84 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World Y!"}));
85 | expect(renderCount).to.equal(2);
86 | });
87 |
88 | it("should accept deep attrs for key gen", () => {
89 | clearRequireCache();
90 | let renderCount = 0;
91 | /* eslint-disable max-params, no-console*/
92 | reactComponentCache({
93 | components: {
94 | "HelloWorld": {
95 | cacheAttrs: ["data.text"]
96 | }
97 | }
98 | });
99 | /* eslint-enable max-params, no-console*/
100 | const React = require("react");
101 | const ReactDomServer = require("react-dom/server");
102 | class HelloWorld extends React.Component {
103 | render() {
104 | renderCount++;
105 | return React.DOM.div(null, this.props.data.text);
106 | }
107 | }
108 |
109 | const props1 = {data: { text: "Hello World X!"}};
110 | const props2 = {data: { text: "Hello World Y!"}};
111 |
112 | // Cache Miss
113 | expect(ReactDomServer.renderToString(React.createFactory(HelloWorld)(props1))).to.contains("Hello World X!");
114 | expect(renderCount).to.equal(1);
115 | // Cache Miss
116 | expect(ReactDomServer.renderToString(React.createFactory(HelloWorld)(props2))).to.contains("Hello World Y!");
117 | expect(renderCount).to.equal(2);
118 | // Cache Hit
119 | expect(ReactDomServer.renderToString(React.createFactory(HelloWorld)(props1))).to.contains("Hello World X!");
120 | expect(renderCount).to.equal(2);
121 | // Cache Hit
122 | expect(ReactDomServer.renderToString(React.createFactory(HelloWorld)(props2))).to.contains("Hello World Y!");
123 | expect(renderCount).to.equal(2);
124 | });
125 |
126 | it("should cache components only when key is not null", () => {
127 | clearRequireCache();
128 | let renderCount = 0;
129 | reactComponentCache({
130 | components: {
131 | "HelloWorld": {
132 | cacheKeyGen: function (props) {
133 | // Only cache when "X" is in the text
134 | return props.text.indexOf("X") > -1 ? props.text : null;
135 | }
136 | }
137 | }});
138 |
139 | const React = require("react");
140 | const ReactDomServer = require("react-dom/server");
141 | class HelloWorld extends React.Component {
142 | render() {
143 | renderCount++;
144 | return React.DOM.div(null, this.props.text);
145 | }
146 | }
147 |
148 | // Cache Miss
149 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}));
150 | expect(renderCount).to.equal(1);
151 | // Cache Miss - Not cached since cache key function returned null
152 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World Y!"}));
153 | expect(renderCount).to.equal(2);
154 | // Cache Hit
155 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}));
156 | expect(renderCount).to.equal(2);
157 | // Cache Miss - Not cached since cache key function returned null
158 | ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World Y!"}));
159 | expect(renderCount).to.equal(3);
160 | });
161 |
162 | it("should accept custom LRU cache configurations", () => {
163 | clearRequireCache();
164 |
165 | // Set maximum cache size to 1
166 | const cacheConfig = {
167 | max: 1
168 | };
169 |
170 | let renderCount = 0;
171 | reactComponentCache({
172 | components: {"HelloWorld2": function (props) {return props.text;}},
173 | lruCacheSettings: cacheConfig
174 | });
175 |
176 | const React = require("react");
177 | const ReactDomServer = require("react-dom/server");
178 | class HelloWorld2 extends React.Component {
179 | render() {
180 | renderCount++;
181 | return React.DOM.div(null, this.props.text);
182 | }
183 | }
184 |
185 | // Cache Miss
186 | ReactDomServer.renderToString(React.createFactory(HelloWorld2)({text: "Hello World X!"}));
187 | expect(renderCount).to.equal(1);
188 | // Cache Miss
189 | ReactDomServer.renderToString(React.createFactory(HelloWorld2)({text: "Hello World Y!"}));
190 | expect(renderCount).to.equal(2);
191 | // Cache Miss since cache size is 1
192 | ReactDomServer.renderToString(React.createFactory(HelloWorld2)({text: "Hello World X!"}));
193 | expect(renderCount).to.equal(3);
194 | // Cache Hit
195 | ReactDomServer.renderToString(React.createFactory(HelloWorld2)({text: "Hello World X!"}));
196 | expect(renderCount).to.equal(3);
197 | });
198 |
199 | it("should accept template configurations", () => {
200 | clearRequireCache();
201 |
202 | let renderCount = 0;
203 | /* eslint-disable max-params, no-console*/
204 | reactComponentCache({
205 | components: {
206 | "HelloWorld": {
207 | templateAttrs: ["text"]
208 | }
209 | }
210 | });
211 | /* eslint-enable max-params, no-console*/
212 | const React = require("react");
213 | const ReactDomServer = require("react-dom/server");
214 | class HelloWorld extends React.Component {
215 | render() {
216 | renderCount++;
217 | return React.DOM.div(null, this.props.text);
218 | }
219 | }
220 |
221 | // Cache Miss
222 | expect(ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}))).to.contains("Hello World X!");
223 | expect(renderCount).to.equal(1);
224 | // Cache Hit since it is templatized
225 | expect(ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World Y!"}))).to.contains("Hello World Y!");
226 | expect(renderCount).to.equal(1);
227 | // Cache Hit
228 | expect(ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}))).to.contains("Hello World X!");
229 | expect(renderCount).to.equal(1);
230 | // Cache Hit
231 | expect(ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}))).to.contains("Hello World X!");
232 | expect(renderCount).to.equal(1);
233 | });
234 |
235 | it("should accept template configurations with cache key attribute", () => {
236 | clearRequireCache();
237 |
238 | let renderCount = 0;
239 | /* eslint-disable max-params, no-console*/
240 | reactComponentCache({
241 | components: {
242 | "HelloWorld": {
243 | cacheAttrs: ["flags"],
244 | templateAttrs: ["text"]
245 | }
246 | }
247 | });
248 | /* eslint-enable max-params, no-console*/
249 | const React = require("react");
250 | const ReactDomServer = require("react-dom/server");
251 | class HelloWorld extends React.Component {
252 | render() {
253 | renderCount++;
254 | return this.props.flags && this.props.flags.bold ? React.DOM.h1(null, this.props.text) : React.DOM.div(null, this.props.text);
255 | }
256 | }
257 |
258 | let markup = ReactDomServer.renderToString(React.createFactory(HelloWorld)({text: "Hello World X!"}));
259 | expect(markup).to.contains("Hello World X!");
260 | expect(markup).to.contains("