-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmodel-source-sync.ts
More file actions
198 lines (179 loc) · 5.79 KB
/
Copy pathmodel-source-sync.ts
File metadata and controls
198 lines (179 loc) · 5.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import { createHash } from 'node:crypto'
import fs from 'node:fs/promises'
import path from 'node:path'
import type { ManifestSource } from '../../../src/types/manifests'
interface ModelManifest {
id: string
sources?: ManifestSource[]
}
interface TextResponse {
ok: boolean
status: number
statusText: string
text(): Promise<string>
}
export type SourceFetch = (
input: string | URL,
init?: { headers?: Record<string, string> }
) => Promise<TextResponse>
interface TrackedSource {
modelId: string
filePath: string
source: ManifestSource & {
changeTracking: NonNullable<ManifestSource['changeTracking']>
}
}
export interface ModelSourceChange {
modelId: string
filePath: string
url: string
fields: string[]
previousDigest: string | null
nextDigest: string
observedAt: string
}
export interface ModelSourceSyncResult {
checked: number
changes: ModelSourceChange[]
}
function escapeRegularExpression(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
function decodeCommonEntities(value: string): string {
return value
.replaceAll(' ', ' ')
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll(''', "'")
}
export function normalizeSourceContent(value: string): string {
return decodeCommonEntities(
value
.replace(/<!--[\s\S]*?-->/g, ' ')
.replace(/<(script|style|noscript|svg)\b[\s\S]*?<\/\1>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
)
.replace(/\s+/g, ' ')
.trim()
}
export function digestSourceContent(value: string): string {
return `sha256:${createHash('sha256').update(normalizeSourceContent(value)).digest('hex')}`
}
async function loadTrackedSources(rootDir: string): Promise<TrackedSource[]> {
const directory = path.join(rootDir, 'manifests', 'models')
const tracked: TrackedSource[] = []
for (const fileName of (await fs.readdir(directory))
.filter(file => file.endsWith('.json'))
.sort()) {
const filePath = path.join(directory, fileName)
const manifest = JSON.parse(await fs.readFile(filePath, 'utf8')) as ModelManifest
for (const source of manifest.sources ?? []) {
if (source.changeTracking) {
tracked.push({
modelId: manifest.id,
filePath,
source: {
...source,
changeTracking: source.changeTracking,
},
})
}
}
}
return tracked
}
async function fetchDigest(url: string, fetchImpl: SourceFetch): Promise<string> {
const response = await fetchImpl(url, {
headers: {
Accept: 'text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.1',
'Accept-Language': 'en-US,en;q=0.9',
'User-Agent': 'aicodingstack-model-source-monitor',
},
})
if (!response.ok) {
throw new Error(`${url} returned ${response.status} ${response.statusText}`)
}
const content = await response.text()
const normalized = normalizeSourceContent(content)
if (normalized.length < 100) {
throw new Error(`${url} returned too little usable content`)
}
return digestSourceContent(content)
}
function replaceTrackedSource(source: string, change: ModelSourceChange): string {
const url = escapeRegularExpression(JSON.stringify(change.url))
const previousDigest = escapeRegularExpression(JSON.stringify(change.previousDigest))
const trackingPattern = new RegExp(
`("url"\\s*:\\s*${url}[\\s\\S]*?"changeTracking"\\s*:\\s*\\{[\\s\\S]*?"digest"\\s*:\\s*)${previousDigest}([\\s\\S]*?"observedAt"\\s*:\\s*)(?:"[^"]*"|null)`,
'g'
)
const matches = [...source.matchAll(trackingPattern)]
if (matches.length !== 1) {
throw new Error(
`models/${change.modelId} must contain exactly one matching tracked source ${change.url}`
)
}
return source.replace(
trackingPattern,
`$1${JSON.stringify(change.nextDigest)}$2${JSON.stringify(change.observedAt)}`
)
}
export async function syncModelSourceDigests(options: {
rootDir: string
write: boolean
observedAt: string
fetchImpl?: SourceFetch
}): Promise<ModelSourceSyncResult> {
const tracked = await loadTrackedSources(options.rootDir)
const fetchImpl = options.fetchImpl ?? (fetch as SourceFetch)
const digestByUrl = new Map<string, Promise<string>>()
for (const entry of tracked) {
if (!digestByUrl.has(entry.source.url)) {
digestByUrl.set(entry.source.url, fetchDigest(entry.source.url, fetchImpl))
}
}
const observations = await Promise.allSettled(
tracked.map(async entry => ({
entry,
digest: await digestByUrl.get(entry.source.url),
}))
)
const failures = observations.flatMap((result, index) =>
result.status === 'rejected'
? [`models/${tracked[index]?.modelId}: ${String(result.reason)}`]
: []
)
if (failures.length > 0) {
throw new Error(
`Model source monitoring failed without writing changes:\n${failures.join('\n')}`
)
}
const changes: ModelSourceChange[] = []
for (const result of observations) {
if (result.status !== 'fulfilled') continue
const { entry, digest } = result.value
if (!digest || digest === entry.source.changeTracking.digest) continue
changes.push({
modelId: entry.modelId,
filePath: entry.filePath,
url: entry.source.url,
fields: entry.source.fields ?? [],
previousDigest: entry.source.changeTracking.digest,
nextDigest: digest,
observedAt: options.observedAt,
})
}
if (options.write) {
const changesByFile = Map.groupBy(changes, change => change.filePath)
for (const [filePath, fileChanges] of changesByFile) {
let source = await fs.readFile(filePath, 'utf8')
for (const change of fileChanges) {
source = replaceTrackedSource(source, change)
}
await fs.writeFile(filePath, source, 'utf8')
}
}
return { checked: tracked.length, changes }
}