fastify-ata 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -91,15 +91,16 @@ Works with Fastify v5's Standard Schema support, tRPC, TanStack Form, Drizzle OR
91
91
  | **Serverless cold start** (50 schemas) | 7.7ms | 96ms | **12.5x faster** |
92
92
  | **ReDoS protection** (catastrophic pattern) | 0.3ms | 765ms | **immune** |
93
93
  | **Batch NDJSON** (10K items, multi-core) | 13.4M/sec | 5.1M/sec | **2.6x faster** |
94
- | **validate(obj)** valid (micro) | 15M ops/sec | 8.5M ops/sec | **1.8x faster** |
95
- | **Schema compilation** | 125K ops/sec | 831 ops/sec | **151x faster** |
94
+ | **validate(obj)** valid (isolated) | 76M ops/sec | 8M ops/sec | **9.5x faster** |
95
+ | **validate(obj)** invalid (isolated) | 34M ops/sec | 8M ops/sec | **4.3x faster** |
96
+ | **Schema compilation** | 113K ops/sec | 818 ops/sec | **138x faster** |
96
97
 
97
98
  ### Things only ata can do
98
99
 
99
100
  - **RE2 regex engine** — linear-time guaranteed, immune to ReDoS attacks
100
101
  - **Multi-core parallel validation** — NDJSON batch at 12.5M items/sec
101
102
  - **Standard Schema V1** — native support, ajv doesn't have it
102
- - **151x faster compilation** — serverless cold starts, dynamic schemas
103
+ - **138x faster compilation** — serverless cold starts, dynamic schemas
103
104
 
104
105
  ## License
105
106
 
@@ -0,0 +1,219 @@
1
+ 'use strict'
2
+
3
+ // Matteo's benchmark: @fastify/ajv-compiler standalone vs ata standalone
4
+ // Exactly the approach from https://backend.cafe/how-to-unlock-the-fastest-fastify-server-startup
5
+
6
+ const { fork } = require('child_process')
7
+ const { writeFileSync, mkdirSync, rmSync, existsSync, unlinkSync } = require('fs')
8
+ const path = require('path')
9
+
10
+ function makeRoutes(n) {
11
+ // Realistic: 5 schema types reused across routes (like a real API)
12
+ const bases = [
13
+ { type: 'object', properties: { id: { type: 'integer', minimum: 1 }, name: { type: 'string', minLength: 1 }, email: { type: 'string', format: 'email' }, active: { type: 'boolean' } }, required: ['id', 'name', 'email', 'active'] },
14
+ { type: 'object', properties: { id: { type: 'integer', minimum: 1 }, title: { type: 'string', minLength: 1 }, price: { type: 'number', minimum: 0 }, inStock: { type: 'boolean' } }, required: ['id', 'title', 'price'] },
15
+ { type: 'object', properties: { orderId: { type: 'string' }, userId: { type: 'integer' }, total: { type: 'number', minimum: 0 }, status: { type: 'string' } }, required: ['orderId', 'userId', 'total'] },
16
+ { type: 'object', properties: { query: { type: 'string', minLength: 1 }, page: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 100 } }, required: ['query'] },
17
+ { type: 'object', properties: { token: { type: 'string', minLength: 10 }, action: { type: 'string' }, timestamp: { type: 'integer' } }, required: ['token', 'action'] },
18
+ ]
19
+ return Array.from({ length: n }, (_, i) => ({
20
+ url: '/route' + i,
21
+ schema: bases[i % bases.length],
22
+ }))
23
+ }
24
+
25
+ // ============================================================
26
+ // 1. ajv default (no standalone)
27
+ // ============================================================
28
+ function ajvDefaultScript(routes) {
29
+ return `
30
+ 'use strict'
31
+ const start = performance.now()
32
+ const fastify = require('fastify')()
33
+ const routes = ${JSON.stringify(routes)}
34
+ routes.forEach(r => {
35
+ fastify.post(r.url, { schema: { body: r.schema } }, (req, reply) => reply.send({ ok: true }))
36
+ })
37
+ fastify.ready().then(() => {
38
+ process.send({ ms: performance.now() - start })
39
+ process.exit()
40
+ })
41
+ `
42
+ }
43
+
44
+ // ============================================================
45
+ // 2. ajv standalone (blog post approach)
46
+ // ============================================================
47
+ function ajvStandaloneBuildScript(routes, dir) {
48
+ return `
49
+ 'use strict'
50
+ const fastify = require('fastify')
51
+ const fs = require('fs')
52
+ const path = require('path')
53
+ const { StandaloneValidator } = require('@fastify/ajv-compiler')
54
+ const sanitize = require('sanitize-filename')
55
+
56
+ function generateFileName(routeOpts) {
57
+ return path.join('${dir}', 'gen-' + routeOpts.method + '-' + (routeOpts.httpPart || routeOpts.httpStatus) + '-' + sanitize(routeOpts.url) + '.js')
58
+ }
59
+
60
+ const app = fastify({
61
+ jsonShorthand: false,
62
+ schemaController: {
63
+ compilersFactory: {
64
+ buildValidator: StandaloneValidator({
65
+ readMode: false,
66
+ storeFunction(routeOpts, code) { fs.writeFileSync(generateFileName(routeOpts), code) }
67
+ })
68
+ }
69
+ }
70
+ })
71
+
72
+ const routes = ${JSON.stringify(routes)}
73
+ routes.forEach(r => {
74
+ app.post(r.url, { schema: { body: r.schema } }, (req, reply) => reply.send({ ok: true }))
75
+ })
76
+ app.ready().then(() => { process.send({ done: true }); process.exit() })
77
+ `
78
+ }
79
+
80
+ function ajvStandaloneReadScript(routes, dir) {
81
+ return `
82
+ 'use strict'
83
+ const start = performance.now()
84
+ const fastify = require('fastify')
85
+ const path = require('path')
86
+ const { StandaloneValidator } = require('@fastify/ajv-compiler')
87
+ const sanitize = require('sanitize-filename')
88
+
89
+ function generateFileName(routeOpts) {
90
+ return path.join('${dir}', 'gen-' + routeOpts.method + '-' + (routeOpts.httpPart || routeOpts.httpStatus) + '-' + sanitize(routeOpts.url) + '.js')
91
+ }
92
+
93
+ const app = fastify({
94
+ jsonShorthand: false,
95
+ schemaController: {
96
+ compilersFactory: {
97
+ buildValidator: StandaloneValidator({
98
+ readMode: true,
99
+ restoreFunction(routeOpts) { return require(generateFileName(routeOpts)) }
100
+ })
101
+ }
102
+ }
103
+ })
104
+
105
+ const routes = ${JSON.stringify(routes)}
106
+ routes.forEach(r => {
107
+ app.post(r.url, { schema: { body: r.schema } }, (req, reply) => reply.send({ ok: true }))
108
+ })
109
+ app.ready().then(() => {
110
+ process.send({ ms: performance.now() - start })
111
+ process.exit()
112
+ })
113
+ `
114
+ }
115
+
116
+ // ============================================================
117
+ // 3. ata compact standalone
118
+ // ============================================================
119
+ function ataStandaloneScript(routes, bundlePath) {
120
+ return `
121
+ 'use strict'
122
+ const start = performance.now()
123
+ const fastify = require('fastify')()
124
+ const fns = require('${bundlePath}')
125
+ const routes = ${JSON.stringify(routes)}
126
+ const map = new WeakMap()
127
+ routes.forEach((r, i) => map.set(r.schema, fns[i]))
128
+ fastify.setValidatorCompiler(({ schema }) => {
129
+ const fn = map.get(schema)
130
+ return (data) => {
131
+ const r = fn(data)
132
+ if (r.valid) return { value: data }
133
+ const e = new Error(r.errors.map(e => e.message).join(', '))
134
+ e.statusCode = 400
135
+ e.validation = r.errors
136
+ return { error: e }
137
+ }
138
+ })
139
+ routes.forEach(r => {
140
+ fastify.post(r.url, { schema: { body: r.schema } }, (req, reply) => reply.send({ ok: true }))
141
+ })
142
+ fastify.ready().then(() => {
143
+ process.send({ ms: performance.now() - start })
144
+ process.exit()
145
+ })
146
+ `
147
+ }
148
+
149
+ async function runScript(script, timeout = 15000) {
150
+ const f = path.join(__dirname, '_bench_tmp.js')
151
+ writeFileSync(f, script)
152
+ const ms = await new Promise((resolve) => {
153
+ const c = fork(f, { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] })
154
+ c.on('message', m => resolve(m.ms || m.done ? m.ms : -1))
155
+ setTimeout(() => { c.kill(); resolve(-1) }, timeout)
156
+ })
157
+ try { unlinkSync(f) } catch {}
158
+ return ms
159
+ }
160
+
161
+ async function main() {
162
+ // Install sanitize-filename if needed
163
+ try { require('sanitize-filename') } catch {
164
+ require('child_process').execSync('npm install sanitize-filename', { cwd: __dirname, stdio: 'pipe' })
165
+ }
166
+
167
+ console.log('\n=======================================================')
168
+ console.log(' Fastify Startup: ajv default vs ajv standalone vs ata')
169
+ console.log(' Measures: process start → app.ready()')
170
+ console.log(' Blog post: backend.cafe/how-to-unlock-the-fastest-fastify-server-startup')
171
+ console.log('=======================================================\n')
172
+
173
+ for (const n of [50, 100, 200, 500]) {
174
+ const routes = makeRoutes(n)
175
+ console.log(`--- ${n} routes (5 schema types) ---`)
176
+
177
+ // 1. ajv default
178
+ const times1 = []
179
+ for (let r = 0; r < 3; r++) times1.push(await runScript(ajvDefaultScript(routes)))
180
+ times1.sort((a, b) => a - b)
181
+ const ajvDefault = times1[1]
182
+
183
+ // 2. ajv standalone — build phase
184
+ const ajvDir = path.resolve(__dirname, '_ajv_standalone')
185
+ mkdirSync(ajvDir, { recursive: true })
186
+ await runScript(ajvStandaloneBuildScript(routes, ajvDir), 30000)
187
+
188
+ // 2b. ajv standalone — read phase (benchmark this)
189
+ const times2 = []
190
+ for (let r = 0; r < 3; r++) times2.push(await runScript(ajvStandaloneReadScript(routes, ajvDir)))
191
+ times2.sort((a, b) => a - b)
192
+ const ajvStandalone = times2[1]
193
+ try { rmSync(ajvDir, { recursive: true }) } catch {}
194
+
195
+ // 3. ata compact standalone — build phase
196
+ const { Validator } = require('ata-validator')
197
+ const schemas = routes.map(r => r.schema)
198
+ const bundlePath = path.resolve(__dirname, '_ata_bundle.js')
199
+ writeFileSync(bundlePath, Validator.bundleCompact(schemas))
200
+
201
+ // 3b. ata standalone — read phase (benchmark this)
202
+ const times3 = []
203
+ for (let r = 0; r < 3; r++) times3.push(await runScript(ataStandaloneScript(routes, bundlePath)))
204
+ times3.sort((a, b) => a - b)
205
+ const ataStandalone = times3[1]
206
+ try { unlinkSync(bundlePath) } catch {}
207
+
208
+ console.log(` ajv default: ${ajvDefault.toFixed(0)}ms`)
209
+ console.log(` ajv standalone: ${ajvStandalone >= 0 ? ajvStandalone.toFixed(0) + 'ms' : 'FAILED'}`)
210
+ console.log(` ata compact: ${ataStandalone.toFixed(0)}ms`)
211
+ if (ajvStandalone > 0) {
212
+ console.log(` ata vs ajv standalone: ${(ajvStandalone / ataStandalone).toFixed(1)}x faster`)
213
+ }
214
+ console.log(` ata vs ajv default: ${(ajvDefault / ataStandalone).toFixed(1)}x faster`)
215
+ console.log()
216
+ }
217
+ }
218
+
219
+ main().catch(console.error)
@@ -0,0 +1,168 @@
1
+ 'use strict'
2
+
3
+ const { execSync } = require('child_process')
4
+ const { writeFileSync, unlinkSync, mkdirSync, rmSync } = require('fs')
5
+ const path = require('path')
6
+
7
+ // Generate N route schemas
8
+ function makeSchemas(n) {
9
+ const schemas = []
10
+ for (let i = 0; i < n; i++) {
11
+ schemas.push({
12
+ type: 'object',
13
+ properties: {
14
+ id: { type: 'integer', minimum: 1 },
15
+ name: { type: 'string', minLength: 1 },
16
+ email: { type: 'string', format: 'email' },
17
+ active: { type: 'boolean' },
18
+ [`field_${i}`]: { type: 'string' },
19
+ },
20
+ required: ['id', 'name', 'email', 'active'],
21
+ })
22
+ }
23
+ return schemas
24
+ }
25
+
26
+ function serverScript(mode, n) {
27
+ const schemas = makeSchemas(n)
28
+
29
+ if (mode === 'ajv-normal') {
30
+ return `
31
+ 'use strict'
32
+ const start = performance.now()
33
+ const fastify = require('fastify')()
34
+ const schemas = ${JSON.stringify(schemas)}
35
+ schemas.forEach((s, i) => {
36
+ fastify.post('/route' + i, { schema: { body: s } }, (req, reply) => reply.send({ ok: true }))
37
+ })
38
+ fastify.ready().then(() => {
39
+ const ms = performance.now() - start
40
+ process.send({ ms })
41
+ process.exit()
42
+ })
43
+ `
44
+ }
45
+
46
+ if (mode === 'ata-normal') {
47
+ return `
48
+ 'use strict'
49
+ const start = performance.now()
50
+ const fastify = require('fastify')()
51
+ fastify.register(require('./index'))
52
+ const schemas = ${JSON.stringify(schemas)}
53
+ schemas.forEach((s, i) => {
54
+ fastify.post('/route' + i, { schema: { body: s } }, (req, reply) => reply.send({ ok: true }))
55
+ })
56
+ fastify.ready().then(() => {
57
+ const ms = performance.now() - start
58
+ process.send({ ms })
59
+ process.exit()
60
+ })
61
+ `
62
+ }
63
+
64
+ if (mode === 'ata-standalone') {
65
+ return `
66
+ 'use strict'
67
+ const start = performance.now()
68
+ const fastify = require('fastify')()
69
+ const { Validator } = require('ata-validator')
70
+ const schemas = ${JSON.stringify(schemas)}
71
+ const cache = new WeakMap()
72
+ fastify.setValidatorCompiler(({ schema }) => {
73
+ let v = cache.get(schema)
74
+ if (!v) {
75
+ const idx = schemas.indexOf(schema)
76
+ if (idx >= 0) {
77
+ try {
78
+ const mod = require('./standalone/s' + idx + '.js')
79
+ v = Validator.fromStandalone(mod, schema)
80
+ } catch {
81
+ v = new Validator(schema)
82
+ }
83
+ } else {
84
+ v = new Validator(schema)
85
+ }
86
+ cache.set(schema, v)
87
+ }
88
+ return (data) => {
89
+ const r = v.validate(data)
90
+ if (r.valid) return { value: data }
91
+ const err = new Error(r.errors.map(e => e.message).join(', '))
92
+ err.statusCode = 400
93
+ err.validation = r.errors.map(e => ({ message: e.message, instancePath: e.path || '' }))
94
+ return { error: err }
95
+ }
96
+ })
97
+ schemas.forEach((s, i) => {
98
+ fastify.post('/route' + i, { schema: { body: s } }, (req, reply) => reply.send({ ok: true }))
99
+ })
100
+ fastify.ready().then(() => {
101
+ const ms = performance.now() - start
102
+ process.send({ ms })
103
+ process.exit()
104
+ })
105
+ `
106
+ }
107
+ }
108
+
109
+ async function bench(label, mode, n) {
110
+ const scriptPath = path.join(__dirname, '_startup_server.js')
111
+ writeFileSync(scriptPath, serverScript(mode, n))
112
+
113
+ // Pre-build standalone files if needed
114
+ if (mode === 'ata-standalone') {
115
+ const { Validator } = require('ata-validator')
116
+ const schemas = makeSchemas(n)
117
+ const dir = path.join(__dirname, 'standalone')
118
+ mkdirSync(dir, { recursive: true })
119
+ schemas.forEach((s, i) => {
120
+ const v = new Validator(s)
121
+ const src = v.toStandalone()
122
+ if (src) writeFileSync(path.join(dir, `s${i}.js`), src)
123
+ })
124
+ }
125
+
126
+ const runs = 5
127
+ const times = []
128
+ for (let r = 0; r < runs; r++) {
129
+ const { fork } = require('child_process')
130
+ const ms = await new Promise((resolve, reject) => {
131
+ const child = fork(scriptPath, { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] })
132
+ child.on('message', (msg) => resolve(msg.ms))
133
+ child.on('error', reject)
134
+ setTimeout(() => { child.kill(); reject(new Error('timeout')); }, 10000)
135
+ })
136
+ times.push(ms)
137
+ }
138
+
139
+ try { unlinkSync(path.join(__dirname, '_startup_server.js')) } catch {}
140
+
141
+ times.sort((a, b) => a - b)
142
+ const median = times[Math.floor(times.length / 2)]
143
+ console.log(` ${label.padEnd(30)} ${median.toFixed(1)}ms (median of ${runs})`)
144
+ return median
145
+ }
146
+
147
+ async function main() {
148
+ console.log('\n==============================================')
149
+ console.log(' Fastify Startup Benchmark')
150
+ console.log(' Time from process start to app.ready()')
151
+ console.log('==============================================\n')
152
+
153
+ for (const n of [10, 50, 100]) {
154
+ console.log(`--- ${n} routes ---`)
155
+ const ajv = await bench('fastify + ajv (default)', 'ajv-normal', n)
156
+ const ata = await bench('fastify + ata (normal)', 'ata-normal', n)
157
+ const standalone = await bench('fastify + ata (standalone)', 'ata-standalone', n)
158
+ console.log(` ajv default: ${ajv.toFixed(1)}ms`)
159
+ console.log(` ata normal: ${ata.toFixed(1)}ms (${(ajv/ata).toFixed(1)}x vs ajv)`)
160
+ console.log(` ata standalone: ${standalone.toFixed(1)}ms (${(ajv/standalone).toFixed(1)}x vs ajv)`)
161
+ console.log()
162
+ }
163
+
164
+ // Cleanup
165
+ try { rmSync(path.join(__dirname, 'standalone'), { recursive: true }) } catch {}
166
+ }
167
+
168
+ main().catch(console.error)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fastify-ata",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "Fastify plugin for ata-validator — beats ajv on every valid-path benchmark. 2.7x faster validate(obj), 151x faster compilation, simdjson + multi-core.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -26,8 +26,9 @@
26
26
  },
27
27
  "homepage": "https://github.com/ata-core/fastify-ata#readme",
28
28
  "dependencies": {
29
- "ata-validator": "^0.4.7",
30
- "fastify-plugin": "^5.1.0"
29
+ "ata-validator": "^0.4.9",
30
+ "fastify-plugin": "^5.1.0",
31
+ "sanitize-filename": "^1.6.4"
31
32
  },
32
33
  "peerDependencies": {
33
34
  "fastify": ">=4.0.0"