-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathhash-fns.ts
More file actions
237 lines (216 loc) · 6.47 KB
/
hash-fns.ts
File metadata and controls
237 lines (216 loc) · 6.47 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { readFile } from 'fs/promises'
import path from 'path'
import { pipeline } from 'stream/promises'
import { Readable } from 'stream'
import { zipFunctions, type FunctionResult, type TrafficRules } from '@netlify/zip-it-and-ship-it'
import BaseCommand from '../../commands/base-command.js'
import { $TSFixMe } from '../../commands/types.js'
import { INTERNAL_FUNCTIONS_FOLDER } from '../functions/functions.js'
import { hasherCtor, manifestCollectorCtor } from './hasher-segments.js'
// Maximum age of functions manifest (2 minutes).
const MANIFEST_FILE_TTL = 12e4
const getFunctionZips = async ({
command,
directories,
functionsConfig,
manifestPath,
rootDir,
skipFunctionsCache,
statusCb,
tmpDir,
}: {
command: BaseCommand
directories: string[]
functionsConfig?: $TSFixMe
manifestPath: $TSFixMe
rootDir: $TSFixMe
skipFunctionsCache?: boolean | undefined
statusCb: $TSFixMe
tmpDir: $TSFixMe
}): Promise<(FunctionResult & { buildData?: unknown })[]> => {
statusCb({
type: 'functions-manifest',
msg: 'Looking for a functions cache...',
phase: 'start',
})
if (manifestPath) {
try {
// read manifest.json file
// @ts-expect-error TS(2345) FIXME: Argument of type 'Buffer' is not assignable to par... Remove this comment to see the full error message
const { functions, timestamp } = JSON.parse(await readFile(manifestPath))
const manifestAge = Date.now() - timestamp
if (manifestAge > MANIFEST_FILE_TTL) {
throw new Error('Manifest expired')
}
statusCb({
type: 'functions-manifest',
msg: 'Deploying functions from cache (use --skip-functions-cache to override)',
phase: 'stop',
})
return functions
} catch {
statusCb({
type: 'functions-manifest',
msg: 'Ignored invalid or expired functions cache',
phase: 'stop',
})
}
} else {
const msg = skipFunctionsCache
? 'Ignoring functions cache (use without --skip-functions-cache to change)'
: 'No cached functions were found'
statusCb({
type: 'functions-manifest',
msg,
phase: 'stop',
})
}
return await zipFunctions(directories, tmpDir, {
basePath: rootDir,
configFileDirectories: [command.getPathInProject(INTERNAL_FUNCTIONS_FOLDER)],
config: functionsConfig,
})
}
const trafficRulesConfig = (trafficRules?: TrafficRules) => {
if (!trafficRules) {
return
}
return {
action: {
type: trafficRules?.action?.type,
config: {
rate_limit_config: {
algorithm: trafficRules?.action?.config?.rateLimitConfig?.algorithm,
window_size: trafficRules?.action?.config?.rateLimitConfig?.windowSize,
window_limit: trafficRules?.action?.config?.rateLimitConfig?.windowLimit,
},
aggregate: trafficRules?.action?.config?.aggregate,
to: trafficRules?.action?.config?.to,
},
},
}
}
const hashFns = async (
command: BaseCommand,
directories: string[],
{
concurrentHash,
functionsConfig,
hashAlgorithm = 'sha256',
manifestPath,
rootDir,
skipFunctionsCache,
statusCb,
tmpDir,
}: {
concurrentHash?: number
functionsConfig?: $TSFixMe
hashAlgorithm?: string | undefined
manifestPath?: string | undefined
rootDir?: string | undefined
skipFunctionsCache?: boolean | undefined
statusCb: $TSFixMe
tmpDir: $TSFixMe
},
): Promise<{
functionSchedules?: { name: string; cron: string }[] | undefined
functions: Record<string, string>
functionsWithNativeModules: $TSFixMe[]
shaMap?: Record<string, $TSFixMe> | undefined
fnShaMap?: Record<string, $TSFixMe[]> | undefined
fnConfig?: Record<string, $TSFixMe> | undefined
}> => {
// Exit early if no functions directories are configured.
if (directories.length === 0) {
return { functions: {}, functionsWithNativeModules: [], shaMap: {} }
}
if (!tmpDir) {
throw new Error('Missing tmpDir directory for zipping files')
}
const functionZips = await getFunctionZips({
command,
directories,
functionsConfig,
manifestPath,
rootDir,
skipFunctionsCache,
statusCb,
tmpDir,
})
const fileObjs = functionZips.map(
({
buildData,
displayName,
generator,
invocationMode,
path: functionPath,
priority,
runtime,
runtimeVersion,
timeout,
trafficRules,
}) => ({
filepath: functionPath,
root: tmpDir,
relname: path.relative(tmpDir, functionPath),
basename: path.basename(functionPath),
extname: path.extname(functionPath),
type: 'file',
assetType: 'function',
normalizedPath: path.basename(functionPath, path.extname(functionPath)),
runtime: runtimeVersion ?? runtime,
displayName,
generator,
invocationMode,
timeout,
buildData,
priority,
trafficRules,
}),
)
const fnConfig = functionZips
.filter((func) =>
Boolean(
func.displayName ||
func.generator ||
func.routes ||
func.buildData ||
func.priority ||
func.trafficRules ||
func.eventSubscriptions,
),
)
.reduce(
(funcs, curr) => ({
...funcs,
[curr.name]: {
display_name: curr.displayName,
excluded_routes: curr.excludedRoutes,
generator: curr.generator,
routes: curr.routes,
build_data: curr.buildData,
priority: curr.priority,
traffic_rules: trafficRulesConfig(curr.trafficRules),
event_subscriptions: curr.eventSubscriptions,
},
}),
{},
)
const functionSchedules = functionZips
.map(({ name, schedule }) => schedule && { name, cron: schedule })
.filter((schedule) => schedule !== '' && schedule !== undefined)
const functionsWithNativeModules = functionZips.filter(
({ nativeNodeModules }) => nativeNodeModules !== undefined && Object.keys(nativeNodeModules).length !== 0,
)
const functionStream = Readable.from(fileObjs)
const hasher = hasherCtor({ concurrentHash, hashAlgorithm })
// Written to by manifestCollector
// normalizedPath: hash (wanted by deploy API)
const functions = {}
// hash: [fileObj, fileObj, fileObj]
const fnShaMap = {}
const manifestCollector = manifestCollectorCtor(functions, fnShaMap, { statusCb })
await pipeline([functionStream, hasher, manifestCollector])
return { functionSchedules, functions, functionsWithNativeModules, fnShaMap, fnConfig }
}
export default hashFns