Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -778,8 +778,15 @@ annotations are fine). The same holds for a root schema that is itself a
`$ref` with its `definitions` next to it.

Any other schema silently uses the default mechanism, so the option is always
safe to enable. The projection only pays off where V8 has the fast path, so on
Node.js 24 and older the option is a no-op and the default mechanism is used.
safe to enable. Where the projection is used also depends on the runtime:

- Node.js 25+ (V8 has the `JSON.stringify` fast path): every schema listed above;
- Node.js 22 and 24: only the schemas where at least half of the values are
strings. Without the fast path the projection is still faster on strings,
which the native `JSON.stringify` escapes faster than the generated code, and
slower on numbers and booleans;
- older runtimes: never, the option is a no-op.

On Node.js 25+ the projection serializes plain objects within 5-16% of a bare
`JSON.stringify` (2-6% on the fixtures in `benchmark/`; the default mechanism
is 25-45% behind it there). On a list of 50 eight-property objects it is
Expand All @@ -796,8 +803,8 @@ a serializer keeps no data of the last input in memory.

Enable `objectMechanism: 'native'` when your application runs on Node.js 25+.
Schemas the projection does not cover keep the default mechanism, the output
is the same, and on older Node.js versions the option does nothing. It pays
off most when:
is the same, and on Node.js 22 and 24 only string-heavy schemas use the
projection. It pays off most when:

- the serialized objects are ORM entities or class instances, or carry columns
that the schema does not declare (the usual case for a response schema).
Expand All @@ -812,8 +819,8 @@ off most when:
v7.3.9 the default mechanism was the faster one here.

Keep the default mechanism when a benchmark on your own payloads shows no
gain, or on Node.js 24 and older, where the option has no effect. The two
mechanisms are interchangeable at any time, since they produce the same output.
gain. The two mechanisms are interchangeable at any time, since they produce
the same output.

With Fastify, pass the option through `serializerOpts`:

Expand Down
23 changes: 15 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,11 @@ const NAMED_FRAGMENT_REF = /^#[a-z_][-\w._]*$/i
// TODO: drop the Node 20 tier (and this version check) once Node 20 is no
// longer supported.
const nodeMajor = Number.parseInt(process.versions.node, 10)
// objectMechanism: 'native' relies on the V8 13.8 JSON.stringify fast path.
const { HAS_FAST_JSON_STRINGIFY: PROJECTION_SUPPORTED } = require('./lib/v8')
// objectMechanism: 'native' is used for every projectable schema where V8 has
// the JSON.stringify fast path (V8 13.8+, Node 25+), only for the schemas made
// mostly of strings on Node 22 and 24, and never on older runtimes.
// 0: never, 1: schemas made mostly of strings, 2: always
const PROJECTION_TIER = Number(require('./lib/v8').HAS_FAST_JSON_STRINGIFY) + Number(nodeMajor >= 22)
const PRIMITIVE_FAST_PATH_MIN_LENGTH = [{ integer: 3e5, number: 3e5, string: 128 }, { integer: 512, number: 128, string: 8 }][+(nodeMajor >= 22)]
const STRING_ARRAY_FAST_PATH_MIN_LENGTH = PRIMITIVE_FAST_PATH_MIN_LENGTH.string
const INTEGER_ARRAY_FAST_PATH = { condition: 'Number.isInteger(v)', minLength: PRIMITIVE_FAST_PATH_MIN_LENGTH.integer }
Expand Down Expand Up @@ -546,19 +549,23 @@ function build (schema, options) {
// objects and delegates to the native JSON.stringify. Only whole schemas
// made of objects, arrays and primitives qualify; anything else falls back
// to the string codegen below, so output never changes for unsupported shapes.
// The projection only pays off where V8 has the side-effect-free
// JSON.stringify fast path (V8 13.8+, Node 25+): on older runtimes the
// string codegen is up to 2x faster, so the option is a no-op there.
// Where V8 has the side-effect-free JSON.stringify fast path (V8 13.8+,
// Node 25+) the projection pays off on every projectable schema. Without it
// (Node 22 and 24) it pays off on strings, which the string codegen escapes
// one by one in JavaScript, and not on numbers and booleans, so it is used
// only for the schemas made mostly of strings.
let code = null
let projection = null
// `forceProjection` is an internal, undocumented escape hatch used by the
// test suite to exercise the projection on runtimes where it is gated off.
if (context.objectMechanism === 'native' && (options.forceProjection === true || PROJECTION_SUPPORTED)) {
// test suite to exercise each tier on every runtime: true is the tier of
// Node 25+, 'string-heavy' the one of Node 22 and 24.
const projectionTier = options.forceProjection === true ? 2 : options.forceProjection === 'string-heavy' ? 1 : PROJECTION_TIER
if (context.objectMechanism === 'native' && projectionTier !== 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With largeArrayMechanism: 'json-stringify' the projection’s output differs from the default mechanism: on arrays at or above largeArraySize, undeclared properties are stripped and items are coerced. This already happens on Node 25+. With this PR it also reaches Node 22/24 users who set both options, and until now they got the default mechanism’s output:

const o = { largeArrayMechanism: 'json-stringify', largeArraySize: 2 }
build({ type: 'array', items: { type: 'string' } }, o)([1, 2, 3])                              // [1,2,3]
build({ type: 'array', items: { type: 'string' } }, { ...o, objectMechanism: 'native' })([1, 2, 3]) // ["1","2","3"]

projection = buildProjection(location, {
resolve: (location) => resolveRef(context, location),
pointer: (location) => getSafeSchemaRef(context, location),
ignoredSiblings: IGNORED_REF_SIBLING_KEYWORDS
})
}, projectionTier === 1)
}
if (projection === null) {
code = buildValue(context, location, 'input')
Expand Down
31 changes: 28 additions & 3 deletions lib/projection.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,15 +289,40 @@ class Emitter {
}
}

// Counts the primitive values of a projectable schema and how many of them
// are strings, plain or ['string', 'null']. The items of an array count once.
function countValues (schema, count = { values: 0, strings: 0 }) {
if (schema.type === 'object') {
for (const key of Object.keys(schema.properties)) countValues(schema.properties[key], count)
} else if (schema.type === 'array') {
countValues(schema.items, count)
} else {
count.values++
if (schema.type === 'string' || nullableMultiType(schema) === 'string') count.strings++
}
return count
}

// True when at least half of the values of a projectable schema are strings.
// Without the V8 fast path the projection gains on strings, which the native
// JSON.stringify escapes faster than the generated code, and loses the cost of
// filling the scratch on numbers and booleans.
function isStringHeavy (schema) {
const { values, strings } = countValues(schema)
return strings * 2 >= values
}

// Returns the full body of the context function (declarations + main) or null
// when the schema at `location` is not projectable. `refs` is how the codegen
// reads a $ref: `resolve(location)` gives the location of its target,
// when the schema at `location` is not projectable, or when `onlyStringHeavy`
// is set and the schema is not made mostly of strings. `refs` is how the
// codegen reads a $ref: `resolve(location)` gives the location of its target,
// `pointer(location)` the JSON pointer used in the errors, `ignoredSiblings`
// the keywords that may stand next to a $ref without changing its target.
function buildProjection (location, refs) {
function buildProjection (location, refs, onlyStringHeavy = false) {
const schema = resolveProjectable(location, refs, { open: new Set(), refNodes: 0 }, 0)
if (schema === null) return null
if (schema.type !== 'object' && schema.type !== 'array') return null // primitive roots gain nothing
if (onlyStringHeavy && !isStringHeavy(schema)) return null
const em = new Emitter()
const body = []
const rootExpr = em.valueExpr(schema, 'input', body, ' ')
Expand Down
85 changes: 76 additions & 9 deletions test/object-mechanism-gate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,84 @@

const { test } = require('node:test')

// objectMechanism: 'native' is a no-op on runtimes without the V8 JSON.stringify
// fast path (Node < 25).
// objectMechanism: 'native' depends on the runtime and on the schema:
// - Node 25+ (V8 13.8+, JSON.stringify fast path): every projectable schema;
// - Node 22 and 24: only the schemas where at least half of the values are
// strings;
// - older runtimes: never.
const build = require('..')

const schema = { type: 'object', properties: { a: { type: 'string' }, n: { type: 'number' } } }
const nodeMajor = Number.parseInt(process.versions.node, 10)
const { HAS_FAST_JSON_STRINGIFY: hasFastPath } = require('../lib/v8')

test('native mechanism is enabled only on Node 25+', t => {
t.plan(2)
const code = build(schema, { objectMechanism: 'native', mode: 'debug' }).code
t.assert.equal(code.includes('asStringValue'), nodeMajor >= 25)
// whatever the runtime, output is the same as the default mechanism
t.assert.equal(build(schema, { objectMechanism: 'native' })({ a: 'x', n: 1, extra: true }), build(schema)({ a: 'x', n: 1, extra: true }))
const S = { type: 'string' }
const numeric = { type: 'object', properties: { a: S, n: { type: 'number' }, i: { type: 'integer' }, b: { type: 'boolean' } } } // 1 of 4
const stringHeavy = { type: 'object', properties: { a: S, b: S, n: { type: 'number' } } } // 2 of 3
const half = { type: 'object', properties: { a: S, n: { type: 'number' } } } // 1 of 2: half is enough
const nested = { // 4 of 5, with a ['string', 'null'] and the items of an array
type: 'object',
properties: {
id: { type: 'integer' },
name: S,
tags: { type: 'array', items: S },
address: { type: 'object', properties: { city: S, zip: { type: ['string', 'null'] } } }
}
}
const nullableNumbers = { type: 'object', properties: { a: S, n: { type: ['number', 'null'] }, b: { type: ['boolean', 'null'] } } } // 1 of 3
const list = { type: 'array', items: stringHeavy }
const numericList = { type: 'array', items: numeric }
// the values behind a $ref count as if they were written in place: 3 of 4 and 1 of 4
const shared = { type: 'object', properties: { a: S, b: S } }
const refToStrings = { type: 'object', definitions: { shared }, properties: { n: { type: 'number' }, s: S, p: { $ref: '#/definitions/shared' } } }
const refToNumbers = { type: 'object', definitions: { numeric }, properties: { p: { $ref: '#/definitions/numeric' } } }
const notProjectable = { type: 'object', properties: { a: S, b: { anyOf: [S, { type: 'number' }] } } }

const schemas = { numeric, stringHeavy, half, nested, nullableNumbers, list, numericList, refToStrings, refToNumbers, notProjectable }
// what each tier projects
const always = { numeric: true, stringHeavy: true, half: true, nested: true, nullableNumbers: true, list: true, numericList: true, refToStrings: true, refToNumbers: true, notProjectable: false }
const onlyStringHeavy = { numeric: false, stringHeavy: true, half: true, nested: true, nullableNumbers: false, list: true, numericList: false, refToStrings: true, refToNumbers: false, notProjectable: false }
const never = { numeric: false, stringHeavy: false, half: false, nested: false, nullableNumbers: false, list: false, numericList: false, refToStrings: false, refToNumbers: false, notProjectable: false }

function projected (options) {
const result = {}
for (const name of Object.keys(schemas)) {
result[name] = build(schemas[name], { objectMechanism: 'native', mode: 'debug', ...options }).code.includes('asStringValue')
}
return result
}

test('native mechanism: which schemas are projected on this runtime', t => {
t.plan(1)
t.assert.deepStrictEqual(projected(), hasFastPath ? always : nodeMajor >= 22 ? onlyStringHeavy : never)
})

test('native mechanism: each tier can be forced on every runtime', t => {
t.plan(3)
t.assert.deepStrictEqual(projected({ forceProjection: true }), always)
t.assert.deepStrictEqual(projected({ forceProjection: 'string-heavy' }), onlyStringHeavy)
// the default mechanism never projects
t.assert.deepStrictEqual(projected({ objectMechanism: 'default', forceProjection: true }), never)
})

test('native mechanism: whatever the tier, the output is the one of the default mechanism', t => {
const inputs = {
numeric: { a: 'x', n: 1.5, i: 2, b: true, extra: true },
stringHeavy: { a: 'x', b: 'y', n: 1, extra: true },
half: { a: 'x', n: 1 },
nested: { id: 1, name: 'n', tags: ['a', 'b'], address: { city: 'c', zip: null }, extra: true },
nullableNumbers: { a: 'x', n: null, b: false },
list: [{ a: 'x', b: 'y', n: 1 }, { a: 'z', b: 'w', n: 2, extra: 1 }],
numericList: [{ a: 'x', n: 1, i: 2, b: false }],
refToStrings: { n: 1, s: 's', p: { a: 'x', b: 'y', extra: true } },
refToNumbers: { p: { a: 'x', n: 1, i: 2, b: true } },
notProjectable: { a: 'x', b: 5 }
}
const tiers = [{}, { forceProjection: true }, { forceProjection: 'string-heavy' }]
t.plan(Object.keys(schemas).length * tiers.length)
for (const name of Object.keys(schemas)) {
const expected = build(schemas[name])(inputs[name])
for (const tier of tiers) {
t.assert.equal(build(schemas[name], { objectMechanism: 'native', ...tier })(inputs[name]), expected)
}
}
})
Loading