chore(xo-server): remove createRawObject

Replace both `createRawObject()` and `Object.create()` by `{ __proto__: null }`.
This commit is contained in:
Julien Fontanet
2018-03-05 17:04:48 +01:00
parent 0308fe4e6e
commit 13f2470887
16 changed files with 44 additions and 76 deletions

View File

@@ -1,6 +1,6 @@
import { EventEmitter } from 'events'
import { createRawObject, noop } from './utils'
import { noop } from './utils'
// ===================================================================
@@ -8,7 +8,7 @@ export default class Connection extends EventEmitter {
constructor () {
super()
this._data = createRawObject()
this._data = { __proto__: null }
}
// Close the connection.

View File

@@ -22,7 +22,6 @@ import { ensureDir, readdir, readFile } from 'fs-extra'
import WebServer from 'http-server-plus'
import Xo from './xo'
import {
createRawObject,
forEach,
isArray,
isFunction,
@@ -103,7 +102,7 @@ function createExpressApp () {
}
async function setUpPassport (express, xo) {
const strategies = createRawObject()
const strategies = { __proto__: null }
xo.registerPassportStrategy = strategy => {
passport.use(strategy)

View File

@@ -73,16 +73,9 @@ export function camelToSnakeCase (string) {
// -------------------------------------------------------------------
// Returns an empty object without prototype (if possible).
export const createRawObject = Object.create
? (createObject => () => createObject(null))(Object.create)
: () => ({})
// -------------------------------------------------------------------
// Only works with string items!
export const diffItems = (coll1, coll2) => {
const removed = createRawObject()
const removed = { __proto__: null }
forEach(coll2, value => {
removed[value] = true
})
@@ -209,7 +202,7 @@ export const parseXml = (function () {
// - works only with strings
// - methods are already bound and chainable
export const lightSet = collection => {
let data = createRawObject()
let data = { __proto__: null }
if (collection) {
forEach(collection, value => {
data[value] = true
@@ -223,7 +216,7 @@ export const lightSet = collection => {
return set
},
clear: () => {
data = createRawObject()
data = { __proto__: null }
return set
},
delete: value => {

View File

@@ -2,7 +2,6 @@
import {
camelToSnakeCase,
createRawObject,
diffItems,
ensureArray,
extractProperty,
@@ -32,24 +31,6 @@ describe('camelToSnakeCase()', function () {
// -------------------------------------------------------------------
describe('createRawObject()', () => {
it('returns an empty object', () => {
expect(createRawObject()).toEqual({})
})
it('creates a new object each time', () => {
expect(createRawObject()).not.toBe(createRawObject())
})
if (Object.getPrototypeOf) {
it('creates an object without a prototype', () => {
expect(Object.getPrototypeOf(createRawObject())).toBe(null)
})
}
})
// -------------------------------------------------------------------
describe('diffItems', () => {
it('computes the added/removed items between 2 iterables', () => {
expect(diffItems(['foo', 'bar'], ['baz', 'foo'])).toEqual([

View File

@@ -35,7 +35,6 @@ import { mixin } from '../decorators'
import {
asyncMap,
camelToSnakeCase,
createRawObject,
ensureArray,
forEach,
isFunction,
@@ -101,8 +100,8 @@ export default class Xapi extends XapiBase {
return getObject.apply(this, args)
})(this.getObject)
const genericWatchers = (this._genericWatchers = createRawObject())
const objectsWatchers = (this._objectWatchers = createRawObject())
const genericWatchers = (this._genericWatchers = { __proto__: null })
const objectsWatchers = (this._objectWatchers = { __proto__: null })
const onAddOrUpdate = objects => {
forEach(objects, object => {
@@ -776,7 +775,7 @@ export default class Xapi extends XapiBase {
}
_assertHealthyVdiChains (vm) {
const cache = createRawObject()
const cache = { __proto__: null }
forEach(vm.$VBDs, ({ $VDI }) => {
this._assertHealthyVdiChain($VDI, cache)
})

View File

@@ -11,7 +11,6 @@ import unzip from 'julien-f-unzip'
import { debounce } from '../../decorators'
import {
createRawObject,
ensureArray,
forEach,
mapFilter,
@@ -35,7 +34,7 @@ export default {
const data = parseXml(await readAll()).patchdata
const patches = createRawObject()
const patches = { __proto__: null }
forEach(data.patches.patch, patch => {
patches[patch.uuid] = {
date: patch.timestamp,
@@ -65,7 +64,7 @@ export default {
})
const resolveVersionPatches = function (uuids) {
const versionPatches = createRawObject()
const versionPatches = { __proto__: null }
forEach(ensureArray(uuids), ({ uuid }) => {
versionPatches[uuid] = patches[uuid]
@@ -74,7 +73,7 @@ export default {
return versionPatches
}
const versions = createRawObject()
const versions = { __proto__: null }
let latestVersion
forEach(data.serverversions.version, version => {
versions[version.value] = {
@@ -112,7 +111,7 @@ export default {
},
_getInstalledPoolPatchesOnHost (host) {
const installed = createRawObject()
const installed = { __proto__: null }
// platform_version < 2.1.1
forEach(host.$patches, hostPatch => {
@@ -131,7 +130,7 @@ export default {
const all = await this._getPoolPatchesForHost(host)
const installed = this._getInstalledPoolPatchesOnHost(host)
const installable = createRawObject()
const installable = { __proto__: null }
forEach(all, (patch, uuid) => {
if (installed[uuid]) {
return

View File

@@ -1,6 +1,6 @@
import { forEach, groupBy } from 'lodash'
import { createRawObject, mapToArray } from '../../utils'
import { mapToArray } from '../../utils'
export default {
_connectAllSrPbds (sr) {
@@ -67,9 +67,9 @@ export default {
getUnhealthyVdiChainsLength (sr) {
const vdis = this.getObject(sr).$VDIs
const unhealthyVdis = createRawObject()
const unhealthyVdis = { __proto__: null }
const children = groupBy(vdis, 'sm_config.vhd-parent')
const cache = createRawObject()
const cache = { __proto__: null }
forEach(vdis, vdi => {
if (vdi.managed && !vdi.is_a_snapshot) {
const { uuid } = vdi

View File

@@ -9,7 +9,6 @@ import { satisfies as versionSatisfies } from 'semver'
import {
camelToSnakeCase,
createRawObject,
forEach,
isArray,
isBoolean,
@@ -77,7 +76,7 @@ export const extractOpaqueRef = str => {
// -------------------------------------------------------------------
const TYPE_TO_NAMESPACE = createRawObject()
const TYPE_TO_NAMESPACE = { __proto__: null }
forEach(
[
'Bond',
@@ -116,7 +115,7 @@ export const getNamespaceForType = type => TYPE_TO_NAMESPACE[type] || type
// -------------------------------------------------------------------
export const getVmDisks = vm => {
const disks = createRawObject(null)
const disks = { __proto__: null }
forEach(vm.$VBDs, vbd => {
let vdi
if (

View File

@@ -3,7 +3,6 @@ import { forEach, includes, map } from 'lodash'
import { ModelAlreadyExists } from '../collection'
import { Acls } from '../models/acl'
import { createRawObject } from '../utils'
// ===================================================================
@@ -86,10 +85,10 @@ export default class {
this._getPermissionsByRole(),
])
const permissions = createRawObject()
const permissions = { __proto__: null }
for (const { action, object: objectId } of acls) {
const current =
permissions[objectId] || (permissions[objectId] = createRawObject())
permissions[objectId] || (permissions[objectId] = { __proto__: null })
const permissionsForRole = permissionsByRole[action]
if (permissionsForRole) {
@@ -128,7 +127,7 @@ export default class {
async _getPermissionsByRole () {
const roles = await this.getRoles()
const permissions = createRawObject()
const permissions = { __proto__: null }
for (const role of roles) {
permissions[role.id] = role.permissions
}

View File

@@ -6,7 +6,7 @@ import { forEach, isArray, isFunction, map, mapValues } from 'lodash'
import * as methods from '../api'
import { MethodNotFound } from 'json-rpc-peer'
import { createRawObject, noop, serializeError } from '../utils'
import { noop, serializeError } from '../utils'
import * as errors from 'xo-common/api-errors'
@@ -164,7 +164,7 @@ const removeSensitiveParams = (value, name) => {
export default class Api {
constructor (xo) {
this._logger = null
this._methods = createRawObject()
this._methods = { __proto__: null }
this._xo = xo
this.addApiMethods(methods)

View File

@@ -3,7 +3,7 @@ import { noSuchObject } from 'xo-common/api-errors'
import { ignoreErrors } from 'promise-toolbox'
import Token, { Tokens } from '../models/token'
import { createRawObject, forEach, generateToken } from '../utils'
import { forEach, generateToken } from '../utils'
// ===================================================================
@@ -17,7 +17,7 @@ export default class {
// Store last failures by user to throttle tries (slow bruteforce
// attacks).
this._failures = createRawObject()
this._failures = { __proto__: null }
this._providers = new Set()

View File

@@ -115,14 +115,14 @@ export default class Jobs {
constructor (xo: any) {
this._app = xo
const executors = (this._executors = Object.create(null))
const executors = (this._executors = { __proto__: null })
const jobsDb = (this._jobs = new JobsDb({
connection: xo._redis,
prefix: 'xo:job',
indexes: ['user_id', 'key'],
}))
this._logger = undefined
this._runningJobs = Object.create(null)
this._runningJobs = { __proto__: null }
executors.call = executeCall

View File

@@ -2,7 +2,7 @@ import Ajv from 'ajv'
import { PluginsMetadata } from '../models/plugin-metadata'
import { invalidParameters, noSuchObject } from 'xo-common/api-errors'
import { createRawObject, isFunction, mapToArray } from '../utils'
import { isFunction, mapToArray } from '../utils'
// ===================================================================
@@ -11,7 +11,7 @@ export default class {
this._ajv = new Ajv({
useDefaults: true,
})
this._plugins = createRawObject()
this._plugins = { __proto__: null }
this._pluginsMetadata = new PluginsMetadata({
connection: xo._redis,

View File

@@ -56,7 +56,7 @@ export default class Scheduling {
prefix: 'xo:schedule',
}))
this._runs = Object.create(null)
this._runs = { __proto__: null }
app.on('clean', () => db.rebuildIndexes())
app.on('start', async () => {

View File

@@ -6,7 +6,6 @@ import xapiObjectToXo from '../xapi-object-to-xo'
import XapiStats from '../xapi-stats'
import {
camelToSnakeCase,
createRawObject,
forEach,
isEmpty,
isString,
@@ -19,15 +18,15 @@ import { Servers } from '../models/server'
export default class {
constructor (xo) {
this._objectConflicts = createRawObject() // TODO: clean when a server is disconnected.
this._objectConflicts = { __proto__: null } // TODO: clean when a server is disconnected.
const serversDb = (this._servers = new Servers({
connection: xo._redis,
prefix: 'xo:server',
indexes: ['host'],
}))
this._stats = new XapiStats()
this._xapis = createRawObject()
this._xapisByPool = createRawObject()
this._xapis = { __proto__: null }
this._xapisByPool = { __proto__: null }
this._xo = xo
xo.on('clean', () => serversDb.rebuildIndexes())
@@ -173,7 +172,7 @@ export default class {
const previous = objects.get(xoId, undefined)
if (previous && previous._xapiRef !== xapiObject.$ref) {
const conflicts_ =
conflicts[xoId] || (conflicts[xoId] = createRawObject())
conflicts[xoId] || (conflicts[xoId] = { __proto__: null })
conflicts_[conId] = xoObject
} else {
objects.set(xoId, xoObject)
@@ -235,7 +234,7 @@ export default class {
const conId = server.id
// Maps ids of XAPI objects to ids of XO objects.
const xapiIdsToXo = createRawObject()
const xapiIdsToXo = { __proto__: null }
// Map of XAPI objects which failed to be transformed to XO
// objects.
@@ -243,7 +242,7 @@ export default class {
// At each `finish` there will be another attempt to transform
// until they succeed.
let toRetry
let toRetryNext = createRawObject()
let toRetryNext = { __proto__: null }
const onAddOrUpdate = objects => {
this._onXenAdd(objects, xapiIdsToXo, toRetryNext, conId)
@@ -266,7 +265,7 @@ export default class {
if (!isEmpty(toRetryNext)) {
toRetry = toRetryNext
toRetryNext = createRawObject()
toRetryNext = { __proto__: null }
}
}

View File

@@ -17,7 +17,7 @@ import {
import mixins from './xo-mixins'
import Connection from './connection'
import { mixin } from './decorators'
import { createRawObject, generateToken, noop } from './utils'
import { generateToken, noop } from './utils'
// ===================================================================
@@ -36,9 +36,9 @@ export default class Xo extends EventEmitter {
// Connections to users.
this._nextConId = 0
this._connections = createRawObject()
this._connections = { __proto__: null }
this._httpRequestWatchers = createRawObject()
this._httpRequestWatchers = { __proto__: null }
// Connects to Redis.
{
@@ -90,7 +90,7 @@ export default class Xo extends EventEmitter {
}
}
const results = createRawObject(null)
const results = { __proto__: null }
for (const id in all) {
const object = all[id]
if (filter(object, id, all)) {
@@ -251,8 +251,8 @@ export default class Xo extends EventEmitter {
let entered, exited
function reset () {
entered = createRawObject()
exited = createRawObject()
entered = { __proto__: null }
exited = { __proto__: null }
}
reset()