Skip to content

Commit 6fa5126

Browse files
committed
feat: optmize code zip flow
1 parent fd0882e commit 6fa5126

File tree

4 files changed

+86
-82
lines changed

4 files changed

+86
-82
lines changed

src/_shims/handler.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ exports.handler = async (event, context) => {
1515
app = require('./sls.js')
1616
}
1717

18+
app.request.__SLS_EVENT__ = event
19+
app.request.__SLS_CONTEXT__ = context
20+
1821
// cache server, not create repeatly
1922
if (!server) {
2023
server = createServer(app.callback(), null, app.binaryTypes || [])
@@ -23,5 +26,10 @@ exports.handler = async (event, context) => {
2326
context.callbackWaitsForEmptyEventLoop =
2427
app.callbackWaitsForEmptyEventLoop === true ? true : false
2528

26-
return proxy(server, event, context, 'PROMISE').promise
29+
if (app.slsInitialize && typeof app.slsInitialize === 'function') {
30+
await app.slsInitialize()
31+
}
32+
33+
const result = await proxy(server, event, context, 'PROMISE')
34+
return result.promise
2735
}

src/package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
"license": "MIT",
1313
"dependencies": {
1414
"download": "^8.0.0",
15-
"fs-extra": "^8.1.0",
16-
"tencent-component-toolkit": "^1.5.5",
15+
"tencent-component-toolkit": "^1.8.3",
1716
"type": "^2.0.0"
1817
}
1918
}

src/serverless.js

Lines changed: 6 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
const { Component } = require('@serverless/core')
2-
const { MultiApigw, Scf, Apigw, Cos, Cns } = require('tencent-component-toolkit')
3-
const { packageCode, getDefaultProtocol, deleteRecord, prepareInputs } = require('./utils')
2+
const { MultiApigw, Scf, Apigw, Cns } = require('tencent-component-toolkit')
3+
const { uploadCodeToCos, getDefaultProtocol, deleteRecord, prepareInputs } = require('./utils')
44
const CONFIGS = require('./config')
55

66
class ServerlessComponent extends Component {
@@ -20,62 +20,19 @@ class ServerlessComponent extends Component {
2020
}
2121
}
2222

23-
async uploadCodeToCos(credentials, inputs, region, filePath) {
24-
const { appId } = this.credentials.tencent.tmpSecrets
25-
// 创建cos对象
26-
const cos = new Cos(credentials, region)
27-
// 创建存储桶 + 设置生命周期
28-
if (!inputs.code.bucket) {
29-
inputs.code.bucket = `sls-cloudfunction-${region}-code`
30-
await cos.deploy({
31-
bucket: inputs.code.bucket + '-' + appId,
32-
force: true,
33-
lifecycle: [
34-
{
35-
status: 'Enabled',
36-
id: 'deleteObject',
37-
filter: '',
38-
expiration: { days: '10' },
39-
abortIncompleteMultipartUpload: { daysAfterInitiation: '10' }
40-
}
41-
]
42-
})
43-
}
44-
45-
// 上传代码
46-
if (!inputs.code.object) {
47-
const object = `${inputs.name}-${Math.floor(Date.now() / 1000)}.zip`
48-
inputs.code.object = object
49-
await cos.upload({
50-
bucket: inputs.code.bucket + '-' + appId,
51-
file: filePath,
52-
key: inputs.code.object
53-
})
54-
}
55-
this.state.bucket = inputs.code.bucket
56-
this.state.object = inputs.code.object
57-
58-
return {
59-
bucket: inputs.code.bucket,
60-
object: inputs.code.object
61-
}
23+
getAppId() {
24+
return this.credentials.tencent.tmpSecrets.appId
6225
}
6326

6427
async deployFunction(credentials, inputs, regionList) {
65-
// if set bucket and object not pack code
66-
let packageDir
67-
if (!inputs.code.bucket || !inputs.code.object) {
68-
packageDir = await packageCode(this, inputs)
69-
}
70-
71-
// 上传代码到COS
7228
const uploadCodeHandler = []
7329
const outputs = {}
30+
const appId = this.getAppId()
7431

7532
for (let eveRegionIndex = 0; eveRegionIndex < regionList.length; eveRegionIndex++) {
7633
const curRegion = regionList[eveRegionIndex]
7734
const funcDeployer = async () => {
78-
const code = await this.uploadCodeToCos(credentials, inputs, curRegion, packageDir)
35+
const code = await uploadCodeToCos(this, appId, credentials, inputs, curRegion)
7936
const scf = new Scf(credentials, curRegion)
8037
const tempInputs = {
8138
...inputs,

src/utils.js

Lines changed: 70 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
const path = require('path')
2-
const { copySync } = require('fs-extra')
3-
const { Domain } = require('tencent-component-toolkit')
2+
const { Domain, Cos } = require('tencent-component-toolkit')
43
const ensureObject = require('type/object/ensure')
54
const ensureIterable = require('type/iterable/ensure')
65
const ensureString = require('type/string/ensure')
@@ -21,52 +20,93 @@ const generateId = () =>
2120
Math.random()
2221
.toString(36)
2322
.substring(6)
24-
/*
25-
* Packages framework app and injects shims and sdk
26-
*
27-
* @param ${instance} instance - the component instance
28-
* @param ${object} config - the component config
29-
*/
30-
const packageCode = async (instance, inputs) => {
23+
24+
const getCodeZipPath = async (instance, inputs) => {
3125
console.log(`Packaging ${CONFIGS.frameworkFullname} application...`)
3226

3327
// unzip source zip file
34-
console.log(`Unzipping ${inputs.code.src || 'files'}...`)
35-
let sourceDirectory
28+
let zipPath
3629
if (!inputs.code.src) {
37-
// add default nextjs template
30+
// add default template
3831
const downloadPath = `/tmp/${generateId()}`
3932
const filename = 'template'
4033

4134
console.log(`Installing Default ${CONFIGS.frameworkFullname} App...`)
4235
await download(CONFIGS.templateUrl, downloadPath, {
4336
filename: `${filename}.zip`
4437
})
45-
const tempPath = await instance.unzip(`${downloadPath}/${filename}.zip`)
46-
sourceDirectory = `${tempPath}/src`
38+
zipPath = `${downloadPath}/${filename}.zip`
4739
} else {
48-
sourceDirectory = await instance.unzip(inputs.code.src)
40+
zipPath = inputs.code.src
4941
}
50-
console.log(`Files unzipped into ${sourceDirectory}...`)
5142

52-
// add shim to the source directory
53-
console.log(`Installing ${CONFIGS.frameworkFullname} + SCF handler...`)
54-
copySync(path.join(__dirname, '_shims'), path.join(sourceDirectory, '_shims'))
43+
return zipPath
44+
}
5545

56-
// add sdk to the source directory, add original handler
57-
console.log(`Installing Serverless Framework SDK...`)
58-
instance.state.handler = await instance.addSDK(sourceDirectory, '_shims/handler.handler')
46+
/**
47+
* Upload code to COS
48+
* @param {Component} instance serverless component instance
49+
* @param {string} appId app id
50+
* @param {object} credentials credentials
51+
* @param {object} inputs component inputs parameters
52+
* @param {string} region region
53+
*/
54+
const uploadCodeToCos = async (instance, appId, credentials, inputs, region) => {
55+
const bucketName = inputs.code.bucket || `sls-cloudfunction-${region}-code`
56+
const objectName = inputs.code.object || `${inputs.name}-${Math.floor(Date.now() / 1000)}.zip`
57+
// if set bucket and object not pack code
58+
if (!inputs.code.bucket || !inputs.code.object) {
59+
const zipPath = await getCodeZipPath(instance, inputs)
60+
console.log(`Code zip path ${zipPath}`)
5961

60-
// zip the source directory with the shim and the sdk
62+
// save the zip path to state for lambda to use it
63+
instance.state.zipPath = zipPath
6164

62-
console.log(`Zipping files...`)
63-
const zipPath = await instance.zip(sourceDirectory)
64-
console.log(`Files zipped into ${zipPath}...`)
65+
const cos = new Cos(credentials, region)
6566

66-
// save the zip path to state for lambda to use it
67-
instance.state.zipPath = zipPath
67+
if (!inputs.code.bucket) {
68+
// create default bucket
69+
await cos.deploy({
70+
bucket: bucketName + '-' + appId,
71+
force: true,
72+
lifecycle: [
73+
{
74+
status: 'Enabled',
75+
id: 'deleteObject',
76+
filter: '',
77+
expiration: { days: '10' },
78+
abortIncompleteMultipartUpload: { daysAfterInitiation: '10' }
79+
}
80+
]
81+
})
82+
}
6883

69-
return zipPath
84+
// upload code to cos
85+
if (!inputs.code.object) {
86+
console.log(`Getting cos upload url for bucket ${bucketName}`)
87+
const uploadUrl = await cos.getObjectUrl({
88+
bucket: bucketName + '-' + appId,
89+
object: objectName,
90+
method: 'PUT'
91+
})
92+
const slsSDKEntries = instance.getSDKEntries('_shims/handler.handler')
93+
94+
console.log(`Uploading code to bucket ${bucketName}`)
95+
await instance.uploadSourceZipToCOS(zipPath, uploadUrl, slsSDKEntries, {
96+
_shims: path.join(__dirname, '_shims')
97+
})
98+
console.log(`Upload ${objectName} to bucket ${bucketName} success`)
99+
}
100+
}
101+
102+
// save bucket state
103+
instance.state.bucket = bucketName
104+
instance.state.object = objectName
105+
106+
return {
107+
bucket: bucketName,
108+
object: objectName
109+
}
70110
}
71111

72112
const mergeJson = (sourceJson, targetJson) => {
@@ -300,7 +340,7 @@ const prepareInputs = async (instance, credentials, inputs = {}) => {
300340
module.exports = {
301341
generateId,
302342
sleep,
303-
packageCode,
343+
uploadCodeToCos,
304344
mergeJson,
305345
capitalString,
306346
getDefaultProtocol,

0 commit comments

Comments
 (0)