-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathindex.ts
182 lines (154 loc) · 5.17 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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { Response } from 'node-fetch';
import { URL } from 'url';
import {
AssetParts,
AssetsGroupedByServiceByType,
CategoryId,
CategorySummaryList,
KibanaAssetType,
RegistryPackage,
RegistrySearchResults,
RegistrySearchResult,
} from '../../../types';
import { cacheGet, cacheSet } from './cache';
import { ArchiveEntry, untarBuffer } from './extract';
import { fetchUrl, getResponse, getResponseStream } from './requests';
import { streamToBuffer } from './streams';
import { getRegistryUrl } from './registry_url';
export { ArchiveEntry } from './extract';
export interface SearchParams {
category?: CategoryId;
}
export const pkgToPkgKey = ({ name, version }: { name: string; version: string }) =>
`${name}-${version}`;
export async function fetchList(params?: SearchParams): Promise<RegistrySearchResults> {
const registryUrl = getRegistryUrl();
const url = new URL(`${registryUrl}/search`);
if (params && params.category) {
url.searchParams.set('category', params.category);
}
return fetchUrl(url.toString()).then(JSON.parse);
}
export async function fetchFindLatestPackage(
packageName: string,
internal: boolean = true
): Promise<RegistrySearchResult> {
const registryUrl = getRegistryUrl();
const url = new URL(`${registryUrl}/search?package=${packageName}&internal=${internal}`);
const res = await fetchUrl(url.toString());
const searchResults = JSON.parse(res);
if (searchResults.length) {
return searchResults[0];
} else {
throw new Error('package not found');
}
}
export async function fetchInfo(pkgName: string, pkgVersion: string): Promise<RegistryPackage> {
const registryUrl = getRegistryUrl();
return fetchUrl(`${registryUrl}/package/${pkgName}/${pkgVersion}`).then(JSON.parse);
}
export async function fetchFile(filePath: string): Promise<Response> {
const registryUrl = getRegistryUrl();
return getResponse(`${registryUrl}${filePath}`);
}
export async function fetchCategories(): Promise<CategorySummaryList> {
const registryUrl = getRegistryUrl();
return fetchUrl(`${registryUrl}/categories`).then(JSON.parse);
}
export async function getArchiveInfo(
pkgName: string,
pkgVersion: string,
filter = (entry: ArchiveEntry): boolean => true
): Promise<string[]> {
const paths: string[] = [];
const onEntry = (entry: ArchiveEntry) => {
const { path, buffer } = entry;
const { file } = pathParts(path);
if (!file) return;
if (buffer) {
cacheSet(path, buffer);
paths.push(path);
}
};
await extract(pkgName, pkgVersion, filter, onEntry);
return paths;
}
export function pathParts(path: string): AssetParts {
let dataset;
let [pkgkey, service, type, file] = path.split('/');
// if it's a dataset
if (service === 'dataset') {
// save the dataset name
dataset = type;
// drop the `dataset/dataset-name` portion & re-parse
[pkgkey, service, type, file] = path.replace(`dataset/${dataset}/`, '').split('/');
}
// This is to cover for the fields.yml files inside the "fields" directory
if (file === undefined) {
file = type;
type = 'fields';
service = '';
}
return {
pkgkey,
service,
type,
file,
dataset,
path,
} as AssetParts;
}
async function extract(
pkgName: string,
pkgVersion: string,
filter = (entry: ArchiveEntry): boolean => true,
onEntry: (entry: ArchiveEntry) => void
) {
const archiveBuffer = await getOrFetchArchiveBuffer(pkgName, pkgVersion);
return untarBuffer(archiveBuffer, filter, onEntry);
}
async function getOrFetchArchiveBuffer(pkgName: string, pkgVersion: string): Promise<Buffer> {
// assume .tar.gz for now. add support for .zip if/when we need it
const key = `${pkgName}-${pkgVersion}.tar.gz`;
let buffer = cacheGet(key);
if (!buffer) {
buffer = await fetchArchiveBuffer(pkgName, pkgVersion);
cacheSet(key, buffer);
}
if (buffer) {
return buffer;
} else {
throw new Error(`no archive buffer for ${key}`);
}
}
async function fetchArchiveBuffer(pkgName: string, pkgVersion: string): Promise<Buffer> {
const { download: archivePath } = await fetchInfo(pkgName, pkgVersion);
const registryUrl = getRegistryUrl();
return getResponseStream(`${registryUrl}${archivePath}`).then(streamToBuffer);
}
export function getAsset(key: string) {
const buffer = cacheGet(key);
if (buffer === undefined) throw new Error(`Cannot find asset ${key}`);
return buffer;
}
export function groupPathsByService(paths: string[]): AssetsGroupedByServiceByType {
// ASK: best way, if any, to avoid `any`?
const assets = paths.reduce((map: any, path) => {
const parts = pathParts(path.replace(/^\/package\//, ''));
if (parts.type in KibanaAssetType) {
if (!map[parts.service]) map[parts.service] = {};
if (!map[parts.service][parts.type]) map[parts.service][parts.type] = [];
map[parts.service][parts.type].push(parts);
}
return map;
}, {});
return {
kibana: assets.kibana,
// elasticsearch: assets.elasticsearch,
};
}