@2kog/kacha 0.1.1 → 0.2.0

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.
@@ -0,0 +1,288 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ const directory = '__kacha_sync__'
4
+ const hashPattern = /^[a-f0-9]{64}$/
5
+ const idPattern = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/
6
+ const metadataLimit = 64 * 1024 * 1024
7
+ const multipartThreshold = 32 * 1024 * 1024
8
+ const digest = data => createHash('sha256').update(data).digest('hex')
9
+
10
+ function errorFor(code) {
11
+ return Object.assign(new Error(code), { code })
12
+ }
13
+
14
+ function invalid() {
15
+ return errorFor('OSS_COLLAB_REMOTE_INVALID')
16
+ }
17
+
18
+ function validString(value, pattern) {
19
+ return typeof value === 'string' && pattern.test(value)
20
+ }
21
+
22
+ function isMissing(error) {
23
+ return error?.code === 'NoSuchKey' || (error?.status === 404 && error.code !== 'NoSuchBucket')
24
+ }
25
+
26
+ function checkStopped(signal) {
27
+ if (signal?.aborted) throw errorFor('OSS_SYNC_STOPPED')
28
+ }
29
+
30
+ export function isProjectFile(file) {
31
+ if (typeof file !== 'string' || /[\\:\x00-\x1f\x7f]/.test(file)) return false
32
+ return file.toLowerCase() !== 'config/oss-sync.json' && file.split('/').every(part => {
33
+ const name = part.toLowerCase()
34
+ return name.trimEnd() === name && name && !name.endsWith('.') &&
35
+ !['.git', '.kacha', '.env', 'node_modules', directory].includes(name) && !name.startsWith('.env.')
36
+ })
37
+ }
38
+
39
+ export function assertPortablePaths(paths) {
40
+ const files = new Set(paths)
41
+ // A project can move to a case-insensitive or Unicode-normalizing filesystem.
42
+ const pathSpellings = new Map()
43
+ for (const file of files) {
44
+ let end = file.indexOf('/')
45
+ while (true) {
46
+ const part = end < 0 ? file : file.slice(0, end)
47
+ const canonical = part.toUpperCase().toLowerCase().normalize('NFC')
48
+ const spelling = pathSpellings.get(canonical)
49
+ if ((spelling && spelling !== part) || (end >= 0 && files.has(part))) throw invalid()
50
+ pathSpellings.set(canonical, part)
51
+ if (end < 0) break
52
+ end = file.indexOf('/', end + 1)
53
+ }
54
+ }
55
+ }
56
+
57
+ export function validateManifest(value) {
58
+ if (!value || !validString(value.projectId, idPattern) || !validString(value.revision, idPattern) ||
59
+ (value.parent !== null && !validString(value.parent, idPattern)) || value.parent === value.revision ||
60
+ typeof value.createdAt !== 'string' || !Number.isFinite(Date.parse(value.createdAt)) ||
61
+ !value.files || typeof value.files !== 'object' || Array.isArray(value.files)) throw invalid()
62
+
63
+ const files = Object.create(null)
64
+ const sizes = new Map()
65
+ for (const [file, item] of Object.entries(value.files)) {
66
+ if (!isProjectFile(file) || !item || !validString(item.hash, hashPattern) ||
67
+ !Number.isSafeInteger(item.size) || item.size < 0) throw invalid()
68
+ if (sizes.has(item.hash) && sizes.get(item.hash) !== item.size) throw invalid()
69
+ sizes.set(item.hash, item.size)
70
+ files[file] = { hash: item.hash, size: item.size }
71
+ }
72
+
73
+ assertPortablePaths(Object.keys(files))
74
+ const { projectId, revision, parent, createdAt } = value
75
+ return { projectId, revision, parent, createdAt, files }
76
+ }
77
+
78
+ export function createRemoteStore(client, destination) {
79
+ const prefix = (destination.prefix || '').replace(/^\/+|\/+$/g, '')
80
+ const relativeKey = path => prefix ? prefix + '/' + path : path
81
+ const managedKey = key => relativeKey(directory + '/' + key)
82
+ const logKey = managedKey('published.jsonl')
83
+ const blobKey = hash => {
84
+ if (!validString(hash, hashPattern)) throw invalid()
85
+ return managedKey('blobs/' + hash)
86
+ }
87
+ const manifestKey = ({ revision, hash }) => managedKey('versions/' + revision + '/' + hash + '.json')
88
+
89
+ async function readMetadata(key) {
90
+ try {
91
+ const { stream } = await client.getStream(key, { headers: { 'Accept-Encoding': 'identity' } })
92
+ const chunks = []
93
+ let bytes = 0
94
+ try {
95
+ for await (const chunk of stream) {
96
+ const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
97
+ bytes += data.length
98
+ if (bytes > metadataLimit) throw invalid()
99
+ chunks.push(data)
100
+ }
101
+ } finally {
102
+ stream.destroy()
103
+ }
104
+ return Buffer.concat(chunks, bytes)
105
+ } catch (error) {
106
+ if (isMissing(error)) return null
107
+ if (error?.code === 'OSS_COLLAB_REMOTE_INVALID') throw error
108
+ throw errorFor('OSS_COLLAB_REMOTE_IO')
109
+ }
110
+ }
111
+
112
+ async function readLog() {
113
+ const data = await readMetadata(logKey)
114
+ if (!data) return { position: 0, records: [] }
115
+
116
+ try {
117
+ const rows = data.toString('utf8').split('\n')
118
+ if (rows.pop() !== '') throw invalid()
119
+ const revisions = new Set()
120
+ const records = []
121
+ for (const line of rows) {
122
+ const item = JSON.parse(line)
123
+ const previous = records.at(-1)
124
+ if (!item || item.version !== 1 || !validString(item.projectId, idPattern) ||
125
+ !validString(item.revision, idPattern) || !validString(item.hash, hashPattern) ||
126
+ item.parent !== (previous?.revision || null) || (previous && item.projectId !== previous.projectId) ||
127
+ revisions.has(item.revision)) throw invalid()
128
+ records.push(item)
129
+ revisions.add(item.revision)
130
+ }
131
+ if (!records.length) throw invalid()
132
+ return { position: data.length, records }
133
+ } catch {
134
+ throw invalid()
135
+ }
136
+ }
137
+
138
+ async function readHead() {
139
+ const { position, records } = await readLog()
140
+ const latest = records.at(-1)
141
+ if (!latest) return { position, manifest: null }
142
+ const bytes = await readMetadata(manifestKey(latest))
143
+ if (!bytes || digest(bytes) !== latest.hash) throw invalid()
144
+ try {
145
+ const manifest = validateManifest(JSON.parse(bytes))
146
+ if (manifest.revision !== latest.revision || manifest.projectId !== latest.projectId || manifest.parent !== latest.parent) {
147
+ throw invalid()
148
+ }
149
+ return { position, manifest }
150
+ } catch {
151
+ throw invalid()
152
+ }
153
+ }
154
+
155
+ async function publish(input, expectedHead) {
156
+ const manifest = validateManifest(input)
157
+ const { projectId, revision, parent } = manifest
158
+ if (!Number.isSafeInteger(expectedHead?.position) || expectedHead.position < 0 ||
159
+ ((expectedHead.position === 0) !== !expectedHead.manifest) ||
160
+ (expectedHead.manifest && expectedHead.manifest.projectId !== projectId) ||
161
+ parent !== (expectedHead.manifest?.revision || null)) throw invalid()
162
+ const payload = Buffer.from(JSON.stringify(manifest) + '\n')
163
+ if (payload.length > metadataLimit) throw invalid()
164
+ const record = { version: 1, projectId, revision, parent, hash: digest(payload) }
165
+ const entry = Buffer.from(JSON.stringify(record) + '\n')
166
+ const nextPosition = expectedHead.position + entry.length
167
+ if (nextPosition > metadataLimit) throw invalid()
168
+
169
+ try {
170
+ // This key identifies the exact bytes. Concurrent retries can only put the same payload.
171
+ await client.put(manifestKey(record), payload, { mime: 'application/json' })
172
+ await client.append(logKey, entry, { position: expectedHead.position, mime: 'application/x-ndjson' })
173
+ return { position: nextPosition, manifest }
174
+ } catch (error) {
175
+ // A transport error can arrive after successful append. The log decides whether to retry.
176
+ let latest
177
+ try {
178
+ latest = await readLog()
179
+ } catch (readError) {
180
+ if (readError?.code === 'OSS_COLLAB_REMOTE_INVALID') throw readError
181
+ if (error?.code === 'PositionNotEqualToLength') throw errorFor('OSS_COLLAB_REMOTE_CHANGED')
182
+ throw errorFor('OSS_COLLAB_REMOTE_IO')
183
+ }
184
+ const published = latest.records.find(item => item.revision === revision)
185
+ if (published?.hash === record.hash) return { position: latest.position, manifest }
186
+ if (error?.code === 'ObjectNotAppendable') throw invalid()
187
+ if (published || latest.position !== expectedHead.position || error?.code === 'PositionNotEqualToLength') {
188
+ throw errorFor('OSS_COLLAB_REMOTE_CHANGED')
189
+ }
190
+ throw errorFor('OSS_COLLAB_REMOTE_IO')
191
+ }
192
+ }
193
+
194
+ async function getBlob(hash) {
195
+ const key = blobKey(hash)
196
+ return (await client.getStream(key, { headers: { 'Accept-Encoding': 'identity' } })).stream
197
+ }
198
+
199
+ async function hasBlob(hash) {
200
+ const key = blobKey(hash)
201
+ try {
202
+ await client.head(key)
203
+ return true
204
+ } catch (error) {
205
+ if (isMissing(error)) return false
206
+ throw error
207
+ }
208
+ }
209
+
210
+ function putBlob(hash, file, { multipart = false, size = 0, checkpoint, ...options } = {}) {
211
+ const key = blobKey(hash)
212
+ if (checkpoint || multipart || size >= multipartThreshold) {
213
+ return client.multipartUpload(key, file, { ...options, checkpoint })
214
+ }
215
+ return client.put(key, file, options)
216
+ }
217
+
218
+ async function listLegacy() {
219
+ const directoryPrefix = prefix && prefix + '/'
220
+ const matched = new Map()
221
+ const tokens = new Set()
222
+ let token
223
+ try {
224
+ do {
225
+ const page = await client.listV2({ prefix: directoryPrefix, 'max-keys': 1000, continuationToken: token })
226
+ for (const item of page.objects || []) {
227
+ if (typeof item.name !== 'string' || !item.name.startsWith(directoryPrefix)) continue
228
+ const file = item.name.slice(directoryPrefix.length)
229
+ if (isProjectFile(file) && Number.isSafeInteger(item.size) && item.size >= 0) {
230
+ matched.set(file, { size: item.size, etag: item.etag })
231
+ }
232
+ }
233
+ if (!page.isTruncated) return matched
234
+ token = page.nextContinuationToken
235
+ if (typeof token !== 'string' || !token || tokens.has(token)) throw invalid()
236
+ tokens.add(token)
237
+ } while (true)
238
+ } catch (error) {
239
+ if (error?.code === 'OSS_COLLAB_REMOTE_INVALID') throw error
240
+ throw errorFor('OSS_COLLAB_REMOTE_IO')
241
+ }
242
+ }
243
+
244
+ async function reuseLegacy(file, hash, size, signal) {
245
+ if (!isProjectFile(file)) throw invalid()
246
+ const key = blobKey(hash)
247
+ const source = relativeKey(file)
248
+ let stream
249
+ const stop = () => stream?.destroy(errorFor('OSS_SYNC_STOPPED'))
250
+ try {
251
+ checkStopped(signal)
252
+ const result = await client.getStream(source, { headers: { 'Accept-Encoding': 'identity' } })
253
+ stream = result.stream
254
+ const etag = result.res?.headers?.etag
255
+ const length = result.res?.headers?.['content-length']
256
+ checkStopped(signal)
257
+ if (!validString(etag, /^"?[a-z0-9-]+"?$/i) || (length !== undefined && Number(length) !== size)) return false
258
+
259
+ const check = createHash('sha256')
260
+ let actualSize = 0
261
+ signal?.addEventListener('abort', stop, { once: true })
262
+ for await (const chunk of stream) {
263
+ checkStopped(signal)
264
+ actualSize += chunk.length
265
+ if (actualSize > size) return false
266
+ check.update(chunk)
267
+ }
268
+ checkStopped(signal)
269
+ if (actualSize !== size || check.digest('hex') !== hash) return false
270
+
271
+ // The source can be overwritten by older clients. Tie the copy to what was just verified.
272
+ const copied = await client.copy(key, source, destination.bucket, { headers: { 'if-match': etag } })
273
+ return copied.res?.status === 200
274
+ } catch (error) {
275
+ checkStopped(signal)
276
+ if (isMissing(error) || [403, 412, 501].includes(error?.status)) return false
277
+ throw errorFor('OSS_COLLAB_REMOTE_IO')
278
+ } finally {
279
+ signal?.removeEventListener('abort', stop)
280
+ stream?.destroy()
281
+ }
282
+ }
283
+
284
+ return {
285
+ id: digest(JSON.stringify([destination.endpoint, destination.bucket, prefix])),
286
+ readHead, publish, blobKey, getBlob, hasBlob, putBlob, listLegacy, reuseLegacy,
287
+ }
288
+ }