-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
containerRegistryClient.ts
310 lines (285 loc) · 9.8 KB
/
containerRegistryClient.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
309
310
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/// <reference lib="esnext.asynciterable" />
import { isTokenCredential, TokenCredential } from "@azure/core-auth";
import {
InternalPipelineOptions,
bearerTokenAuthenticationPolicy,
PipelineOptions
} from "@azure/core-rest-pipeline";
import { OperationOptions } from "@azure/core-client";
import { SpanStatusCode } from "@azure/core-tracing";
import "@azure/core-paging";
import { PageSettings, PagedAsyncIterableIterator } from "@azure/core-paging";
import { logger } from "./logger";
import { GeneratedClient } from "./generated";
import { createSpan } from "./tracing";
import { RepositoryPageResponse } from "./models";
import { extractNextLink } from "./utils/helpers";
import { ChallengeHandler } from "./containerRegistryChallengeHandler";
import {
ContainerRepository,
ContainerRepositoryImpl,
DeleteRepositoryOptions
} from "./containerRepository";
import { RegistryArtifact } from "./registryArtifact";
import { ContainerRegistryRefreshTokenCredential } from "./containerRegistryTokenCredential";
/**
* Client options used to configure Container Registry Repository API requests.
*/
export interface ContainerRegistryClientOptions extends PipelineOptions {
/**
* Gets or sets the audience to use for authentication with Azure Active Directory.
* The authentication scope will be set from this audience.
* See {@link KnownContainerRegistryAudience} for known audience values.
*/
audience?: string;
}
/**
* Options for the `listRepositories` method of `ContainerRegistryClient`.
*/
export interface ListRepositoriesOptions extends OperationOptions {}
/**
* The client class used to interact with the Container Registry service.
*/
export class ContainerRegistryClient {
/**
* The Azure Container Registry endpoint.
*/
public readonly endpoint: string;
private client: GeneratedClient;
/**
* Creates an instance of a ContainerRegistryClient.
*
* Example usage:
* ```ts
* import { ContainerRegistryClient } from "@azure/container-registry";
* import { DefaultAzureCredential} from "@azure/identity";
*
* const client = new ContainerRegistryClient(
* "<container registry API endpoint>",
* new DefaultAzureCredential()
* );
* ```
* @param endpoint - the URL endpoint of the container registry
* @param credential - used to authenticate requests to the service
* @param options - optional configuration used to send requests to the service
*/
constructor(
endpoint: string,
credential: TokenCredential,
options?: ContainerRegistryClientOptions
);
/**
* Creates an instance of a ContainerRegistryClient to interact with
* an Azure Container Registry that has anonymous pull access enabled.
* Only operations that support anonymous access are enabled. Other service
* methods will throw errors.
*
* Example usage:
* ```ts
* import { ContainerRegistryClient } from "@azure/container-registry";
*
* const client = new ContainerRegistryClient(
* "<container registry API endpoint>",
* );
* ```
* @param endpoint - the URL endpoint of the container registry
* @param options - optional configuration used to send requests to the service
*/
constructor(endpoint: string, options?: ContainerRegistryClientOptions);
constructor(
endpoint: string,
credentialOrOptions?: TokenCredential | ContainerRegistryClientOptions,
clientOptions: ContainerRegistryClientOptions = {}
) {
if (!endpoint) {
throw new Error("invalid endpoint");
}
this.endpoint = endpoint;
let credential: TokenCredential | undefined;
let options: ContainerRegistryClientOptions | undefined;
if (isTokenCredential(credentialOrOptions)) {
credential = credentialOrOptions;
options = clientOptions;
} else {
options = credentialOrOptions ?? {};
}
const internalPipelineOptions: InternalPipelineOptions = {
...options,
loggingOptions: {
logger: logger.info,
// This array contains header names we want to log that are not already
// included as safe. Unknown/unsafe headers are logged as "<REDACTED>".
additionalAllowedQueryParameters: ["last", "n", "orderby", "digest"]
}
};
// Require audience now until we have a default ACR audience from the service.
if (!options.audience) {
throw new Error(
"ContainerRegistryClientOptions.audience must be set to initialize ContainerRegistryClient."
);
}
const defaultScope = `${options.audience}/.default`;
const authClient = new GeneratedClient(endpoint, internalPipelineOptions);
this.client = new GeneratedClient(endpoint, internalPipelineOptions);
this.client.pipeline.addPolicy(
bearerTokenAuthenticationPolicy({
credential,
scopes: [defaultScope],
challengeCallbacks: new ChallengeHandler(
new ContainerRegistryRefreshTokenCredential(authClient, defaultScope, credential)
)
})
);
}
/**
* Deletes the repository identified by the given name and all associated artifacts.
*
* @param repositoryName - the name of repository to delete
* @param options - optional configuration for the operation
*/
public async deleteRepository(
repositoryName: string,
options: DeleteRepositoryOptions = {}
): Promise<void> {
if (!repositoryName) {
throw new Error("invalid repositoryName");
}
const { span, updatedOptions } = createSpan(
"ContainerRegistryClient-deleteRepository",
options
);
try {
await this.client.containerRegistry.deleteRepository(repositoryName, updatedOptions);
} catch (e) {
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
throw e;
} finally {
span.end();
}
}
/**
* Returns an instance of {@link RegistryArtifact} for calling service methods related to the artifact specified by `repositoryName` and `tagOrDigest`.
*
* @param repositoryName - the name of repository
* @param tagOrDigest - tag or digest of the artifact to retrieve
*/
public getArtifact(repositoryName: string, tagOrDigest: string): RegistryArtifact {
if (!repositoryName) {
throw new Error("invalid repositoryName");
}
if (!tagOrDigest) {
throw new Error("invalid tagOrDigest");
}
return new ContainerRepositoryImpl(this.endpoint, repositoryName, this.client).getArtifact(
tagOrDigest
);
}
/**
* Returns an instance of {@link ContainerRepository} for calling service methods related to the repository specified by `repositoryName`.
*
* @param repositoryName - the name of repository
*/
public getRepository(repositoryName: string): ContainerRepository {
if (!repositoryName) {
throw new Error("invalid repositoryName");
}
return new ContainerRepositoryImpl(this.endpoint, repositoryName, this.client);
}
/**
* Returns an async iterable iterator to list names of repositories in this registry.
*
* Example usage:
* ```javascript
* let client = new ContainerRegistryClient(url, credential);
* for await (const repository of client.listRepositoryNames()) {
* console.log("repository name: ", repository);
* }
* ```
*
* Example using `iter.next()`:
*
* ```javascript
* let iter = client.listRepositoryNames();
* let item = await iter.next();
* while (!item.done) {
* console.log(`repository name: ${item.value}`);
* item = await iter.next();
* }
* ```
*
* Example using `byPage()`:
*
* ```javascript
* const pages = client.listRepositoryNames().byPage({ maxPageSize: 2 });
* let page = await pages.next();
* let i = 1;
* while (!page.done) {
* if (page.value) {
* console.log(`-- page ${i++}`);
* for (const name of page.value) {
* console.log(` repository name: ${name}`);
* }
* }
* page = await pages.next();
* }
* ```
* @param options -
*/
public listRepositoryNames(
options: ListRepositoriesOptions = {}
): PagedAsyncIterableIterator<string, RepositoryPageResponse> {
const iter = this.listRepositoryItems(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: (settings: PageSettings = {}) => this.listRepositoriesPage(settings, options)
};
}
private async *listRepositoryItems(
options: ListRepositoriesOptions = {}
): AsyncIterableIterator<string> {
for await (const page of this.listRepositoriesPage({}, options)) {
yield* page;
}
}
private async *listRepositoriesPage(
continuationState: PageSettings,
options: ListRepositoriesOptions = {}
): AsyncIterableIterator<RepositoryPageResponse> {
if (!continuationState.continuationToken) {
const optionsComplete = {
...options,
n: continuationState.maxPageSize
};
const currentPage = await this.client.containerRegistry.getRepositories(optionsComplete);
continuationState.continuationToken = extractNextLink(currentPage.link);
if (currentPage.repositories) {
const array = currentPage.repositories;
yield Object.defineProperty(array, "continuationToken", {
value: continuationState.continuationToken,
enumerable: true
});
}
}
while (continuationState.continuationToken) {
const currentPage = await this.client.containerRegistry.getRepositoriesNext(
continuationState.continuationToken,
options
);
continuationState.continuationToken = extractNextLink(currentPage.link);
if (currentPage.repositories) {
const array = currentPage.repositories;
yield Object.defineProperty(array, "continuationToken", {
value: continuationState.continuationToken,
enumerable: true
});
}
}
}
}