-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.ts
308 lines (280 loc) · 9.46 KB
/
index.ts
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import { PascalCasedProps } from './../../modules/interface';
import { ApiServiceType } from './../interface';
import { Capi } from '@tencent-sdk/capi';
import { sleep, waitResponse } from '@ygkit/request';
import { pascalCaseProps, deepClone } from '../../utils';
import { ApiTypeError } from '../../utils/error';
import { CapiCredentials, RegionType } from '../interface';
import APIS from './apis';
import { CdnDeployInputs, CdnOutputs } from './interface';
import { TIMEOUT, formatCertInfo, formatOrigin, getCdnByDomain, openCdnService } from './utils';
import TagClient from '../tag';
export default class Cdn {
credentials: CapiCredentials;
capi: Capi;
tagClient: TagClient;
constructor(credentials: CapiCredentials = {} as any, region: RegionType = 'ap-guangzhou') {
this.credentials = credentials;
this.capi = new Capi({
Region: region,
ServiceType: ApiServiceType.cdn,
SecretId: this.credentials.SecretId!,
SecretKey: this.credentials.SecretKey!,
Token: this.credentials.Token,
});
this.tagClient = new TagClient(this.credentials, region);
}
async purgeCdnUrls(urls: string[], flushType = 'flush') {
console.log(`Purging CDN caches, it will work in 5 minutes...`);
try {
await APIS.PurgePathCache(this.capi, {
Paths: urls,
FlushType: flushType,
});
} catch (e) {
// no op
}
}
async pushCdnUrls(urls: string[], userAgent = 'TencentCdn', area = 'mainland') {
console.log(`Pushing CDN caches...`);
try {
await APIS.PushUrlsCache(this.capi, {
Urls: urls,
Area: area,
UserAgent: userAgent,
});
} catch (e) {
// no op
}
}
async offlineCdnDomain(domain: string) {
const { Status } = await getCdnByDomain(this.capi, domain);
if (Status === 'online') {
// disable first
await APIS.StopCdnDomain(this.capi, { Domain: domain });
} else if (Status === 'processing') {
throw new Error(`Status is not operational for ${domain}`);
}
}
/** 部署 CDN */
async deploy(inputs: CdnDeployInputs): Promise<CdnOutputs | undefined> {
if (inputs.ignoreUpdate) {
console.log('CDN update ignored');
return;
}
await openCdnService(this.capi);
const { oldState = {} } = inputs;
delete inputs.oldState;
const pascalInputs = pascalCaseProps(inputs);
// only refresh cdn
if (pascalInputs.OnlyRefresh === true) {
const domainExist = await getCdnByDomain(this.capi, pascalInputs.Domain);
// refresh cdn urls
if (domainExist && pascalInputs.RefreshCdn?.Urls) {
await this.purgeCdnUrls(pascalInputs.RefreshCdn.Urls, pascalInputs.RefreshCdn.FlushType);
}
return {
resourceId: domainExist.ResourceId,
https: !!pascalInputs.Https,
domain: pascalInputs.Domain,
origins: pascalInputs.Origin && pascalInputs.Origin.Origins,
cname: `${pascalInputs.Domain}.cdn.dnsv1.com`,
refreshUrls: pascalInputs.RefreshCdn?.Urls,
};
}
const {
Domain,
Area,
Cache,
IpFilter,
IpFreqLimit,
StatusCodeCache,
ForceRedirect,
Compression,
BandwidthAlert,
RangeOriginPull,
FollowRedirect,
ErrorPage,
RequestHeader,
ResponseHeader,
DownstreamCapping,
CacheKey,
ResponseHeaderCache,
VideoSeek,
OriginPullOptimization,
Authentication,
Seo,
Referer,
MaxAge,
SpecificConfig,
OriginPullTimeout,
} = pascalInputs;
const cdnInputs: PascalCasedProps<CdnDeployInputs> = deepClone({
Domain,
Area,
Cache,
IpFilter,
IpFreqLimit,
StatusCodeCache,
ForceRedirect,
Compression,
BandwidthAlert,
RangeOriginPull,
FollowRedirect,
ErrorPage,
RequestHeader,
ResponseHeader,
DownstreamCapping,
CacheKey,
ResponseHeaderCache,
VideoSeek,
OriginPullOptimization,
Authentication,
Seo,
Referer,
MaxAge,
SpecificConfig,
OriginPullTimeout,
Origin: formatOrigin(pascalInputs.Origin),
});
const outputs: CdnOutputs = {
https: !!pascalInputs.Https,
domain: pascalInputs.Domain,
origins: cdnInputs.Origin.Origins,
cname: `${pascalInputs.Domain}.cdn.dnsv1.com`,
inputCache: JSON.stringify(inputs),
};
if (pascalInputs.Https) {
cdnInputs.Https = {
Switch: pascalInputs.Https.Switch ?? 'on',
Http2: pascalInputs.Https.Http2 ?? 'off',
OcspStapling: pascalInputs.Https.OcspStapling || 'off',
VerifyClient: pascalInputs.Https.VerifyClient || 'off',
CertInfo: formatCertInfo(pascalInputs.Https.CertInfo),
};
}
if (pascalInputs.ForceRedirect && pascalInputs.Https) {
cdnInputs.ForceRedirect = {
Switch: pascalInputs.ForceRedirect.Switch ?? 'on',
RedirectStatusCode: pascalInputs.ForceRedirect.RedirectStatusCode || 301,
RedirectType: 'https',
};
}
let cdnInfo = await getCdnByDomain(this.capi, pascalInputs.Domain);
const sourceInputs = JSON.parse(JSON.stringify(cdnInputs));
const createOrUpdateCdn = async () => {
if (cdnInfo && cdnInfo.Status === 'offline') {
console.log(`The CDN domain ${pascalInputs.Domain} is offline.`);
console.log(`Recreating CDN domain ${pascalInputs.Domain}`);
await APIS.DeleteCdnDomain(this.capi, { Domain: pascalInputs.Domain });
cdnInfo = null;
}
if (cdnInfo) {
// update
console.log(`The CDN domain ${pascalInputs.Domain} has existed.`);
console.log('Updating...');
// TODO: when update, VIP user can not set ServiceType parameter, need CDN api optimize
if (cdnInputs.ServiceType && cdnInputs.ServiceType !== cdnInfo.ServiceType) {
cdnInputs.ServiceType = inputs.serviceType;
}
await APIS.UpdateDomainConfig(this.capi, cdnInputs);
outputs.resourceId = cdnInfo.ResourceId;
} else {
// create
console.log(`Adding CDN domain ${pascalInputs.Domain}...`);
try {
// if not config ServiceType, default to web
cdnInputs.ServiceType = inputs.serviceType ?? 'web';
await APIS.AddCdnDomain(this.capi, cdnInputs);
} catch (e) {
if (e.code === 'ResourceNotFound.CdnUserNotExists') {
console.log(`Please goto https://console.cloud.tencent.com/cdn open CDN service.`);
}
throw e;
}
await sleep(1000);
const detail = await getCdnByDomain(this.capi, pascalInputs.Domain);
outputs.resourceId = detail && detail.ResourceId;
}
console.log('Waiting for CDN deploy success, it maybe cost 5 minutes....');
// When set syncFlow false, just continue, do not wait for online status.
if (pascalInputs.Async === false) {
await waitResponse({
callback: async () => getCdnByDomain(this.capi, pascalInputs.Domain),
targetProp: 'Status',
targetResponse: 'online',
timeout: TIMEOUT,
});
// push cdn urls
if (pascalInputs.PushCdn && pascalInputs.PushCdn.Urls) {
await this.pushCdnUrls(
pascalInputs.PushCdn.Urls,
pascalInputs.PushCdn.Area,
pascalInputs.PushCdn.UserAgent,
);
}
// refresh cdn urls
if (pascalInputs.RefreshCdn && pascalInputs.RefreshCdn.Urls) {
await this.purgeCdnUrls(pascalInputs.RefreshCdn.Urls);
}
}
try {
const { tags = [] } = inputs;
await this.tagClient.deployResourceTags({
tags: tags.map(({ key, value }) => ({ TagKey: key, TagValue: value })),
resourceId: Domain,
serviceType: ApiServiceType.cdn,
resourcePrefix: 'domain',
});
if (tags.length > 0) {
outputs.tags = tags;
}
} catch (e) {
console.log(`[TAG] ${e.message}`);
}
console.log(`CDN deploy success to domain: ${pascalInputs.Domain}`);
};
// pass state for cache check
const { inputCache } = oldState;
if (inputCache && inputCache === JSON.stringify(sourceInputs)) {
console.log(`No configuration changes for CDN domain ${pascalInputs.Domain}`);
outputs.resourceId = cdnInfo.ResourceId;
} else {
await createOrUpdateCdn();
}
return outputs;
}
/** 删除 CDN */
async remove(inputs: { domain: string }) {
const { domain } = inputs;
if (!domain) {
throw new ApiTypeError(`PARAMETER_CDN`, 'domain is required');
}
// need circle for deleting, after domain status is 6, then we can delete it
console.log(`Start removing CDN for ${domain}`);
const detail = await getCdnByDomain(this.capi, domain);
if (!detail) {
console.log(`CDN domain ${domain} not exist`);
return {};
}
const { Status } = detail;
if (Status === 'online') {
// disable first
await APIS.StopCdnDomain(this.capi, { Domain: domain });
} else if (Status === 'processing') {
console.log(`Status is not operational for ${domain}`);
return {};
}
console.log(`Waiting for offline ${domain}...`);
await waitResponse({
callback: async () => getCdnByDomain(this.capi, domain),
targetProp: 'Status',
targetResponse: 'offline',
timeout: TIMEOUT,
});
console.log(`Removing CDN for ${domain}`);
await APIS.DeleteCdnDomain(this.capi, { Domain: domain });
console.log(`Removed CDN for ${domain}.`);
return {};
}
}