Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

release-http-registry.js

236 lines7.9 KB

1/** Loopback HTTP production receiver. It supplies registry facts, not tag policy. */
2import assert from 'node:assert/strict'
3import { createHash } from 'node:crypto'
4import { readFileSync, renameSync, writeFileSync } from 'node:fs'
5import http from 'node:http'
6import { gunzipSync } from 'node:zlib'
7​
8const statePath = process.argv[2]
9const state = JSON.parse(readFileSync(statePath, 'utf8'))
10const requests = []
11let origin
12const save = () => {
13 writeFileSync(`${statePath}.next`, JSON.stringify({ ...state, requests }))
14 renameSync(`${statePath}.next`, statePath)
16​
17// Observe the packed manifest without extracting any filesystem path. Fixture
18// archives are small USTAR streams made by the real package manager.
19function packedManifest(attachment) {
20 const compressed = Buffer.from(attachment.data, 'base64')
21 assert.equal(compressed.length, attachment.length, 'attachment byte length')
22 const tar = gunzipSync(compressed, { maxOutputLength: 4 * 1024 * 1024 })
23 let manifest
24 let files = 0
25 for (let offset = 0; offset + 512 <= tar.length;) {
26 const header = tar.subarray(offset, offset + 512)
27 if (header.every((value) => value === 0)) break
28 const name = header.subarray(0, 100).toString().replace(/\0.*$/, '')
29 const size = Number.parseInt(
30 header.subarray(124, 136).toString().replace(/\0.*$/, '').trim(),
31 8,
32 )
33 assert(Number.isSafeInteger(size) && size >= 0, 'tar entry size')
34 const data = tar.subarray(offset + 512, offset + 512 + size)
35 assert.equal(data.length, size, 'complete tar entry')
36 files++
37 if (name === 'package/package.json') {
38 assert.equal(manifest, undefined, 'one packed manifest')
39 manifest = JSON.parse(data.toString())
40 }
41 offset += 512 + Math.ceil(size / 512) * 512
42 }
43 assert(manifest, 'packed package.json exists')
44 return {
45 manifest,
46 files,
47 shasum: createHash('sha1').update(compressed).digest('hex'),
48 }
50​
51const server = http.createServer((request, response) => {
52 const chunks = []
53 let size = 0
54 request.on('data', (chunk) => {
55 size += chunk.length
56 if (size > 4 * 1024 * 1024)
57 request.destroy(new Error('fixture request exceeds limit'))
58 else chunks.push(chunk)
59 })
60 request.on('end', () => {
61 const observed = {
62 method: request.method,
63 path: request.url,
64 registry: `http://${request.headers.host}`,
65 authenticated:
66 request.headers.authorization === 'Bearer release-http-fixture',
67 }
68 const reply = (status, value) => {
69 save()
70 response.writeHead(status, { 'content-type': 'application/json' })
71 response.end(JSON.stringify(value))
72 }
73 try {
74 const url = new URL(request.url, origin)
75 assert.equal(observed.registry, origin, 'loopback Host header')
76 assert.equal(url.origin, origin, 'loopback request target')
77 assert.equal(url.search, '', 'registry request has no unrecognized query')
78 if (
79 request.method === 'GET' &&
80 url.pathname === '/-/npm/v1/user/profile'
81 ) {
82 requests.push({ ...observed, type: 'profile' })
83 return reply(200, {
84 name: 'release-fixture',
85 tfa: { mode: 'auth-only' },
86 })
87 }
88 const name = decodeURIComponent(url.pathname.slice(1))
89 assert(Object.hasOwn(state.packages, name), 'known public package route')
90 const entry = state.packages[name]
91 if (request.method === 'GET') {
92 requests.push({
93 ...observed,
94 type: 'info',
95 name,
96 versions: [...entry.versions],
97 tags: { ...entry.tags },
98 })
99 if (entry.versions.length === 0)
100 return reply(404, { error: 'not_found' })
101 return reply(200, {
102 _id: name,
103 name,
104 'dist-tags': entry.tags,
105 versions: Object.fromEntries(
106 entry.versions.map((version) => [
107 version,
108 {
109 name,
110 version,
111 dist: {
112 tarball: `${origin}/${encodeURIComponent(name)}/-/fixture-${version}.tgz`,
113 },
114 },
115 ]),
116 ),
117 })
118 }
119 assert.equal(request.method, 'PUT', 'registry publish method')
120 assert.equal(
121 observed.authenticated,
122 true,
123 'isolated fixture authentication',
124 )
125 let body = Buffer.concat(chunks)
126 if (request.headers['content-encoding'] === 'gzip')
127 body = gunzipSync(body, { maxOutputLength: 4 * 1024 * 1024 })
128 else
129 assert.equal(
130 request.headers['content-encoding'],
131 undefined,
132 'known body encoding',
133 )
134 const document = JSON.parse(body.toString())
135 assert.equal(document.name, name, 'document matches route')
136 const versions = Object.keys(document.versions)
137 const tags = Object.entries(document['dist-tags'])
138 const attachments = Object.values(document._attachments)
139 assert.equal(versions.length, 1, 'one uploaded version')
140 assert.equal(tags.length, 1, 'one publication tag')
141 assert.equal(attachments.length, 1, 'one packed attachment')
142 const [version] = versions
143 const [[tag, taggedVersion]] = tags
144 assert.equal(taggedVersion, version, 'tag points to uploaded version')
145 const archive = packedManifest(attachments[0])
146 assert.equal(archive.manifest.name, name, 'packed name matches route')
147 assert.equal(
148 archive.manifest.version,
149 version,
150 'packed version matches document',
151 )
152 assert.equal(
153 document.versions[version].dist.shasum,
154 archive.shasum,
155 'packed digest matches document',
156 )
157 const duplicate = entry.versions.includes(version)
158 // Fail the next candidate only after an actual candidate upload succeeded.
159 // This observes arrival order and imposes no package scheduling strategy.
160 const priorCandidateSuccess = requests.some(
161 (request) =>
162 request.type === 'publish' &&
163 request.success &&
164 state.candidateNames?.includes(request.name),
165 )
166 const controlledFailure =
167 !state.failed &&
168 !duplicate &&
169 (name === state.failureName ||
170 (state.failureMode === 'candidate-after-success' &&
171 state.candidateNames.includes(name) &&
172 priorCandidateSuccess))
173 const success = !controlledFailure && !duplicate
174 requests.push({
175 ...observed,
176 type: 'publish',
177 name,
178 version,
179 tag,
180 access: document.access,
181 success,
182 controlledFailure,
183 duplicate,
184 archive: {
185 name: archive.manifest.name,
186 version: archive.manifest.version,
187 files: archive.files,
188 },
189 })
190 if (controlledFailure) {
191 state.failed = true
192 return reply(400, {
193 error: 'EORACLE',
194 reason: 'controlled publication failure',
195 })
196 }
197 if (duplicate)
198 return reply(409, {
199 error: 'EPUBLISHCONFLICT',
200 reason: 'version already exists',
201 })
202 entry.versions.push(version)
203 entry.tags[tag] = version
204 return reply(201, { ok: true, id: name, rev: 'fixture' })
205 } catch (error) {
206 requests.push({
207 ...observed,
208 type: 'protocol-error',
209 error: error.message,
210 })
211 return reply(422, { error: 'EORACLEPROTOCOL', reason: error.message })
212 }
213 })
214 request.on('error', (error) => {
215 requests.push({ type: 'request-error', error: error.message })
216 save()
217 })
218})
219server.on('error', (error) => {
220 process.send?.({ setupError: error.message, code: error.code })
221 process.exitCode = 1
222})
223server.listen(0, '127.0.0.1', () => {
224 origin = `http://127.0.0.1:${server.address().port}`
225 process.send?.({ origin })
226})
227process.on('message', (message) => {
228 if (message === 'close') {
229 server.close(() => process.exit(0))
230 server.closeAllConnections()
231 }
232})
233process.on('disconnect', () => {
234 server.close(() => process.exit(0))
235 server.closeAllConnections()
236})