[storage-queue] Migrate to core-rest-pipeline (#26207)

### Packages impacted by this PR

`@azure/storage-queue`

### Issues associated with this PR

Fixes #15813
Closes #15594

### Describe the problem that is addressed by this PR

This PR migrates storage-queue to the new core pipeline in the same way
that storage-file-share was migrated. There are no changes to the public
surface and existing recorded tests still pass.

### Provide a list of related PRs _(if any)_

https://github.com/Azure/azure-sdk-for-js/pull/26102
This commit is contained in:
Jeff Fisher 2023-06-15 16:10:58 -05:00 коммит произвёл GitHub
Родитель 960a169a18
Коммит 6582843a1a
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
70 изменённых файлов: 1334 добавлений и 2419 удалений

Просмотреть файл

@ -19424,7 +19424,7 @@ packages:
dev: false
file:projects/storage-queue.tgz:
resolution: {integrity: sha512-gx0lTVTkd8sw4IuQpQue9AyPD9VRY5gxPaulhKOvEi0UWRvqbnt8tJ6iUhVibgnCAZGRkSqDwvKhNb9kiQJAAw==, tarball: file:projects/storage-queue.tgz}
resolution: {integrity: sha512-Q0bri+ynTJgsge2RC0t1+0Zf8PfAL9+/CRa2llPvyq5uFoMexdRvBv6h+91V1mRjUAcJkDGPfpJNDXRghhRHGw==, tarball: file:projects/storage-queue.tgz}
name: '@rush-temp/storage-queue'
version: 0.0.0
dependencies:
@ -19435,6 +19435,7 @@ packages:
'@types/chai': 4.3.5
'@types/mocha': 7.0.2
'@types/node': 14.18.50
'@types/uuid': 8.3.4
chai: 4.3.7
cross-env: 7.0.3
dotenv: 16.1.4
@ -19465,6 +19466,7 @@ packages:
tslib: 2.5.3
typescript: 5.0.4
util: 0.12.5
uuid: 8.3.2
transitivePeerDependencies:
- '@swc/core'
- '@swc/wasm'

Просмотреть файл

@ -0,0 +1,7 @@
{
"plugins": ["@azure/azure-sdk"],
"extends": ["plugin:@azure/azure-sdk/azure-sdk-base"],
"rules": {
"@azure/azure-sdk/ts-package-json-module": "warn"
}
}

Просмотреть файл

@ -1,5 +1,17 @@
# Release History
## 12.20.0 (Unreleased)
### Features Added
### Breaking Changes
### Bugs Fixed
### Other Changes
- Migrated dependency on `@azure/core-http` to `@azure/core-rest-pipeline`.
## 12.12.0 (Unreleased)
### Features Added

Просмотреть файл

@ -1,6 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"mainEntryPointFilePath": "types/latest/src/index.d.ts",
"mainEntryPointFilePath": "types/latest/storage-queue/src/index.d.ts",
"docModel": {
"enabled": true
},

Просмотреть файл

@ -1,19 +1,20 @@
{
"name": "@azure/storage-queue",
"sdk-type": "client",
"version": "12.12.0",
"version": "12.20.0",
"description": "Microsoft Azure Storage SDK for JavaScript - Queue",
"main": "./dist/index.js",
"module": "./dist-esm/src/index.js",
"module": "./dist-esm/storage-queue/src/index.js",
"browser": {
"./dist-esm/src/index.js": "./dist-esm/src/index.browser.js",
"./dist-esm/src/credentials/StorageSharedKeyCredential.js": "./dist-esm/src/credentials/StorageSharedKeyCredential.browser.js",
"./dist-esm/test/utils/index.js": "./dist-esm/test/utils/index.browser.js",
"./dist-esm/storage-queue/src/index.js": "./dist-esm/storage-queue/src/index.browser.js",
"./dist-esm/storage-blob/src/credentials/StorageSharedKeyCredential.js": "./dist-esm/storage-blob/src/credentials/StorageSharedKeyCredential.browser.js",
"./dist-esm/storage-blob/src/policies/StorageSharedKeyCredentialPolicyV2.js": "./dist-esm/storage-blob/src/policies/StorageSharedKeyCredentialPolicyV2.browser.js",
"./dist-esm/storage-queue/test/utils/index.js": "./dist-esm/storage-queue/test/utils/index.browser.js",
"os": false,
"process": false
},
"react-native": {
"./dist/index.js": "./dist-esm/src/index.js"
"./dist/index.js": "./dist-esm/storage-queue/src/index.js"
},
"types": "./types/latest/storage-queue.d.ts",
"typesVersions": {
@ -42,7 +43,7 @@
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
"generate:client": "autorest --typescript ./swagger/README.md",
"integration-test:browser": "karma start --single-run",
"integration-test:node": "nyc mocha -r esm --require source-map-support/register --reporter ../../../common/tools/mocha-multi-reporter.js --full-trace -t 120000 \"dist-esm/test/*.spec.js\" \"dist-esm/test/node/*.spec.js\"",
"integration-test:node": "nyc mocha -r esm --require source-map-support/register --reporter ../../../common/tools/mocha-multi-reporter.js --full-trace -t 120000 \"dist-esm/storage-queue/test/*.spec.js\" \"dist-esm/storage-queue/test/node/*.spec.js\"",
"integration-test": "npm run integration-test:node && npm run integration-test:browser",
"lint:fix": "eslint package.json api-extractor.json README.md src test --ext .ts,.javascript,.js --fix",
"lint": "eslint package.json api-extractor.json README.md src test --ext .ts,.javascript,.js",
@ -56,9 +57,9 @@
"emulator-tests": "cross-env STORAGE_CONNECTION_STRING=UseDevelopmentStorage=true && npm run test:node"
},
"files": [
"BreakingChanges.md",
"dist/",
"dist-esm/src/",
"dist-esm/storage-blob/src/",
"dist-esm/storage-queue/src/",
"types/latest/storage-queue.d.ts",
"types/3.1/storage-queue.d.ts",
"README.md",
@ -118,22 +119,30 @@
},
"dependencies": {
"@azure/abort-controller": "^1.0.0",
"@azure/core-http": "^3.0.0",
"@azure/core-auth": "^1.4.0",
"@azure/core-client": "^1.6.2",
"@azure/core-http-compat": "^2.0.0",
"@azure/core-paging": "^1.1.1",
"@azure/core-rest-pipeline": "^1.10.1",
"@azure/core-tracing": "1.0.0-preview.13",
"@azure/core-util": "^1.1.1",
"@azure/core-xml": "^1.3.2",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0"
"tslib": "^2.2.0",
"uuid": "^8.3.0"
},
"devDependencies": {
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/identity": "^2.0.1",
"@azure/storage-blob": "^12.20.0",
"@azure/test-utils": "^1.0.0",
"@azure-tools/test-recorder": "^1.0.0",
"@microsoft/api-extractor": "^7.31.1",
"@types/chai": "^4.1.6",
"@types/mocha": "^7.0.2",
"@types/node": "^14.0.0",
"@types/uuid": "^8.0.0",
"chai": "^4.2.0",
"cross-env": "^7.0.2",
"dotenv": "^16.0.0",

Просмотреть файл

@ -20,7 +20,7 @@ nock('https://fakestorageaccount.queue.core.windows.net:443', {"encodedQueryPara
nock('https://fakestorageaccount.queue.core.windows.net:443', {"encodedQueryParams":true})
.post('/queue156816832289609918/messages', "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><QueueMessage><MessageText>!@#$%^&amp;*()_+`-=[]|};'\":,./?&gt;&lt;`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞𻆕󛿓򐞺Ӯ򡗺򴜍&lt;񐸩԰Bu)򁉂񖨞á&lt;џɏ嗂<C98F>⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦é</MessageText></QueueMessage>")
.post('/queue156816832289609918/messages', "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><QueueMessage><MessageText>!@#$%^&amp;*()_+`-=[]|};&apos;&quot;:,./?&gt;&lt;`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞𻆕󛿓򐞺Ӯ򡗺򴜍&lt;񐸩԰Bu)򁉂񖨞á&lt;џɏ嗂<C98F>⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦é</MessageText></QueueMessage>")
.query(true)
.reply(201, "<?xml version=\"1.0\" encoding=\"utf-8\"?><QueueMessagesList><QueueMessage><MessageId>c609a6e3-da86-4c92-a6aa-32e453e8bce7</MessageId><InsertionTime>Wed, 11 Sep 2019 02:18:43 GMT</InsertionTime><ExpirationTime>Wed, 11 Sep 2019 02:19:23 GMT</ExpirationTime><PopReceipt>AgAAAAMAAAAAAAAAYPQJPEdo1QE=</PopReceipt><TimeNextVisible>Wed, 11 Sep 2019 02:18:43 GMT</TimeNextVisible></QueueMessage></QueueMessagesList>", [ 'Transfer-Encoding',
'chunked',
@ -103,4 +103,3 @@ nock('https://fakestorageaccount.queue.core.windows.net:443', {"encodedQueryPara
'2019-02-02',
'Date',
'Wed, 11 Sep 2019 02:18:44 GMT' ]);

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Просмотреть файл

@ -6,27 +6,22 @@
import { AbortSignalLike } from '@azure/abort-controller';
import { AzureLogger } from '@azure/logger';
import { BaseRequestPolicy } from '@azure/core-http';
import * as coreHttp from '@azure/core-http';
import { deserializationPolicy } from '@azure/core-http';
import { HttpHeaders } from '@azure/core-http';
import { HttpOperationResponse } from '@azure/core-http';
import { HttpRequestBody } from '@azure/core-http';
import { HttpResponse } from '@azure/core-http';
import { HttpClient as IHttpClient } from '@azure/core-http';
import { KeepAliveOptions } from '@azure/core-http';
import { CompatResponse } from '@azure/core-http-compat';
import * as coreClient from '@azure/core-client';
import * as coreHttpCompat from '@azure/core-http-compat';
import { HttpHeadersLike } from '@azure/core-http-compat';
import { HttpPipelineLogLevel } from '@azure/core-http-compat';
import { KeepAliveOptions } from '@azure/core-http-compat';
import { OperationTracingOptions } from '@azure/core-tracing';
import { PagedAsyncIterableIterator } from '@azure/core-paging';
import { ProxyOptions } from '@azure/core-http';
import { RequestOptionsBase } from '@azure/core-http';
import { RequestPolicy } from '@azure/core-http';
import { RequestPolicyFactory } from '@azure/core-http';
import { RequestPolicyOptions } from '@azure/core-http';
import { RestError } from '@azure/core-http';
import { ServiceClientOptions } from '@azure/core-http';
import { TokenCredential } from '@azure/core-http';
import { UserAgentOptions } from '@azure/core-http';
import { WebResource } from '@azure/core-http';
import { ProxySettings } from '@azure/core-rest-pipeline';
import { RequestPolicy } from '@azure/core-http-compat';
import { RequestPolicyFactory } from '@azure/core-http-compat';
import { RequestPolicyOptionsLike } from '@azure/core-http-compat';
import { RestError } from '@azure/core-rest-pipeline';
import { TokenCredential } from '@azure/core-auth';
import { UserAgentPolicyOptions } from '@azure/core-rest-pipeline';
import { WebResourceLike } from '@azure/core-http-compat';
// @public
export interface AccessPolicy {
@ -82,15 +77,25 @@ export interface AccountSASSignatureValues {
// @public
export class AnonymousCredential extends Credential_2 {
create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): AnonymousCredentialPolicy;
create(nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike): AnonymousCredentialPolicy;
}
// @public
export class AnonymousCredentialPolicy extends CredentialPolicy {
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions);
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike);
}
export { BaseRequestPolicy }
// @public
export abstract class BaseRequestPolicy implements RequestPolicy {
protected constructor(
_nextPolicy: RequestPolicy,
_options: RequestPolicyOptionsLike);
log(logLevel: HttpPipelineLogLevel, message: string): void;
readonly _nextPolicy: RequestPolicy;
readonly _options: RequestPolicyOptionsLike;
abstract sendRequest(webResource: WebResourceLike): Promise<CompatResponse>;
shouldLog(logLevel: HttpPipelineLogLevel): boolean;
}
// @public
export interface CommonOptions {
@ -108,18 +113,18 @@ export interface CorsRule {
// @public
abstract class Credential_2 implements RequestPolicyFactory {
create(_nextPolicy: RequestPolicy, _options: RequestPolicyOptions): RequestPolicy;
create(_nextPolicy: RequestPolicy, _options: RequestPolicyOptionsLike): RequestPolicy;
}
export { Credential_2 as Credential }
// @public
export abstract class CredentialPolicy extends BaseRequestPolicy {
sendRequest(request: WebResource): Promise<HttpOperationResponse>;
protected signRequest(request: WebResource): WebResource;
sendRequest(request: WebResourceLike): Promise<CompatResponse>;
protected signRequest(request: WebResourceLike): WebResourceLike;
}
// @public
export type CredentialPolicyCreator = (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => CredentialPolicy;
export type CredentialPolicyCreator = (nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike) => CredentialPolicy;
// @public
export interface DequeuedMessageItem {
@ -132,8 +137,6 @@ export interface DequeuedMessageItem {
popReceipt: string;
}
export { deserializationPolicy }
// @public
export interface EnqueuedMessage {
expiresOn: Date;
@ -158,13 +161,15 @@ export interface GeoReplication {
// @public
export type GeoReplicationStatusType = "live" | "bootstrap" | "unavailable";
export { HttpHeaders }
// @public
export interface HttpResponse {
headers: HttpHeadersLike;
request: WebResourceLike;
status: number;
}
export { HttpOperationResponse }
export { HttpRequestBody }
export { IHttpClient }
// @public
export function isPipelineLike(pipeline: unknown): pipeline is PipelineLike;
// @public
export type ListQueuesIncludeType = "metadata";
@ -207,11 +212,7 @@ export interface MessageIdDeleteHeaders {
}
// @public
export type MessageIdDeleteResponse = MessageIdDeleteHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: MessageIdDeleteHeaders;
};
};
export type MessageIdDeleteResponse = WithResponse<MessageIdDeleteHeaders, MessageIdDeleteHeaders>;
// @public
export interface MessageIdUpdateHeaders {
@ -225,11 +226,7 @@ export interface MessageIdUpdateHeaders {
}
// @public
export type MessageIdUpdateResponse = MessageIdUpdateHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: MessageIdUpdateHeaders;
};
};
export type MessageIdUpdateResponse = WithResponse<MessageIdUpdateHeaders, MessageIdUpdateHeaders>;
// @public
export interface MessagesClearHeaders {
@ -241,11 +238,7 @@ export interface MessagesClearHeaders {
}
// @public
export type MessagesClearResponse = MessagesClearHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: MessagesClearHeaders;
};
};
export type MessagesClearResponse = WithResponse<MessagesClearHeaders, MessagesClearHeaders>;
// @public
export interface MessagesDequeueHeaders {
@ -257,7 +250,7 @@ export interface MessagesDequeueHeaders {
}
// @public
export interface MessagesDequeueOptionalParams extends RequestOptionsBase {
export interface MessagesDequeueOptionalParams extends CommonOptions {
numberOfMessages?: number;
requestId?: string;
timeoutInSeconds?: number;
@ -274,7 +267,7 @@ export interface MessagesEnqueueHeaders {
}
// @public
export interface MessagesEnqueueOptionalParams extends RequestOptionsBase {
export interface MessagesEnqueueOptionalParams extends CommonOptions {
messageTimeToLive?: number;
requestId?: string;
timeoutInSeconds?: number;
@ -291,7 +284,7 @@ export interface MessagesPeekHeaders {
}
// @public
export interface MessagesPeekOptionalParams extends RequestOptionsBase {
export interface MessagesPeekOptionalParams extends CommonOptions {
numberOfMessages?: number;
requestId?: string;
timeoutInSeconds?: number;
@ -323,16 +316,23 @@ export interface PeekedMessageItem {
}
// @public
export class Pipeline {
export class Pipeline implements PipelineLike {
constructor(factories: RequestPolicyFactory[], options?: PipelineOptions);
readonly factories: RequestPolicyFactory[];
readonly options: PipelineOptions;
toServiceClientOptions(): ServiceClientOptions;
}
// @public
export interface PipelineLike {
readonly factories: RequestPolicyFactory[];
readonly options: PipelineOptions;
toServiceClientOptions(): ServiceClientOptions;
}
// @public
export interface PipelineOptions {
httpClient?: IHttpClient;
httpClient?: RequestPolicy;
}
// @public
@ -390,11 +390,7 @@ export interface QueueCreateOptions extends CommonOptions {
}
// @public
export type QueueCreateResponse = QueueCreateHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: QueueCreateHeaders;
};
};
export type QueueCreateResponse = WithResponse<QueueCreateHeaders, QueueCreateHeaders>;
// @public
export interface QueueDeleteHeaders {
@ -424,11 +420,7 @@ export interface QueueDeleteOptions extends CommonOptions {
}
// @public
export type QueueDeleteResponse = QueueDeleteHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: QueueDeleteHeaders;
};
};
export type QueueDeleteResponse = WithResponse<QueueDeleteHeaders, QueueDeleteHeaders>;
// @public
export interface QueueExistsOptions extends CommonOptions {
@ -461,15 +453,9 @@ export interface QueueGetAccessPolicyOptions extends CommonOptions {
}
// @public
export type QueueGetAccessPolicyResponse = {
export type QueueGetAccessPolicyResponse = WithResponse<{
signedIdentifiers: SignedIdentifier[];
} & QueueGetAccessPolicyHeaders & {
_response: HttpResponse & {
parsedHeaders: QueueGetAccessPolicyHeaders;
bodyAsText: string;
parsedBody: SignedIdentifierModel[];
};
};
} & QueueGetAccessPolicyHeaders, QueueGetAccessPolicyHeaders, SignedIdentifierModel[]>;
// @public
export interface QueueGetPropertiesHeaders {
@ -491,11 +477,7 @@ export interface QueueGetPropertiesOptions extends CommonOptions {
}
// @public
export type QueueGetPropertiesResponse = QueueGetPropertiesHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: QueueGetPropertiesHeaders;
};
};
export type QueueGetPropertiesResponse = WithResponse<QueueGetPropertiesHeaders, QueueGetPropertiesHeaders>;
// @public
export interface QueueItem {
@ -510,30 +492,18 @@ export interface QueuePeekMessagesOptions extends MessagesPeekOptionalParams, Co
}
// @public
export type QueuePeekMessagesResponse = {
export type QueuePeekMessagesResponse = WithResponse<{
peekedMessageItems: PeekedMessageItem[];
} & MessagesPeekHeaders & {
_response: HttpResponse & {
parsedHeaders: MessagesPeekHeaders;
bodyAsText: string;
parsedBody: PeekedMessageItem[];
};
};
} & MessagesPeekHeaders, MessagesPeekHeaders, PeekedMessageItem[]>;
// @public
export interface QueueReceiveMessageOptions extends MessagesDequeueOptionalParams, CommonOptions {
}
// @public
export type QueueReceiveMessageResponse = {
export type QueueReceiveMessageResponse = WithResponse<{
receivedMessageItems: ReceivedMessageItem[];
} & MessagesDequeueHeaders & {
_response: HttpResponse & {
parsedHeaders: MessagesDequeueHeaders;
bodyAsText: string;
parsedBody: ReceivedMessageItem[];
};
};
} & MessagesDequeueHeaders, MessagesDequeueHeaders, ReceivedMessageItem[]>;
// @public
export class QueueSASPermissions {
@ -562,19 +532,13 @@ export interface QueueSendMessageOptions extends MessagesEnqueueOptionalParams,
}
// @public
export type QueueSendMessageResponse = {
export type QueueSendMessageResponse = WithResponse<{
messageId: string;
popReceipt: string;
insertedOn: Date;
expiresOn: Date;
nextVisibleOn: Date;
} & MessagesEnqueueHeaders & {
_response: HttpResponse & {
parsedHeaders: MessagesEnqueueHeaders;
bodyAsText: string;
parsedBody: EnqueuedMessage[];
};
};
} & MessagesEnqueueHeaders, MessagesEnqueueHeaders, EnqueuedMessage[]>;
// @public
export class QueueServiceClient extends StorageClient {
@ -619,11 +583,7 @@ export interface QueueSetAccessPolicyOptions extends CommonOptions {
}
// @public
export type QueueSetAccessPolicyResponse = QueueSetAccessPolicyHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: QueueSetAccessPolicyHeaders;
};
};
export type QueueSetAccessPolicyResponse = WithResponse<QueueSetAccessPolicyHeaders, QueueSetAccessPolicyHeaders>;
// @public
export interface QueueSetMetadataHeaders {
@ -640,11 +600,7 @@ export interface QueueSetMetadataOptions extends CommonOptions {
}
// @public
export type QueueSetMetadataResponse = QueueSetMetadataHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: QueueSetMetadataHeaders;
};
};
export type QueueSetMetadataResponse = WithResponse<QueueSetMetadataHeaders, QueueSetMetadataHeaders>;
// @public
export interface QueueUpdateMessageOptions extends CommonOptions {
@ -657,11 +613,26 @@ export type QueueUpdateMessageResponse = MessageIdUpdateResponse;
// @public
export type ReceivedMessageItem = DequeuedMessageItem;
export { RequestPolicy }
// @public
export interface ResponseLike {
_response: HttpResponse;
}
export { RequestPolicyFactory }
// @public
export interface ResponseWithBody<Headers, Body> {
_response: HttpResponse & {
parsedHeaders: Headers;
bodyAsText: string;
parsedBody: Body;
};
}
export { RequestPolicyOptions }
// @public
export interface ResponseWithHeaders<Headers> {
_response: HttpResponse & {
parsedHeaders: Headers;
};
}
export { RestError }
@ -700,6 +671,12 @@ export class SASQueryParameters {
readonly version: string;
}
// @public
export interface ServiceClientOptions {
httpClient?: RequestPolicy;
requestPolicyFactories?: RequestPolicyFactory[] | ((defaultRequestPolicyFactories: RequestPolicyFactory[]) => void | RequestPolicyFactory[]);
}
// @public
export interface ServiceGenerateAccountSasUrlOptions {
ipRange?: SasIPRange;
@ -722,13 +699,7 @@ export interface ServiceGetPropertiesOptions extends CommonOptions {
}
// @public
export type ServiceGetPropertiesResponse = ServiceGetPropertiesHeaders & QueueServiceProperties & {
_response: coreHttp.HttpResponse & {
bodyAsText: string;
parsedBody: QueueServiceProperties;
parsedHeaders: ServiceGetPropertiesHeaders;
};
};
export type ServiceGetPropertiesResponse = WithResponse<ServiceGetPropertiesHeaders & QueueServiceProperties, ServiceGetPropertiesHeaders, QueueServiceProperties>;
// @public
export interface ServiceGetStatisticsHeaders {
@ -745,13 +716,7 @@ export interface ServiceGetStatisticsOptions extends CommonOptions {
}
// @public
export type ServiceGetStatisticsResponse = ServiceGetStatisticsHeaders & QueueServiceStatistics & {
_response: coreHttp.HttpResponse & {
bodyAsText: string;
parsedBody: QueueServiceStatistics;
parsedHeaders: ServiceGetStatisticsHeaders;
};
};
export type ServiceGetStatisticsResponse = WithResponse<ServiceGetStatisticsHeaders & QueueServiceStatistics, ServiceGetStatisticsHeaders, QueueServiceStatistics>;
// @public
export interface ServiceListQueuesOptions extends CommonOptions {
@ -770,13 +735,7 @@ export interface ServiceListQueuesSegmentHeaders {
}
// @public
export type ServiceListQueuesSegmentResponse = ServiceListQueuesSegmentHeaders & ListQueuesSegmentResponse & {
_response: coreHttp.HttpResponse & {
bodyAsText: string;
parsedBody: ListQueuesSegmentResponse;
parsedHeaders: ServiceListQueuesSegmentHeaders;
};
};
export type ServiceListQueuesSegmentResponse = WithResponse<ServiceListQueuesSegmentHeaders & ListQueuesSegmentResponse, ServiceListQueuesSegmentHeaders, ListQueuesSegmentResponse>;
// @public
export interface ServiceSetPropertiesHeaders {
@ -792,11 +751,7 @@ export interface ServiceSetPropertiesOptions extends CommonOptions {
}
// @public
export type ServiceSetPropertiesResponse = ServiceSetPropertiesHeaders & {
_response: coreHttp.HttpResponse & {
parsedHeaders: ServiceSetPropertiesHeaders;
};
};
export type ServiceSetPropertiesResponse = WithResponse<ServiceSetPropertiesHeaders, ServiceSetPropertiesHeaders>;
// @public
export interface SignedIdentifier {
@ -816,25 +771,23 @@ export interface SignedIdentifierModel {
// @public
export class StorageBrowserPolicy extends BaseRequestPolicy {
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions);
sendRequest(request: WebResource): Promise<HttpOperationResponse>;
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike);
sendRequest(request: WebResourceLike): Promise<CompatResponse>;
}
// @public
export class StorageBrowserPolicyFactory implements RequestPolicyFactory {
create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): StorageBrowserPolicy;
create(nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike): StorageBrowserPolicy;
}
// @public
export const StorageOAuthScopes: string | string[];
// @public
export interface StoragePipelineOptions {
httpClient?: IHttpClient;
audience?: string | string[];
httpClient?: RequestPolicy;
keepAliveOptions?: KeepAliveOptions;
proxyOptions?: ProxyOptions;
proxyOptions?: ProxySettings;
retryOptions?: StorageRetryOptions;
userAgentOptions?: UserAgentOptions;
userAgentOptions?: UserAgentPolicyOptions;
}
// @public
@ -849,16 +802,16 @@ export interface StorageRetryOptions {
// @public
export class StorageRetryPolicy extends BaseRequestPolicy {
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, retryOptions?: StorageRetryOptions);
protected attemptSendRequest(request: WebResource, secondaryHas404: boolean, attempt: number): Promise<HttpOperationResponse>;
sendRequest(request: WebResource): Promise<HttpOperationResponse>;
protected shouldRetry(isPrimaryRetry: boolean, attempt: number, response?: HttpOperationResponse, err?: RestError): boolean;
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike, retryOptions?: StorageRetryOptions);
protected attemptSendRequest(request: WebResourceLike, secondaryHas404: boolean, attempt: number): Promise<CompatResponse>;
sendRequest(request: WebResourceLike): Promise<CompatResponse>;
protected shouldRetry(isPrimaryRetry: boolean, attempt: number, response?: CompatResponse, err?: RestError): boolean;
}
// @public
export class StorageRetryPolicyFactory implements RequestPolicyFactory {
constructor(retryOptions?: StorageRetryOptions);
create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): StorageRetryPolicy;
create(nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike): StorageRetryPolicy;
}
// @public
@ -872,16 +825,17 @@ export class StorageSharedKeyCredential extends Credential_2 {
constructor(accountName: string, accountKey: string);
readonly accountName: string;
computeHMACSHA256(stringToSign: string): string;
create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): StorageSharedKeyCredentialPolicy;
create(nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike): StorageSharedKeyCredentialPolicy;
}
// @public
export class StorageSharedKeyCredentialPolicy extends CredentialPolicy {
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, factory: StorageSharedKeyCredential);
protected signRequest(request: WebResource): WebResource;
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike, factory: StorageSharedKeyCredential);
protected signRequest(request: WebResourceLike): WebResourceLike;
}
export { WebResource }
// @public
export type WithResponse<T, Headers = undefined, Body = undefined> = T & (Body extends object ? ResponseWithBody<Headers, Body> : Headers extends object ? ResponseWithHeaders<Headers> : ResponseLike);
// (No @packageDocumentation comment for this package)

Просмотреть файл

@ -4,7 +4,7 @@
import { AccountSASPermissions } from "./AccountSASPermissions";
import { AccountSASResourceTypes } from "./AccountSASResourceTypes";
import { AccountSASServices } from "./AccountSASServices";
import { StorageSharedKeyCredential } from "./credentials/StorageSharedKeyCredential";
import { StorageSharedKeyCredential } from "../../storage-blob/src/credentials/StorageSharedKeyCredential";
import { SasIPRange, ipRangeToString } from "./SasIPRange";
import { SASProtocol, SASQueryParameters } from "./SASQueryParameters";
import { SERVICE_VERSION } from "./utils/constants";

Просмотреть файл

@ -1,188 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
BaseRequestPolicy,
deserializationPolicy,
HttpClient as IHttpClient,
HttpHeaders,
HttpOperationResponse,
HttpRequestBody,
RequestPolicy,
RequestPolicyFactory,
RequestPolicyOptions,
ServiceClientOptions,
WebResource,
proxyPolicy,
isNode,
TokenCredential,
isTokenCredential,
bearerTokenAuthenticationPolicy,
tracingPolicy,
logPolicy,
ProxyOptions,
KeepAliveOptions,
UserAgentOptions,
generateClientRequestIdPolicy,
keepAlivePolicy,
} from "@azure/core-http";
import { logger } from "./log";
import { StorageBrowserPolicyFactory } from "./StorageBrowserPolicyFactory";
import { StorageRetryOptions, StorageRetryPolicyFactory } from "./StorageRetryPolicyFactory";
import { TelemetryPolicyFactory } from "./TelemetryPolicyFactory";
import { StorageSharedKeyCredential } from "./credentials/StorageSharedKeyCredential";
import { AnonymousCredential } from "./credentials/AnonymousCredential";
import {
StorageOAuthScopes,
StorageQueueLoggingAllowedHeaderNames,
StorageQueueLoggingAllowedQueryParameters,
} from "./utils/constants";
import { getCachedDefaultHttpClient } from "./utils/cache";
// Export following interfaces and types for customers who want to implement their
// own RequestPolicy or HTTPClient
export {
BaseRequestPolicy,
StorageOAuthScopes,
deserializationPolicy,
IHttpClient,
HttpHeaders,
HttpOperationResponse,
HttpRequestBody,
WebResource,
RequestPolicyFactory,
RequestPolicy,
RequestPolicyOptions,
};
/**
* Option interface for Pipeline constructor.
*/
export interface PipelineOptions {
/**
* Optional. Configures the HTTP client to send requests and receive responses.
*/
httpClient?: IHttpClient;
}
/**
* A Pipeline class containing HTTP request policies.
* You can create a default Pipeline by calling newPipeline().
* Or you can create a Pipeline with your own policies by the constructor of Pipeline.
* Refer to newPipeline() and provided policies as reference before
* implementing your customized Pipeline.
*/
export class Pipeline {
/**
* A list of chained request policy factories.
*/
public readonly factories: RequestPolicyFactory[];
/**
* Configures pipeline logger and HTTP client.
*/
public readonly options: PipelineOptions;
/**
* Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface.
*
* @param factories -
* @param options -
*/
constructor(factories: RequestPolicyFactory[], options: PipelineOptions = {}) {
this.factories = factories;
// when options.httpClient is not specified, passing in a DefaultHttpClient instance to
// avoid each client creating its own http client.
this.options = {
...options,
httpClient: options.httpClient || getCachedDefaultHttpClient(),
};
}
/**
* Transfers Pipeline object to ServiceClientOptions object which required by
* ServiceClient constructor.
*
* @returns The ServiceClientOptions object from this Pipeline.
*/
public toServiceClientOptions(): ServiceClientOptions {
return {
httpClient: this.options.httpClient,
requestPolicyFactories: this.factories,
};
}
}
/**
* Option interface for newPipeline() method.
*/
export interface StoragePipelineOptions {
/**
* Options to configure a proxy for outgoing requests.
*/
proxyOptions?: ProxyOptions;
/**
* Options for adding user agent details to outgoing requests.
*/
userAgentOptions?: UserAgentOptions;
/**
* Configures the built-in retry policy behavior.
*/
retryOptions?: StorageRetryOptions;
/**
* Keep alive configurations. Default keep-alive is enabled.
*/
keepAliveOptions?: KeepAliveOptions;
/**
* Configures the HTTP client to send requests and receive responses.
*/
httpClient?: IHttpClient;
}
/**
* Creates a new Pipeline object with Credential provided.
*
* @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used.
* @param pipelineOptions - Options.
* @returns A new Pipeline object.
*/
export function newPipeline(
credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential,
pipelineOptions: StoragePipelineOptions = {}
): Pipeline {
if (credential === undefined) {
credential = new AnonymousCredential();
}
// Order is important. Closer to the API at the top & closer to the network at the bottom.
// The credential's policy factory must appear close to the wire so it can sign any
// changes made by other factories (like UniqueRequestIDPolicyFactory)
const telemetryPolicy = new TelemetryPolicyFactory(pipelineOptions.userAgentOptions);
const factories: RequestPolicyFactory[] = [
tracingPolicy({ userAgent: telemetryPolicy.telemetryString }),
keepAlivePolicy(pipelineOptions.keepAliveOptions),
telemetryPolicy,
generateClientRequestIdPolicy(),
new StorageBrowserPolicyFactory(),
new StorageRetryPolicyFactory(pipelineOptions.retryOptions), // Retry policy should be above any policy that throws retryable errors
deserializationPolicy(), // Default deserializationPolicy is provided by protocol layer
logPolicy({
logger: logger.info,
allowedHeaderNames: StorageQueueLoggingAllowedHeaderNames,
allowedQueryParameters: StorageQueueLoggingAllowedQueryParameters,
}),
];
if (isNode) {
// ProxyPolicy is only available in Node.js runtime, not in browsers
factories.push(proxyPolicy(pipelineOptions.proxyOptions));
}
factories.push(
isTokenCredential(credential)
? bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes)
: credential
);
return new Pipeline(factories, pipelineOptions);
}

Просмотреть файл

@ -1,15 +1,8 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
HttpResponse,
TokenCredential,
isTokenCredential,
isNode,
getDefaultProxySettings,
URLBuilder,
RequestOptionsBase,
} from "@azure/core-http";
import { TokenCredential, isTokenCredential } from "@azure/core-auth";
import { isNode } from "@azure/core-util";
import { SpanStatusCode } from "@azure/core-tracing";
import {
EnqueuedMessage,
@ -21,34 +14,44 @@ import {
MessageIdDeleteResponse,
MessagesClearResponse,
PeekedMessageItem,
QueueCreateResponse,
QueueCreateHeaders,
QueueDeleteResponse,
QueueGetAccessPolicyHeaders,
QueueGetPropertiesResponse,
QueueSetAccessPolicyResponse,
QueueSetMetadataResponse,
SignedIdentifierModel,
QueueCreateResponse,
QueueDeleteHeaders,
QueueSetMetadataHeaders,
QueueGetPropertiesHeaders,
QueueSetAccessPolicyHeaders,
MessagesClearHeaders,
MessageIdDeleteHeaders,
MessageIdUpdateHeaders,
} from "./generatedModels";
import { AbortSignalLike } from "@azure/abort-controller";
import { Messages, MessageId, Queue } from "./generated/src/operations";
import { newPipeline, StoragePipelineOptions, Pipeline } from "./Pipeline";
import { StorageClient, CommonOptions } from "./StorageClient";
import { Messages, MessageId, Queue } from "./generated/src/operationsInterfaces";
import { newPipeline, StoragePipelineOptions, Pipeline } from "../../storage-blob/src/Pipeline";
import { StorageClient, CommonOptions, getStorageClientContext } from "./StorageClient";
import {
appendToURLPath,
extractConnectionStringParts,
isIpEndpointStyle,
truncatedISO8061Date,
getStorageClientContext,
appendToURLQuery,
WithResponse,
assertResponse,
} from "./utils/utils.common";
import { StorageSharedKeyCredential } from "./credentials/StorageSharedKeyCredential";
import { AnonymousCredential } from "./credentials/AnonymousCredential";
import { StorageSharedKeyCredential } from "../../storage-blob/src/credentials/StorageSharedKeyCredential";
import { AnonymousCredential } from "../../storage-blob/src/credentials/AnonymousCredential";
import { createSpan } from "./utils/tracing";
import { Metadata } from "./models";
import { generateQueueSASQueryParameters } from "./QueueSASSignatureValues";
import { SasIPRange } from "./SasIPRange";
import { QueueSASPermissions } from "./QueueSASPermissions";
import { SASProtocol } from "./SASQueryParameters";
import { getDefaultProxySettings } from "@azure/core-rest-pipeline";
/**
* Options to configure {@link QueueClient.create} operation
@ -163,27 +166,13 @@ export interface SignedIdentifier {
/**
* Contains response data for the {@link QueueClient.getAccessPolicy} operation.
*/
export declare type QueueGetAccessPolicyResponse = {
signedIdentifiers: SignedIdentifier[];
} & QueueGetAccessPolicyHeaders & {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: QueueGetAccessPolicyHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SignedIdentifierModel[];
};
};
export declare type QueueGetAccessPolicyResponse = WithResponse<
{
signedIdentifiers: SignedIdentifier[];
} & QueueGetAccessPolicyHeaders,
QueueGetAccessPolicyHeaders,
SignedIdentifierModel[]
>;
/**
* Options to configure {@link QueueClient.clearMessages} operation
@ -197,7 +186,7 @@ export interface QueueClearMessagesOptions extends CommonOptions {
}
/** Optional parameters. */
export interface MessagesEnqueueOptionalParams extends RequestOptionsBase {
export interface MessagesEnqueueOptionalParams extends CommonOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations">Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -214,7 +203,7 @@ export interface MessagesEnqueueOptionalParams extends RequestOptionsBase {
export interface QueueSendMessageOptions extends MessagesEnqueueOptionalParams, CommonOptions {}
/** Optional parameters. */
export interface MessagesDequeueOptionalParams extends RequestOptionsBase {
export interface MessagesDequeueOptionalParams extends CommonOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations">Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -231,7 +220,7 @@ export interface MessagesDequeueOptionalParams extends RequestOptionsBase {
export interface QueueReceiveMessageOptions extends MessagesDequeueOptionalParams, CommonOptions {}
/** Optional parameters. */
export interface MessagesPeekOptionalParams extends RequestOptionsBase {
export interface MessagesPeekOptionalParams extends CommonOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations">Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -248,51 +237,37 @@ export interface QueuePeekMessagesOptions extends MessagesPeekOptionalParams, Co
/**
* Contains the response data for the {@link QueueClient.sendMessage} operation.
*/
export declare type QueueSendMessageResponse = {
/**
* The ID of the sent Message.
*/
messageId: string;
/**
* This value is required to delete the Message.
* If deletion fails using this popreceipt then the message has been received
* by another client.
*/
popReceipt: string;
/**
* The time that the message was inserted into the
* Queue.
*/
insertedOn: Date;
/**
* The time that the message will expire and be
* automatically deleted.
*/
expiresOn: Date;
/**
* The time that the message will again become
* visible in the Queue.
*/
nextVisibleOn: Date;
} & MessagesEnqueueHeaders & {
export declare type QueueSendMessageResponse = WithResponse<
{
/**
* The underlying HTTP response.
* The ID of the sent Message.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: MessagesEnqueueHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EnqueuedMessage[];
};
};
messageId: string;
/**
* This value is required to delete the Message.
* If deletion fails using this popreceipt then the message has been received
* by another client.
*/
popReceipt: string;
/**
* The time that the message was inserted into the
* Queue.
*/
insertedOn: Date;
/**
* The time that the message will expire and be
* automatically deleted.
*/
expiresOn: Date;
/**
* The time that the message will again become
* visible in the Queue.
*/
nextVisibleOn: Date;
} & MessagesEnqueueHeaders,
MessagesEnqueueHeaders,
EnqueuedMessage[]
>;
/**
* The object returned in the `receivedMessageItems` array when calling {@link QueueClient.receiveMessages}.
@ -304,52 +279,24 @@ export declare type ReceivedMessageItem = DequeuedMessageItem;
/**
* Contains the response data for the {@link QueueClient.receiveMessages} operation.
*/
export declare type QueueReceiveMessageResponse = {
receivedMessageItems: ReceivedMessageItem[];
} & MessagesDequeueHeaders & {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: MessagesDequeueHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ReceivedMessageItem[];
};
};
export declare type QueueReceiveMessageResponse = WithResponse<
{
receivedMessageItems: ReceivedMessageItem[];
} & MessagesDequeueHeaders,
MessagesDequeueHeaders,
ReceivedMessageItem[]
>;
/**
* Contains the response data for the {@link QueueClient.peekMessages} operation.
*/
export declare type QueuePeekMessagesResponse = {
peekedMessageItems: PeekedMessageItem[];
} & MessagesPeekHeaders & {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: MessagesPeekHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PeekedMessageItem[];
};
};
export declare type QueuePeekMessagesResponse = WithResponse<
{
peekedMessageItems: PeekedMessageItem[];
} & MessagesPeekHeaders,
MessagesPeekHeaders,
PeekedMessageItem[]
>;
/**
* Options to configure the {@link QueueClient.deleteMessage} operation
@ -549,7 +496,7 @@ export class QueueClient extends StorageClient {
typeof credentialOrPipelineOrQueueName !== "string"
) {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
// The second paramter is undefined. Use anonymous credential.
// The second parameter is undefined. Use anonymous credential.
url = urlOrConnectionString;
pipeline = newPipeline(new AnonymousCredential(), options);
} else if (
@ -589,7 +536,7 @@ export class QueueClient extends StorageClient {
}
super(url, pipeline);
this._name = this.getQueueNameFromUrl();
this.queueContext = new Queue(this.storageClientContext);
this.queueContext = this.storageClientContext.queue;
// MessagesContext
// Build the url with "messages"
@ -598,7 +545,7 @@ export class QueueClient extends StorageClient {
? appendToURLPath(partsOfUrl[0], "messages") + "?" + partsOfUrl[1]
: appendToURLPath(partsOfUrl[0], "messages");
this.messagesContext = new Messages(getStorageClientContext(this._messagesUrl, this.pipeline));
this.messagesContext = getStorageClientContext(this._messagesUrl, this.pipeline).messages;
}
private getMessageIdContext(messageId: string): MessageId {
@ -608,7 +555,7 @@ export class QueueClient extends StorageClient {
? appendToURLPath(partsOfUrl[0], messageId) + "?" + partsOfUrl[1]
: appendToURLPath(partsOfUrl[0], messageId);
return new MessageId(getStorageClientContext(urlWithMessageId, this.pipeline));
return getStorageClientContext(urlWithMessageId, this.pipeline).messageId;
}
/**
@ -628,10 +575,9 @@ export class QueueClient extends StorageClient {
public async create(options: QueueCreateOptions = {}): Promise<QueueCreateResponse> {
const { span, updatedOptions } = createSpan("QueueClient-create", options);
try {
return await this.queueContext.create({
...updatedOptions,
abortSignal: options.abortSignal,
});
return assertResponse<QueueCreateHeaders, QueueCreateHeaders>(
await this.queueContext.create(updatedOptions)
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -750,10 +696,12 @@ export class QueueClient extends StorageClient {
public async delete(options: QueueDeleteOptions = {}): Promise<QueueDeleteResponse> {
const { span, updatedOptions } = createSpan("QueueClient-delete", options);
try {
return await this.queueContext.delete({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<QueueDeleteHeaders, QueueDeleteHeaders>(
await this.queueContext.delete({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -818,10 +766,12 @@ export class QueueClient extends StorageClient {
): Promise<QueueGetPropertiesResponse> {
const { span, updatedOptions } = createSpan("QueueClient-getProperties", options);
try {
return await this.queueContext.getProperties({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<QueueGetPropertiesHeaders, QueueGetPropertiesHeaders>(
await this.queueContext.getProperties({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -850,11 +800,13 @@ export class QueueClient extends StorageClient {
): Promise<QueueSetMetadataResponse> {
const { span, updatedOptions } = createSpan("QueueClient-setMetadata", options);
try {
return await this.queueContext.setMetadata({
abortSignal: options.abortSignal,
metadata,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<QueueSetMetadataHeaders, QueueSetMetadataHeaders>(
await this.queueContext.setMetadata({
abortSignal: options.abortSignal,
metadata,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -882,10 +834,16 @@ export class QueueClient extends StorageClient {
): Promise<QueueGetAccessPolicyResponse> {
const { span, updatedOptions } = createSpan("QueueClient-getAccessPolicy", options);
try {
const response = await this.queueContext.getAccessPolicy({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
const response = assertResponse<
QueueGetAccessPolicyHeaders & SignedIdentifierModel[],
QueueGetAccessPolicyHeaders,
SignedIdentifierModel[]
>(
await this.queueContext.getAccessPolicy({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
})
);
const res: QueueGetAccessPolicyResponse = {
_response: response._response,
@ -961,11 +919,13 @@ export class QueueClient extends StorageClient {
});
}
return await this.queueContext.setAccessPolicy({
abortSignal: options.abortSignal,
queueAcl: acl,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<QueueSetAccessPolicyHeaders, QueueSetAccessPolicyHeaders>(
await this.queueContext.setAccessPolicy({
abortSignal: options.abortSignal,
queueAcl: acl,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -989,10 +949,12 @@ export class QueueClient extends StorageClient {
): Promise<QueueClearMessagesResponse> {
const { span, updatedOptions } = createSpan("QueueClient-clearMessages", options);
try {
return await this.messagesContext.clear({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<MessagesClearHeaders, MessagesClearHeaders>(
await this.messagesContext.clear({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -1031,11 +993,17 @@ export class QueueClient extends StorageClient {
): Promise<QueueSendMessageResponse> {
const { span, updatedOptions } = createSpan("QueueClient-sendMessage", options);
try {
const response = await this.messagesContext.enqueue(
{
messageText: messageText,
},
updatedOptions
const response = assertResponse<
MessagesEnqueueHeaders & EnqueuedMessage[],
MessagesEnqueueHeaders,
EnqueuedMessage[]
>(
await this.messagesContext.enqueue(
{
messageText: messageText,
},
updatedOptions
)
);
const item = response[0];
return {
@ -1092,7 +1060,11 @@ export class QueueClient extends StorageClient {
): Promise<QueueReceiveMessageResponse> {
const { span, updatedOptions } = createSpan("QueueClient-receiveMessages", options);
try {
const response = await this.messagesContext.dequeue(updatedOptions);
const response = assertResponse<
MessagesDequeueHeaders & DequeuedMessageItem[],
MessagesDequeueHeaders,
DequeuedMessageItem[]
>(await this.messagesContext.dequeue(updatedOptions));
const res: QueueReceiveMessageResponse = {
_response: response._response,
@ -1139,7 +1111,11 @@ export class QueueClient extends StorageClient {
): Promise<QueuePeekMessagesResponse> {
const { span, updatedOptions } = createSpan("QueueClient-peekMessages", options);
try {
const response = await this.messagesContext.peek(updatedOptions);
const response = assertResponse<
MessagesPeekHeaders & PeekedMessageItem[],
MessagesPeekHeaders,
PeekedMessageItem[]
>(await this.messagesContext.peek(updatedOptions));
const res: QueuePeekMessagesResponse = {
_response: response._response,
@ -1183,10 +1159,12 @@ export class QueueClient extends StorageClient {
): Promise<QueueDeleteMessageResponse> {
const { span, updatedOptions } = createSpan("QueueClient-deleteMessage", options);
try {
return await this.getMessageIdContext(messageId).delete(popReceipt, {
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<MessageIdDeleteHeaders, MessageIdDeleteHeaders>(
await this.getMessageIdContext(messageId).delete(popReceipt, {
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -1229,11 +1207,13 @@ export class QueueClient extends StorageClient {
}
try {
return await this.getMessageIdContext(messageId).update(popReceipt, visibilityTimeout || 0, {
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
queueMessage,
});
return assertResponse<MessageIdUpdateHeaders, MessageIdUpdateHeaders>(
await this.getMessageIdContext(messageId).update(popReceipt, visibilityTimeout || 0, {
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
queueMessage,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -1254,21 +1234,21 @@ export class QueueClient extends StorageClient {
// IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10001/devstoreaccount1/myqueue`
// http://localhost:10001/devstoreaccount1/queuename
const parsedUrl = URLBuilder.parse(this.url);
const parsedUrl = new URL(this.url);
if (parsedUrl.getHost()!.split(".")[1] === "queue") {
if (parsedUrl.hostname.split(".")[1] === "queue") {
// "https://myaccount.queue.core.windows.net/queuename".
// .getPath() -> /queuename
queueName = parsedUrl.getPath()!.split("/")[1];
queueName = parsedUrl.pathname.split("/")[1];
} else if (isIpEndpointStyle(parsedUrl)) {
// IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/queuename
// Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/queuename
// .getPath() -> /devstoreaccount1/queuename
queueName = parsedUrl.getPath()!.split("/")[2];
queueName = parsedUrl.pathname.split("/")[2];
} else {
// "https://customdomain.com/queuename".
// .getPath() -> /queuename
queueName = parsedUrl.getPath()!.split("/")[1];
queueName = parsedUrl.pathname.split("/")[1];
}
if (!queueName) {

Просмотреть файл

@ -2,7 +2,7 @@
// Licensed under the MIT license.
import { QueueSASPermissions } from "./QueueSASPermissions";
import { StorageSharedKeyCredential } from "./credentials/StorageSharedKeyCredential";
import { StorageSharedKeyCredential } from "../../storage-blob/src/credentials/StorageSharedKeyCredential";
import { SasIPRange, ipRangeToString } from "./SasIPRange";
import { SASProtocol } from "./SASQueryParameters";
import { SASQueryParameters } from "./SASQueryParameters";

Просмотреть файл

@ -1,12 +1,8 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
TokenCredential,
isTokenCredential,
isNode,
getDefaultProxySettings,
} from "@azure/core-http";
import { TokenCredential, isTokenCredential } from "@azure/core-auth";
import { isNode } from "@azure/core-util";
import { SpanStatusCode } from "@azure/core-tracing";
import {
QueueCreateResponse,
@ -14,13 +10,19 @@ import {
QueueItem,
QueueServiceProperties,
ServiceGetPropertiesResponse,
ServiceGetPropertiesHeaders,
ServiceGetStatisticsResponse,
ServiceListQueuesSegmentResponse,
ServiceSetPropertiesResponse,
ServiceListQueuesSegmentHeaders,
ListQueuesSegmentResponse,
ServiceSetPropertiesHeaders,
ServiceGetStatisticsHeaders,
QueueServiceStatistics,
} from "./generatedModels";
import { AbortSignalLike } from "@azure/abort-controller";
import { Service } from "./generated/src/operations";
import { newPipeline, StoragePipelineOptions, Pipeline } from "./Pipeline";
import { Service } from "./generated/src/operationsInterfaces";
import { newPipeline, StoragePipelineOptions, Pipeline } from "../../storage-blob/src/Pipeline";
import { StorageClient, CommonOptions } from "./StorageClient";
import "@azure/core-paging";
import { PageSettings, PagedAsyncIterableIterator } from "@azure/core-paging";
@ -28,9 +30,10 @@ import {
appendToURLPath,
appendToURLQuery,
extractConnectionStringParts,
assertResponse,
} from "./utils/utils.common";
import { StorageSharedKeyCredential } from "./credentials/StorageSharedKeyCredential";
import { AnonymousCredential } from "./credentials/AnonymousCredential";
import { StorageSharedKeyCredential } from "../../storage-blob/src/credentials/StorageSharedKeyCredential";
import { AnonymousCredential } from "../../storage-blob/src/credentials/AnonymousCredential";
import { createSpan } from "./utils/tracing";
import { QueueClient, QueueCreateOptions, QueueDeleteOptions } from "./QueueClient";
import { AccountSASPermissions } from "./AccountSASPermissions";
@ -38,6 +41,7 @@ import { generateAccountSASQueryParameters } from "./AccountSASSignatureValues";
import { AccountSASServices } from "./AccountSASServices";
import { SASProtocol } from "./SASQueryParameters";
import { SasIPRange } from "./SasIPRange";
import { getDefaultProxySettings } from "@azure/core-rest-pipeline";
/**
* Options to configure {@link QueueServiceClient.getProperties} operation
@ -286,11 +290,11 @@ export class QueueServiceClient extends StorageClient {
) {
pipeline = newPipeline(credentialOrPipeline, options);
} else {
// The second paramter is undefined. Use anonymous credential.
// The second parameter is undefined. Use anonymous credential.
pipeline = newPipeline(new AnonymousCredential(), options);
}
super(url, pipeline);
this.serviceContext = new Service(this.storageClientContext);
this.serviceContext = this.storageClientContext.service;
}
/**
@ -335,14 +339,20 @@ export class QueueServiceClient extends StorageClient {
}
try {
return await this.serviceContext.listQueuesSegment({
abortSignal: options.abortSignal,
marker: marker,
maxPageSize: options.maxPageSize,
prefix: options.prefix,
include: options.include === undefined ? undefined : [options.include],
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<
ServiceListQueuesSegmentHeaders & ListQueuesSegmentResponse,
ServiceListQueuesSegmentHeaders,
ListQueuesSegmentResponse
>(
await this.serviceContext.listQueuesSegment({
abortSignal: options.abortSignal,
marker: marker,
maxPageSize: options.maxPageSize,
prefix: options.prefix,
include: options.include === undefined ? undefined : [options.include],
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -531,10 +541,16 @@ export class QueueServiceClient extends StorageClient {
): Promise<ServiceGetPropertiesResponse> {
const { span, updatedOptions } = createSpan("QueueServiceClient-getProperties", options);
try {
return await this.serviceContext.getProperties({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<
ServiceGetPropertiesHeaders & QueueServiceProperties,
ServiceGetPropertiesHeaders,
QueueServiceProperties
>(
await this.serviceContext.getProperties({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -561,10 +577,12 @@ export class QueueServiceClient extends StorageClient {
): Promise<ServiceSetPropertiesResponse> {
const { span, updatedOptions } = createSpan("QueueServiceClient-setProperties", options);
try {
return await this.serviceContext.setProperties(properties, {
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<ServiceSetPropertiesHeaders, ServiceSetPropertiesHeaders>(
await this.serviceContext.setProperties(properties, {
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,
@ -590,10 +608,16 @@ export class QueueServiceClient extends StorageClient {
): Promise<ServiceGetStatisticsResponse> {
const { span, updatedOptions } = createSpan("QueueServiceClient-getStatistics", options);
try {
return await this.serviceContext.getStatistics({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
});
return assertResponse<
ServiceGetStatisticsHeaders & QueueServiceStatistics,
ServiceGetStatisticsHeaders,
QueueServiceStatistics
>(
await this.serviceContext.getStatistics({
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions,
})
);
} catch (e: any) {
span.setStatus({
code: SpanStatusCode.ERROR,

Просмотреть файл

@ -1,21 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/core-http";
import { StorageBrowserPolicy } from "./policies/StorageBrowserPolicy";
export { StorageBrowserPolicy };
/**
* StorageBrowserPolicyFactory is a factory class helping generating {@link StorageBrowserPolicy} objects.
*/
export class StorageBrowserPolicyFactory implements RequestPolicyFactory {
/**
* Creates a StorageBrowserPolicyFactory object.
*
* @param nextPolicy -
* @param options -
*/
public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): StorageBrowserPolicy {
return new StorageBrowserPolicy(nextPolicy, options);
}
}

Просмотреть файл

@ -1,14 +1,20 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { StorageClientContext } from "./generated/src/storageClientContext";
import { Pipeline } from "./Pipeline";
import { getAccountNameFromUrl, getStorageClientContext } from "./utils/utils.common";
import { StorageClient as StorageClientContext } from "./generated/src/";
import { StorageContextClient } from "./StorageContextClient";
import {
Pipeline,
StoragePipelineOptions,
getCoreClientOptions,
getCredentialFromPipeline,
} from "../../storage-blob/src/Pipeline";
import { getAccountNameFromUrl } from "./utils/utils.common";
import { OperationTracingOptions } from "@azure/core-tracing";
import { Credential } from "./credentials/Credential";
import { AnonymousCredential } from "./credentials/AnonymousCredential";
import { isNode } from "@azure/core-http";
import { StorageSharedKeyCredential } from "./credentials/StorageSharedKeyCredential";
import { AnonymousCredential } from "../../storage-blob/src/credentials/AnonymousCredential";
import { StorageSharedKeyCredential } from "../../storage-blob/src/credentials/StorageSharedKeyCredential";
import { HttpClient } from "@azure/core-rest-pipeline";
import { TokenCredential } from "@azure/core-auth";
/**
* An interface for options common to every remote operation.
@ -38,12 +44,12 @@ export abstract class StorageClient {
protected readonly pipeline: Pipeline;
/**
* Credential factory in the pipleline to authenticate requests to the service, such as AnonymousCredential, StorageSharedKeyCredential.
* Credential factory in the pipeline to authenticate requests to the service, such as AnonymousCredential, StorageSharedKeyCredential.
* Initialized to an AnonymousCredential if not able to retrieve it from the pipeline.
*
* @internal
*/
protected readonly credential: Credential;
protected readonly credential: StorageSharedKeyCredential | AnonymousCredential | TokenCredential;
/**
* StorageClientContext is a reference to protocol layer operations entry, which is
@ -60,29 +66,8 @@ export abstract class StorageClient {
this.url = url;
this.accountName = getAccountNameFromUrl(url);
this.pipeline = pipeline;
this.storageClientContext = getStorageClientContext(url, pipeline);
// Retrieve credential from the pipeline.
this.credential = new AnonymousCredential();
for (const factory of this.pipeline.factories) {
if (
(isNode && factory instanceof StorageSharedKeyCredential) ||
factory instanceof AnonymousCredential
) {
this.credential = factory;
break;
} else {
try {
const authPolicy = (factory as any).create();
if (authPolicy.constructor.name === "BearerTokenAuthenticationPolicy") {
this.credential = factory;
break;
}
} catch (err: any) {
// ignore errors in creating policy, the client instance may still work without the policy.
}
}
}
this.storageClientContext = getStorageClientContext(this.url, this.pipeline);
this.credential = getCredentialFromPipeline(pipeline);
}
}
@ -96,3 +81,34 @@ export abstract class StorageClient {
* @readonly
*/
export type ListQueuesIncludeType = "metadata";
let testOnlyHttpClient: HttpClient | undefined;
/**
* @internal
* Set a custom default http client for testing purposes
*/
export function setTestOnlySetHttpClient(httpClient: HttpClient): void {
testOnlyHttpClient = httpClient;
}
/**
* @internal
*/
export function getStorageClientContext(url: string, pipeline: Pipeline): StorageClientContext {
const pipelineOptions = pipeline.options as StoragePipelineOptions;
// Set maximum timeout for queue operations.
// This was previously set manually in the retry policy specific to this package.
// https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations
if (pipelineOptions.retryOptions === undefined) {
pipelineOptions.retryOptions = {
tryTimeoutInMs: 30 * 1000,
};
} else if (pipelineOptions.retryOptions.tryTimeoutInMs === undefined) {
(pipelineOptions.retryOptions as any).tryTimeoutInMs = 30 * 1000;
}
const coreOptions = getCoreClientOptions(pipeline);
if (testOnlyHttpClient) {
coreOptions.httpClient = testOnlyHttpClient;
}
return new StorageContextClient(url, coreOptions);
}

Просмотреть файл

@ -0,0 +1,26 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { OperationArguments, OperationSpec } from "@azure/core-client";
import { StorageClient } from "./generated/src";
/**
* @internal
*/
export class StorageContextClient extends StorageClient {
async sendOperationRequest<T>(
operationArguments: OperationArguments,
operationSpec: OperationSpec
): Promise<T> {
const operationSpecToSend = { ...operationSpec };
if (
operationSpecToSend.path === "/{queueName}" ||
operationSpecToSend.path === "/{queueName}/messages" ||
operationSpecToSend.path === "/{queueName}/messages/{messageid}"
) {
operationSpecToSend.path = "";
}
return super.sendOperationRequest(operationArguments, operationSpecToSend);
}
}

Просмотреть файл

@ -1,80 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/core-http";
import { StorageRetryPolicy, StorageRetryPolicyType } from "./policies/StorageRetryPolicy";
export { StorageRetryPolicyType, StorageRetryPolicy };
/**
* Storage Queue retry options interface.
*/
export interface StorageRetryOptions {
/**
* Optional. StorageRetryPolicyType, default is exponential retry policy.
*/
readonly retryPolicyType?: StorageRetryPolicyType;
/**
* Optional. Max try number of attempts, default is 4.
* A value of 1 means 1 try and no retries.
* A value smaller than 1 means default retry number of attempts.
*/
readonly maxTries?: number;
/**
* Optional. Indicates the maximum time in ms allowed for any single try of an HTTP request.
* A value of zero or undefined means that you accept our default timeout, 30s or 30 * 1000ms.
*
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations
*/
readonly tryTimeoutInMs?: number;
/**
* Optional. Specifies the amount of delay to use before retrying an operation (default is 4s or 4 * 1000ms).
* The delay increases (exponentially or linearly) with each retry up to a maximum specified by
* maxRetryDelayInMs. If you specify 0, then you must also specify 0 for maxRetryDelayInMs.
*/
readonly retryDelayInMs?: number;
/**
* Optional. Specifies the maximum delay allowed before retrying an operation (default is 120s or 120 * 1000ms).
* If you specify 0, then you must also specify 0 for retryDelayInMs.
*/
readonly maxRetryDelayInMs?: number;
/**
* If a secondaryHost is specified, retries will be tried against this host. If secondaryHost is undefined
* (the default) then operations are not retried against another host.
*
* NOTE: Before setting this field, make sure you understand the issues around
* reading stale and potentially-inconsistent data at
* {@link https://docs.microsoft.com/en-us/azure/storage/common/storage-designing-ha-apps-with-ragrs}
*/
readonly secondaryHost?: string;
}
/**
* StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects.
*/
export class StorageRetryPolicyFactory implements RequestPolicyFactory {
private retryOptions?: StorageRetryOptions;
/**
* Creates an instance of StorageRetryPolicyFactory.
* @param retryOptions -
*/
constructor(retryOptions?: StorageRetryOptions) {
this.retryOptions = retryOptions;
}
/**
* Creates a {@link StorageRetryPolicy} object.
*
* @param nextPolicy -
* @param options -
*/
public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): StorageRetryPolicy {
return new StorageRetryPolicy(nextPolicy, options, this.retryOptions);
}
}

Просмотреть файл

@ -1,68 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
isNode,
RequestPolicy,
RequestPolicyFactory,
RequestPolicyOptions,
UserAgentOptions,
} from "@azure/core-http";
import * as os from "os";
import { TelemetryPolicy } from "./policies/TelemetryPolicy";
import { SDK_VERSION } from "./utils/constants";
/**
* TelemetryPolicyFactory is a factory class helping generating {@link TelemetryPolicy} objects.
*/
export class TelemetryPolicyFactory implements RequestPolicyFactory {
/**
* @internal
*/
public readonly telemetryString: string;
/**
* Creates an instance of TelemetryPolicyFactory.
* @param telemetry -
*/
constructor(telemetry?: UserAgentOptions) {
const userAgentInfo: string[] = [];
if (isNode) {
if (telemetry) {
const telemetryString = telemetry.userAgentPrefix || "";
if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) {
userAgentInfo.push(telemetryString);
}
}
// e.g. azsdk-js-storagequeue/11.0.0
const libInfo = `azsdk-js-storagequeue/${SDK_VERSION}`;
if (userAgentInfo.indexOf(libInfo) === -1) {
userAgentInfo.push(libInfo);
}
// e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299)
let runtimeInfo = `(NODE-VERSION ${process.version})`;
if (os) {
runtimeInfo = `(NODE-VERSION ${process.version}; ${os.type()} ${os.release()})`;
}
if (userAgentInfo.indexOf(runtimeInfo) === -1) {
userAgentInfo.push(runtimeInfo);
}
}
this.telemetryString = userAgentInfo.join(" ");
}
/**
* Creates a {@link TelemetryPolicy} object.
*
* @param nextPolicy -
* @param options -
*/
public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): TelemetryPolicy {
return new TelemetryPolicy(nextPolicy, options, this.telemetryString);
}
}

Просмотреть файл

@ -1,28 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RequestPolicy, RequestPolicyOptions } from "@azure/core-http";
import { AnonymousCredentialPolicy } from "../policies/AnonymousCredentialPolicy";
import { Credential } from "./Credential";
/**
* AnonymousCredential provides a {@link CredentialPolicyCreator} member used to create
* {@link AnonymousCredentialPolicy} objects. {@link AnonymousCredentialPolicy} is used with
* HTTP(S) requests that read public resources or for use with Shared Access
* Signatures (SAS).
*/
export class AnonymousCredential extends Credential {
/**
* Creates an {@link AnonymousCredentialPolicy} object.
*
* @param nextPolicy -
* @param options -
*/
public create(
nextPolicy: RequestPolicy,
options: RequestPolicyOptions
): AnonymousCredentialPolicy {
return new AnonymousCredentialPolicy(nextPolicy, options);
}
}

Просмотреть файл

@ -1,29 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/core-http";
import { CredentialPolicy } from "../policies/CredentialPolicy";
/**
* Credential is an abstract class for Azure Storage HTTP requests signing. This
* class will host an credentialPolicyCreator factory which generates CredentialPolicy.
*/
export abstract class Credential implements RequestPolicyFactory {
/**
* Creates a RequestPolicy object.
*
* @param _nextPolicy -
* @param _options -
*/
public create(_nextPolicy: RequestPolicy, _options: RequestPolicyOptions): RequestPolicy {
throw new Error("Method should be implemented in children classes.");
}
}
/**
* A factory function that creates a new CredentialPolicy that uses the provided nextPolicy.
*/
export type CredentialPolicyCreator = (
nextPolicy: RequestPolicy,
options: RequestPolicyOptions
) => CredentialPolicy;

Просмотреть файл

@ -1,4 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export class StorageSharedKeyCredential {}

Просмотреть файл

@ -1,58 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { createHmac } from "crypto";
import { RequestPolicy, RequestPolicyOptions } from "@azure/core-http";
import { StorageSharedKeyCredentialPolicy } from "../policies/StorageSharedKeyCredentialPolicy";
import { Credential } from "./Credential";
/**
* ONLY AVAILABLE IN NODE.JS RUNTIME.
*
* StorageSharedKeyCredential for account key authorization of Azure Storage service.
*/
export class StorageSharedKeyCredential extends Credential {
/**
* Azure Storage account name; readonly.
*/
public readonly accountName: string;
/**
* Azure Storage account key; readonly.
*/
private readonly accountKey: Buffer;
/**
* Creates an instance of StorageSharedKeyCredential.
* @param accountName -
* @param accountKey -
*/
constructor(accountName: string, accountKey: string) {
super();
this.accountName = accountName;
this.accountKey = Buffer.from(accountKey, "base64");
}
/**
* Creates a {@link StorageSharedKeyCredentialPolicy} object.
*
* @param nextPolicy -
* @param options -
*/
public create(
nextPolicy: RequestPolicy,
options: RequestPolicyOptions
): StorageSharedKeyCredentialPolicy {
return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this);
}
/**
* Generates a hash signature for an HTTP request or for a SAS.
*
* @param stringToSign -
*/
public computeHMACSHA256(stringToSign: string): string {
return createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64");
}
}

2
sdk/storage/storage-queue/src/generated/src/index.ts сгенерированный
Просмотреть файл

@ -8,4 +8,4 @@
export * from "./models";
export { StorageClient } from "./storageClient";
export { StorageClientContext } from "./storageClientContext";
export * from "./operationsInterfaces";

Просмотреть файл

@ -6,7 +6,8 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import * as coreClient from "@azure/core-client";
import * as coreHttpCompat from "@azure/core-http-compat";
/** Storage Service Properties. */
export interface QueueServiceProperties {
@ -515,63 +516,120 @@ export interface MessageIdDeleteExceptionHeaders {
}
/** Known values of {@link StorageErrorCode} that the service accepts. */
export const enum KnownStorageErrorCode {
export enum KnownStorageErrorCode {
/** AccountAlreadyExists */
AccountAlreadyExists = "AccountAlreadyExists",
/** AccountBeingCreated */
AccountBeingCreated = "AccountBeingCreated",
/** AccountIsDisabled */
AccountIsDisabled = "AccountIsDisabled",
/** AuthenticationFailed */
AuthenticationFailed = "AuthenticationFailed",
/** AuthorizationFailure */
AuthorizationFailure = "AuthorizationFailure",
/** ConditionHeadersNotSupported */
ConditionHeadersNotSupported = "ConditionHeadersNotSupported",
/** ConditionNotMet */
ConditionNotMet = "ConditionNotMet",
/** EmptyMetadataKey */
EmptyMetadataKey = "EmptyMetadataKey",
/** InsufficientAccountPermissions */
InsufficientAccountPermissions = "InsufficientAccountPermissions",
/** InternalError */
InternalError = "InternalError",
/** InvalidAuthenticationInfo */
InvalidAuthenticationInfo = "InvalidAuthenticationInfo",
/** InvalidHeaderValue */
InvalidHeaderValue = "InvalidHeaderValue",
/** InvalidHttpVerb */
InvalidHttpVerb = "InvalidHttpVerb",
/** InvalidInput */
InvalidInput = "InvalidInput",
/** InvalidMd5 */
InvalidMd5 = "InvalidMd5",
/** InvalidMetadata */
InvalidMetadata = "InvalidMetadata",
/** InvalidQueryParameterValue */
InvalidQueryParameterValue = "InvalidQueryParameterValue",
/** InvalidRange */
InvalidRange = "InvalidRange",
/** InvalidResourceName */
InvalidResourceName = "InvalidResourceName",
/** InvalidUri */
InvalidUri = "InvalidUri",
/** InvalidXmlDocument */
InvalidXmlDocument = "InvalidXmlDocument",
/** InvalidXmlNodeValue */
InvalidXmlNodeValue = "InvalidXmlNodeValue",
/** Md5Mismatch */
Md5Mismatch = "Md5Mismatch",
/** MetadataTooLarge */
MetadataTooLarge = "MetadataTooLarge",
/** MissingContentLengthHeader */
MissingContentLengthHeader = "MissingContentLengthHeader",
/** MissingRequiredQueryParameter */
MissingRequiredQueryParameter = "MissingRequiredQueryParameter",
/** MissingRequiredHeader */
MissingRequiredHeader = "MissingRequiredHeader",
/** MissingRequiredXmlNode */
MissingRequiredXmlNode = "MissingRequiredXmlNode",
/** MultipleConditionHeadersNotSupported */
MultipleConditionHeadersNotSupported = "MultipleConditionHeadersNotSupported",
/** OperationTimedOut */
OperationTimedOut = "OperationTimedOut",
/** OutOfRangeInput */
OutOfRangeInput = "OutOfRangeInput",
/** OutOfRangeQueryParameterValue */
OutOfRangeQueryParameterValue = "OutOfRangeQueryParameterValue",
/** RequestBodyTooLarge */
RequestBodyTooLarge = "RequestBodyTooLarge",
/** ResourceTypeMismatch */
ResourceTypeMismatch = "ResourceTypeMismatch",
/** RequestUrlFailedToParse */
RequestUrlFailedToParse = "RequestUrlFailedToParse",
/** ResourceAlreadyExists */
ResourceAlreadyExists = "ResourceAlreadyExists",
/** ResourceNotFound */
ResourceNotFound = "ResourceNotFound",
/** ServerBusy */
ServerBusy = "ServerBusy",
/** UnsupportedHeader */
UnsupportedHeader = "UnsupportedHeader",
/** UnsupportedXmlNode */
UnsupportedXmlNode = "UnsupportedXmlNode",
/** UnsupportedQueryParameter */
UnsupportedQueryParameter = "UnsupportedQueryParameter",
/** UnsupportedHttpVerb */
UnsupportedHttpVerb = "UnsupportedHttpVerb",
/** InvalidMarker */
InvalidMarker = "InvalidMarker",
/** MessageNotFound */
MessageNotFound = "MessageNotFound",
/** MessageTooLarge */
MessageTooLarge = "MessageTooLarge",
/** PopReceiptMismatch */
PopReceiptMismatch = "PopReceiptMismatch",
/** QueueAlreadyExists */
QueueAlreadyExists = "QueueAlreadyExists",
/** QueueBeingDeleted */
QueueBeingDeleted = "QueueBeingDeleted",
/** QueueDisabled */
QueueDisabled = "QueueDisabled",
/** QueueNotEmpty */
QueueNotEmpty = "QueueNotEmpty",
/** QueueNotFound */
QueueNotFound = "QueueNotFound",
/** AuthorizationSourceIPMismatch */
AuthorizationSourceIPMismatch = "AuthorizationSourceIPMismatch",
/** AuthorizationProtocolMismatch */
AuthorizationProtocolMismatch = "AuthorizationProtocolMismatch",
/** AuthorizationPermissionMismatch */
AuthorizationPermissionMismatch = "AuthorizationPermissionMismatch",
/** AuthorizationServiceMismatch */
AuthorizationServiceMismatch = "AuthorizationServiceMismatch",
/** AuthorizationResourceTypeMismatch */
AuthorizationResourceTypeMismatch = "AuthorizationResourceTypeMismatch",
/** FeatureVersionMismatch */
FeatureVersionMismatch = "FeatureVersionMismatch"
}
@ -579,7 +637,7 @@ export const enum KnownStorageErrorCode {
* Defines values for StorageErrorCode. \
* {@link KnownStorageErrorCode} can be used interchangeably with StorageErrorCode,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* ### Known values supported by the service
* **AccountAlreadyExists** \
* **AccountBeingCreated** \
* **AccountIsDisabled** \
@ -644,7 +702,7 @@ export type GeoReplicationStatusType = "live" | "bootstrap" | "unavailable";
/** Optional parameters. */
export interface ServiceSetPropertiesOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -652,17 +710,11 @@ export interface ServiceSetPropertiesOptionalParams
}
/** Contains response data for the setProperties operation. */
export type ServiceSetPropertiesResponse = ServiceSetPropertiesHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: ServiceSetPropertiesHeaders;
};
};
export type ServiceSetPropertiesResponse = ServiceSetPropertiesHeaders;
/** Optional parameters. */
export interface ServiceGetPropertiesOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -671,22 +723,11 @@ export interface ServiceGetPropertiesOptionalParams
/** Contains response data for the getProperties operation. */
export type ServiceGetPropertiesResponse = ServiceGetPropertiesHeaders &
QueueServiceProperties & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: QueueServiceProperties;
/** The parsed HTTP response headers. */
parsedHeaders: ServiceGetPropertiesHeaders;
};
};
QueueServiceProperties;
/** Optional parameters. */
export interface ServiceGetStatisticsOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -695,22 +736,11 @@ export interface ServiceGetStatisticsOptionalParams
/** Contains response data for the getStatistics operation. */
export type ServiceGetStatisticsResponse = ServiceGetStatisticsHeaders &
QueueServiceStatistics & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: QueueServiceStatistics;
/** The parsed HTTP response headers. */
parsedHeaders: ServiceGetStatisticsHeaders;
};
};
QueueServiceStatistics;
/** Optional parameters. */
export interface ServiceListQueuesSegmentOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -727,21 +757,10 @@ export interface ServiceListQueuesSegmentOptionalParams
/** Contains response data for the listQueuesSegment operation. */
export type ServiceListQueuesSegmentResponse = ServiceListQueuesSegmentHeaders &
ListQueuesSegmentResponse & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: ListQueuesSegmentResponse;
/** The parsed HTTP response headers. */
parsedHeaders: ServiceListQueuesSegmentHeaders;
};
};
ListQueuesSegmentResponse;
/** Optional parameters. */
export interface QueueCreateOptionalParams extends coreHttp.OperationOptions {
export interface QueueCreateOptionalParams extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -751,16 +770,10 @@ export interface QueueCreateOptionalParams extends coreHttp.OperationOptions {
}
/** Contains response data for the create operation. */
export type QueueCreateResponse = QueueCreateHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: QueueCreateHeaders;
};
};
export type QueueCreateResponse = QueueCreateHeaders;
/** Optional parameters. */
export interface QueueDeleteOptionalParams extends coreHttp.OperationOptions {
export interface QueueDeleteOptionalParams extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -768,17 +781,11 @@ export interface QueueDeleteOptionalParams extends coreHttp.OperationOptions {
}
/** Contains response data for the delete operation. */
export type QueueDeleteResponse = QueueDeleteHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: QueueDeleteHeaders;
};
};
export type QueueDeleteResponse = QueueDeleteHeaders;
/** Optional parameters. */
export interface QueueGetPropertiesOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -786,17 +793,11 @@ export interface QueueGetPropertiesOptionalParams
}
/** Contains response data for the getProperties operation. */
export type QueueGetPropertiesResponse = QueueGetPropertiesHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: QueueGetPropertiesHeaders;
};
};
export type QueueGetPropertiesResponse = QueueGetPropertiesHeaders;
/** Optional parameters. */
export interface QueueSetMetadataOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -806,17 +807,11 @@ export interface QueueSetMetadataOptionalParams
}
/** Contains response data for the setMetadata operation. */
export type QueueSetMetadataResponse = QueueSetMetadataHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: QueueSetMetadataHeaders;
};
};
export type QueueSetMetadataResponse = QueueSetMetadataHeaders;
/** Optional parameters. */
export interface QueueGetAccessPolicyOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -825,22 +820,11 @@ export interface QueueGetAccessPolicyOptionalParams
/** Contains response data for the getAccessPolicy operation. */
export type QueueGetAccessPolicyResponse = QueueGetAccessPolicyHeaders &
SignedIdentifier[] & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: SignedIdentifier[];
/** The parsed HTTP response headers. */
parsedHeaders: QueueGetAccessPolicyHeaders;
};
};
SignedIdentifier[];
/** Optional parameters. */
export interface QueueSetAccessPolicyOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -850,17 +834,11 @@ export interface QueueSetAccessPolicyOptionalParams
}
/** Contains response data for the setAccessPolicy operation. */
export type QueueSetAccessPolicyResponse = QueueSetAccessPolicyHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: QueueSetAccessPolicyHeaders;
};
};
export type QueueSetAccessPolicyResponse = QueueSetAccessPolicyHeaders;
/** Optional parameters. */
export interface MessagesDequeueOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -873,21 +851,11 @@ export interface MessagesDequeueOptionalParams
/** Contains response data for the dequeue operation. */
export type MessagesDequeueResponse = MessagesDequeueHeaders &
DequeuedMessageItem[] & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: DequeuedMessageItem[];
/** The parsed HTTP response headers. */
parsedHeaders: MessagesDequeueHeaders;
};
};
DequeuedMessageItem[];
/** Optional parameters. */
export interface MessagesClearOptionalParams extends coreHttp.OperationOptions {
export interface MessagesClearOptionalParams
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -895,17 +863,11 @@ export interface MessagesClearOptionalParams extends coreHttp.OperationOptions {
}
/** Contains response data for the clear operation. */
export type MessagesClearResponse = MessagesClearHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: MessagesClearHeaders;
};
};
export type MessagesClearResponse = MessagesClearHeaders;
/** Optional parameters. */
export interface MessagesEnqueueOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -918,21 +880,11 @@ export interface MessagesEnqueueOptionalParams
/** Contains response data for the enqueue operation. */
export type MessagesEnqueueResponse = MessagesEnqueueHeaders &
EnqueuedMessage[] & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: EnqueuedMessage[];
/** The parsed HTTP response headers. */
parsedHeaders: MessagesEnqueueHeaders;
};
};
EnqueuedMessage[];
/** Optional parameters. */
export interface MessagesPeekOptionalParams extends coreHttp.OperationOptions {
export interface MessagesPeekOptionalParams
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -942,23 +894,11 @@ export interface MessagesPeekOptionalParams extends coreHttp.OperationOptions {
}
/** Contains response data for the peek operation. */
export type MessagesPeekResponse = MessagesPeekHeaders &
PeekedMessageItem[] & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: PeekedMessageItem[];
/** The parsed HTTP response headers. */
parsedHeaders: MessagesPeekHeaders;
};
};
export type MessagesPeekResponse = MessagesPeekHeaders & PeekedMessageItem[];
/** Optional parameters. */
export interface MessageIdUpdateOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -968,17 +908,11 @@ export interface MessageIdUpdateOptionalParams
}
/** Contains response data for the update operation. */
export type MessageIdUpdateResponse = MessageIdUpdateHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: MessageIdUpdateHeaders;
};
};
export type MessageIdUpdateResponse = MessageIdUpdateHeaders;
/** Optional parameters. */
export interface MessageIdDeleteOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */
timeoutInSeconds?: number;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */
@ -986,17 +920,11 @@ export interface MessageIdDeleteOptionalParams
}
/** Contains response data for the delete operation. */
export type MessageIdDeleteResponse = MessageIdDeleteHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: MessageIdDeleteHeaders;
};
};
export type MessageIdDeleteResponse = MessageIdDeleteHeaders;
/** Optional parameters. */
export interface StorageClientOptionalParams
extends coreHttp.ServiceClientOptions {
extends coreHttpCompat.ExtendedServiceClientOptions {
/** Specifies the version of the operation to use for this request. */
version?: string;
/** Overrides client endpoint. */

Просмотреть файл

@ -6,9 +6,9 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import * as coreClient from "@azure/core-client";
export const QueueServiceProperties: coreHttp.CompositeMapper = {
export const QueueServiceProperties: coreClient.CompositeMapper = {
serializedName: "QueueServiceProperties",
xmlName: "StorageServiceProperties",
type: {
@ -58,7 +58,7 @@ export const QueueServiceProperties: coreHttp.CompositeMapper = {
}
};
export const Logging: coreHttp.CompositeMapper = {
export const Logging: coreClient.CompositeMapper = {
serializedName: "Logging",
type: {
name: "Composite",
@ -108,7 +108,7 @@ export const Logging: coreHttp.CompositeMapper = {
}
};
export const RetentionPolicy: coreHttp.CompositeMapper = {
export const RetentionPolicy: coreClient.CompositeMapper = {
serializedName: "RetentionPolicy",
type: {
name: "Composite",
@ -136,7 +136,7 @@ export const RetentionPolicy: coreHttp.CompositeMapper = {
}
};
export const Metrics: coreHttp.CompositeMapper = {
export const Metrics: coreClient.CompositeMapper = {
serializedName: "Metrics",
type: {
name: "Composite",
@ -176,7 +176,7 @@ export const Metrics: coreHttp.CompositeMapper = {
}
};
export const CorsRule: coreHttp.CompositeMapper = {
export const CorsRule: coreClient.CompositeMapper = {
serializedName: "CorsRule",
type: {
name: "Composite",
@ -229,7 +229,7 @@ export const CorsRule: coreHttp.CompositeMapper = {
}
};
export const StorageError: coreHttp.CompositeMapper = {
export const StorageError: coreClient.CompositeMapper = {
serializedName: "StorageError",
type: {
name: "Composite",
@ -253,7 +253,7 @@ export const StorageError: coreHttp.CompositeMapper = {
}
};
export const QueueServiceStatistics: coreHttp.CompositeMapper = {
export const QueueServiceStatistics: coreClient.CompositeMapper = {
serializedName: "QueueServiceStatistics",
xmlName: "StorageServiceStats",
type: {
@ -272,7 +272,7 @@ export const QueueServiceStatistics: coreHttp.CompositeMapper = {
}
};
export const GeoReplication: coreHttp.CompositeMapper = {
export const GeoReplication: coreClient.CompositeMapper = {
serializedName: "GeoReplication",
type: {
name: "Composite",
@ -299,7 +299,7 @@ export const GeoReplication: coreHttp.CompositeMapper = {
}
};
export const ListQueuesSegmentResponse: coreHttp.CompositeMapper = {
export const ListQueuesSegmentResponse: coreClient.CompositeMapper = {
serializedName: "ListQueuesSegmentResponse",
xmlName: "EnumerationResults",
type: {
@ -365,7 +365,7 @@ export const ListQueuesSegmentResponse: coreHttp.CompositeMapper = {
}
};
export const QueueItem: coreHttp.CompositeMapper = {
export const QueueItem: coreClient.CompositeMapper = {
serializedName: "QueueItem",
xmlName: "Queue",
type: {
@ -392,7 +392,7 @@ export const QueueItem: coreHttp.CompositeMapper = {
}
};
export const SignedIdentifier: coreHttp.CompositeMapper = {
export const SignedIdentifier: coreClient.CompositeMapper = {
serializedName: "SignedIdentifier",
type: {
name: "Composite",
@ -418,7 +418,7 @@ export const SignedIdentifier: coreHttp.CompositeMapper = {
}
};
export const AccessPolicy: coreHttp.CompositeMapper = {
export const AccessPolicy: coreClient.CompositeMapper = {
serializedName: "AccessPolicy",
type: {
name: "Composite",
@ -449,7 +449,7 @@ export const AccessPolicy: coreHttp.CompositeMapper = {
}
};
export const DequeuedMessageItem: coreHttp.CompositeMapper = {
export const DequeuedMessageItem: coreClient.CompositeMapper = {
serializedName: "DequeuedMessageItem",
xmlName: "QueueMessage",
xmlIsWrapped: true,
@ -517,7 +517,7 @@ export const DequeuedMessageItem: coreHttp.CompositeMapper = {
}
};
export const QueueMessage: coreHttp.CompositeMapper = {
export const QueueMessage: coreClient.CompositeMapper = {
serializedName: "QueueMessage",
type: {
name: "Composite",
@ -535,7 +535,7 @@ export const QueueMessage: coreHttp.CompositeMapper = {
}
};
export const EnqueuedMessage: coreHttp.CompositeMapper = {
export const EnqueuedMessage: coreClient.CompositeMapper = {
serializedName: "EnqueuedMessage",
xmlName: "QueueMessage",
xmlIsWrapped: true,
@ -587,7 +587,7 @@ export const EnqueuedMessage: coreHttp.CompositeMapper = {
}
};
export const PeekedMessageItem: coreHttp.CompositeMapper = {
export const PeekedMessageItem: coreClient.CompositeMapper = {
serializedName: "PeekedMessageItem",
xmlName: "QueueMessage",
xmlIsWrapped: true,
@ -639,7 +639,7 @@ export const PeekedMessageItem: coreHttp.CompositeMapper = {
}
};
export const ServiceSetPropertiesHeaders: coreHttp.CompositeMapper = {
export const ServiceSetPropertiesHeaders: coreClient.CompositeMapper = {
serializedName: "Service_setPropertiesHeaders",
type: {
name: "Composite",
@ -677,7 +677,7 @@ export const ServiceSetPropertiesHeaders: coreHttp.CompositeMapper = {
}
};
export const ServiceSetPropertiesExceptionHeaders: coreHttp.CompositeMapper = {
export const ServiceSetPropertiesExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Service_setPropertiesExceptionHeaders",
type: {
name: "Composite",
@ -701,7 +701,7 @@ export const ServiceSetPropertiesExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const ServiceGetPropertiesHeaders: coreHttp.CompositeMapper = {
export const ServiceGetPropertiesHeaders: coreClient.CompositeMapper = {
serializedName: "Service_getPropertiesHeaders",
type: {
name: "Composite",
@ -739,7 +739,7 @@ export const ServiceGetPropertiesHeaders: coreHttp.CompositeMapper = {
}
};
export const ServiceGetPropertiesExceptionHeaders: coreHttp.CompositeMapper = {
export const ServiceGetPropertiesExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Service_getPropertiesExceptionHeaders",
type: {
name: "Composite",
@ -763,7 +763,7 @@ export const ServiceGetPropertiesExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const ServiceGetStatisticsHeaders: coreHttp.CompositeMapper = {
export const ServiceGetStatisticsHeaders: coreClient.CompositeMapper = {
serializedName: "Service_getStatisticsHeaders",
type: {
name: "Composite",
@ -808,7 +808,7 @@ export const ServiceGetStatisticsHeaders: coreHttp.CompositeMapper = {
}
};
export const ServiceGetStatisticsExceptionHeaders: coreHttp.CompositeMapper = {
export const ServiceGetStatisticsExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Service_getStatisticsExceptionHeaders",
type: {
name: "Composite",
@ -832,7 +832,7 @@ export const ServiceGetStatisticsExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const ServiceListQueuesSegmentHeaders: coreHttp.CompositeMapper = {
export const ServiceListQueuesSegmentHeaders: coreClient.CompositeMapper = {
serializedName: "Service_listQueuesSegmentHeaders",
type: {
name: "Composite",
@ -877,7 +877,7 @@ export const ServiceListQueuesSegmentHeaders: coreHttp.CompositeMapper = {
}
};
export const ServiceListQueuesSegmentExceptionHeaders: coreHttp.CompositeMapper = {
export const ServiceListQueuesSegmentExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Service_listQueuesSegmentExceptionHeaders",
type: {
name: "Composite",
@ -901,7 +901,7 @@ export const ServiceListQueuesSegmentExceptionHeaders: coreHttp.CompositeMapper
}
};
export const QueueCreateHeaders: coreHttp.CompositeMapper = {
export const QueueCreateHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_createHeaders",
type: {
name: "Composite",
@ -946,7 +946,7 @@ export const QueueCreateHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueCreateExceptionHeaders: coreHttp.CompositeMapper = {
export const QueueCreateExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_createExceptionHeaders",
type: {
name: "Composite",
@ -970,7 +970,7 @@ export const QueueCreateExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueDeleteHeaders: coreHttp.CompositeMapper = {
export const QueueDeleteHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_deleteHeaders",
type: {
name: "Composite",
@ -1015,7 +1015,7 @@ export const QueueDeleteHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueDeleteExceptionHeaders: coreHttp.CompositeMapper = {
export const QueueDeleteExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_deleteExceptionHeaders",
type: {
name: "Composite",
@ -1039,7 +1039,7 @@ export const QueueDeleteExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueGetPropertiesHeaders: coreHttp.CompositeMapper = {
export const QueueGetPropertiesHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_getPropertiesHeaders",
type: {
name: "Composite",
@ -1047,12 +1047,12 @@ export const QueueGetPropertiesHeaders: coreHttp.CompositeMapper = {
modelProperties: {
metadata: {
serializedName: "x-ms-meta",
headerCollectionPrefix: "x-ms-meta-",
xmlName: "x-ms-meta",
type: {
name: "Dictionary",
value: { type: { name: "String" } }
},
headerCollectionPrefix: "x-ms-meta-"
}
},
approximateMessagesCount: {
serializedName: "x-ms-approximate-messages-count",
@ -1100,7 +1100,7 @@ export const QueueGetPropertiesHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueGetPropertiesExceptionHeaders: coreHttp.CompositeMapper = {
export const QueueGetPropertiesExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_getPropertiesExceptionHeaders",
type: {
name: "Composite",
@ -1124,7 +1124,7 @@ export const QueueGetPropertiesExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueSetMetadataHeaders: coreHttp.CompositeMapper = {
export const QueueSetMetadataHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_setMetadataHeaders",
type: {
name: "Composite",
@ -1169,7 +1169,7 @@ export const QueueSetMetadataHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueSetMetadataExceptionHeaders: coreHttp.CompositeMapper = {
export const QueueSetMetadataExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_setMetadataExceptionHeaders",
type: {
name: "Composite",
@ -1193,7 +1193,7 @@ export const QueueSetMetadataExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueGetAccessPolicyHeaders: coreHttp.CompositeMapper = {
export const QueueGetAccessPolicyHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_getAccessPolicyHeaders",
type: {
name: "Composite",
@ -1238,7 +1238,7 @@ export const QueueGetAccessPolicyHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueGetAccessPolicyExceptionHeaders: coreHttp.CompositeMapper = {
export const QueueGetAccessPolicyExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_getAccessPolicyExceptionHeaders",
type: {
name: "Composite",
@ -1262,7 +1262,7 @@ export const QueueGetAccessPolicyExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueSetAccessPolicyHeaders: coreHttp.CompositeMapper = {
export const QueueSetAccessPolicyHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_setAccessPolicyHeaders",
type: {
name: "Composite",
@ -1307,7 +1307,7 @@ export const QueueSetAccessPolicyHeaders: coreHttp.CompositeMapper = {
}
};
export const QueueSetAccessPolicyExceptionHeaders: coreHttp.CompositeMapper = {
export const QueueSetAccessPolicyExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Queue_setAccessPolicyExceptionHeaders",
type: {
name: "Composite",
@ -1331,7 +1331,7 @@ export const QueueSetAccessPolicyExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const MessagesDequeueHeaders: coreHttp.CompositeMapper = {
export const MessagesDequeueHeaders: coreClient.CompositeMapper = {
serializedName: "Messages_dequeueHeaders",
type: {
name: "Composite",
@ -1376,7 +1376,7 @@ export const MessagesDequeueHeaders: coreHttp.CompositeMapper = {
}
};
export const MessagesDequeueExceptionHeaders: coreHttp.CompositeMapper = {
export const MessagesDequeueExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Messages_dequeueExceptionHeaders",
type: {
name: "Composite",
@ -1400,7 +1400,7 @@ export const MessagesDequeueExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const MessagesClearHeaders: coreHttp.CompositeMapper = {
export const MessagesClearHeaders: coreClient.CompositeMapper = {
serializedName: "Messages_clearHeaders",
type: {
name: "Composite",
@ -1445,7 +1445,7 @@ export const MessagesClearHeaders: coreHttp.CompositeMapper = {
}
};
export const MessagesClearExceptionHeaders: coreHttp.CompositeMapper = {
export const MessagesClearExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Messages_clearExceptionHeaders",
type: {
name: "Composite",
@ -1469,7 +1469,7 @@ export const MessagesClearExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const MessagesEnqueueHeaders: coreHttp.CompositeMapper = {
export const MessagesEnqueueHeaders: coreClient.CompositeMapper = {
serializedName: "Messages_enqueueHeaders",
type: {
name: "Composite",
@ -1514,7 +1514,7 @@ export const MessagesEnqueueHeaders: coreHttp.CompositeMapper = {
}
};
export const MessagesEnqueueExceptionHeaders: coreHttp.CompositeMapper = {
export const MessagesEnqueueExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Messages_enqueueExceptionHeaders",
type: {
name: "Composite",
@ -1538,7 +1538,7 @@ export const MessagesEnqueueExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const MessagesPeekHeaders: coreHttp.CompositeMapper = {
export const MessagesPeekHeaders: coreClient.CompositeMapper = {
serializedName: "Messages_peekHeaders",
type: {
name: "Composite",
@ -1583,7 +1583,7 @@ export const MessagesPeekHeaders: coreHttp.CompositeMapper = {
}
};
export const MessagesPeekExceptionHeaders: coreHttp.CompositeMapper = {
export const MessagesPeekExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "Messages_peekExceptionHeaders",
type: {
name: "Composite",
@ -1607,7 +1607,7 @@ export const MessagesPeekExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const MessageIdUpdateHeaders: coreHttp.CompositeMapper = {
export const MessageIdUpdateHeaders: coreClient.CompositeMapper = {
serializedName: "MessageId_updateHeaders",
type: {
name: "Composite",
@ -1666,7 +1666,7 @@ export const MessageIdUpdateHeaders: coreHttp.CompositeMapper = {
}
};
export const MessageIdUpdateExceptionHeaders: coreHttp.CompositeMapper = {
export const MessageIdUpdateExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "MessageId_updateExceptionHeaders",
type: {
name: "Composite",
@ -1690,7 +1690,7 @@ export const MessageIdUpdateExceptionHeaders: coreHttp.CompositeMapper = {
}
};
export const MessageIdDeleteHeaders: coreHttp.CompositeMapper = {
export const MessageIdDeleteHeaders: coreClient.CompositeMapper = {
serializedName: "MessageId_deleteHeaders",
type: {
name: "Composite",
@ -1735,7 +1735,7 @@ export const MessageIdDeleteHeaders: coreHttp.CompositeMapper = {
}
};
export const MessageIdDeleteExceptionHeaders: coreHttp.CompositeMapper = {
export const MessageIdDeleteExceptionHeaders: coreClient.CompositeMapper = {
serializedName: "MessageId_deleteExceptionHeaders",
type: {
name: "Composite",

Просмотреть файл

@ -9,9 +9,8 @@
import {
OperationParameter,
OperationURLParameter,
OperationQueryParameter,
QueryCollectionFormat
} from "@azure/core-http";
OperationQueryParameter
} from "@azure/core-client";
import {
QueueServiceProperties as QueueServicePropertiesMapper,
QueueMessage as QueueMessageMapper
@ -209,7 +208,7 @@ export const include: OperationQueryParameter = {
}
}
},
collectionFormat: QueryCollectionFormat.Csv
collectionFormat: "CSV"
};
export const metadata: OperationParameter = {
@ -217,11 +216,11 @@ export const metadata: OperationParameter = {
mapper: {
serializedName: "x-ms-meta",
xmlName: "x-ms-meta",
headerCollectionPrefix: "x-ms-meta-",
type: {
name: "Dictionary",
value: { type: { name: "String" } }
},
headerCollectionPrefix: "x-ms-meta-"
}
}
};

Просмотреть файл

@ -6,10 +6,11 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import { MessageId } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { StorageClientContext } from "../storageClientContext";
import { StorageClient } from "../storageClient";
import {
MessageIdUpdateOptionalParams,
MessageIdUpdateResponse,
@ -17,15 +18,15 @@ import {
MessageIdDeleteResponse
} from "../models";
/** Class representing a MessageId. */
export class MessageId {
private readonly client: StorageClientContext;
/** Class containing MessageId operations. */
export class MessageIdImpl implements MessageId {
private readonly client: StorageClient;
/**
* Initialize a new instance of the class MessageId class.
* @param client Reference to the service client
*/
constructor(client: StorageClientContext) {
constructor(client: StorageClient) {
this.client = client;
}
@ -48,15 +49,10 @@ export class MessageId {
visibilityTimeout: number,
options?: MessageIdUpdateOptionalParams
): Promise<MessageIdUpdateResponse> {
const operationArguments: coreHttp.OperationArguments = {
popReceipt,
visibilityTimeout,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ popReceipt, visibilityTimeout, options },
updateOperationSpec
) as Promise<MessageIdUpdateResponse>;
);
}
/**
@ -69,20 +65,16 @@ export class MessageId {
popReceipt: string,
options?: MessageIdDeleteOptionalParams
): Promise<MessageIdDeleteResponse> {
const operationArguments: coreHttp.OperationArguments = {
popReceipt,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ popReceipt, options },
deleteOperationSpec
) as Promise<MessageIdDeleteResponse>;
);
}
}
// Operation Specifications
const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true);
const xmlSerializer = coreClient.createSerializer(Mappers, /* isXml */ true);
const updateOperationSpec: coreHttp.OperationSpec = {
const updateOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}/messages/{messageid}",
httpMethod: "PUT",
responses: {
@ -112,7 +104,7 @@ const updateOperationSpec: coreHttp.OperationSpec = {
mediaType: "xml",
serializer: xmlSerializer
};
const deleteOperationSpec: coreHttp.OperationSpec = {
const deleteOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}/messages/{messageid}",
httpMethod: "DELETE",
responses: {

Просмотреть файл

@ -6,10 +6,11 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import { Messages } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { StorageClientContext } from "../storageClientContext";
import { StorageClient } from "../storageClient";
import {
MessagesDequeueOptionalParams,
MessagesDequeueResponse,
@ -22,15 +23,15 @@ import {
MessagesPeekResponse
} from "../models";
/** Class representing a Messages. */
export class Messages {
private readonly client: StorageClientContext;
/** Class containing Messages operations. */
export class MessagesImpl implements Messages {
private readonly client: StorageClient;
/**
* Initialize a new instance of the class Messages class.
* @param client Reference to the service client
*/
constructor(client: StorageClientContext) {
constructor(client: StorageClient) {
this.client = client;
}
@ -41,13 +42,7 @@ export class Messages {
dequeue(
options?: MessagesDequeueOptionalParams
): Promise<MessagesDequeueResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
dequeueOperationSpec
) as Promise<MessagesDequeueResponse>;
return this.client.sendOperationRequest({ options }, dequeueOperationSpec);
}
/**
@ -55,13 +50,7 @@ export class Messages {
* @param options The options parameters.
*/
clear(options?: MessagesClearOptionalParams): Promise<MessagesClearResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
clearOperationSpec
) as Promise<MessagesClearResponse>;
return this.client.sendOperationRequest({ options }, clearOperationSpec);
}
/**
@ -76,14 +65,10 @@ export class Messages {
queueMessage: QueueMessage,
options?: MessagesEnqueueOptionalParams
): Promise<MessagesEnqueueResponse> {
const operationArguments: coreHttp.OperationArguments = {
queueMessage,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ queueMessage, options },
enqueueOperationSpec
) as Promise<MessagesEnqueueResponse>;
);
}
/**
@ -92,19 +77,13 @@ export class Messages {
* @param options The options parameters.
*/
peek(options?: MessagesPeekOptionalParams): Promise<MessagesPeekResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
peekOperationSpec
) as Promise<MessagesPeekResponse>;
return this.client.sendOperationRequest({ options }, peekOperationSpec);
}
}
// Operation Specifications
const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true);
const xmlSerializer = coreClient.createSerializer(Mappers, /* isXml */ true);
const dequeueOperationSpec: coreHttp.OperationSpec = {
const dequeueOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}/messages",
httpMethod: "GET",
responses: {
@ -142,7 +121,7 @@ const dequeueOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const clearOperationSpec: coreHttp.OperationSpec = {
const clearOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}/messages",
httpMethod: "DELETE",
responses: {
@ -164,7 +143,7 @@ const clearOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const enqueueOperationSpec: coreHttp.OperationSpec = {
const enqueueOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}/messages",
httpMethod: "POST",
responses: {
@ -204,7 +183,7 @@ const enqueueOperationSpec: coreHttp.OperationSpec = {
mediaType: "xml",
serializer: xmlSerializer
};
const peekOperationSpec: coreHttp.OperationSpec = {
const peekOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}/messages",
httpMethod: "GET",
responses: {

Просмотреть файл

@ -6,10 +6,11 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import { Queue } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { StorageClientContext } from "../storageClientContext";
import { StorageClient } from "../storageClient";
import {
QueueCreateOptionalParams,
QueueCreateResponse,
@ -25,15 +26,15 @@ import {
QueueSetAccessPolicyResponse
} from "../models";
/** Class representing a Queue. */
export class Queue {
private readonly client: StorageClientContext;
/** Class containing Queue operations. */
export class QueueImpl implements Queue {
private readonly client: StorageClient;
/**
* Initialize a new instance of the class Queue class.
* @param client Reference to the service client
*/
constructor(client: StorageClientContext) {
constructor(client: StorageClient) {
this.client = client;
}
@ -42,13 +43,7 @@ export class Queue {
* @param options The options parameters.
*/
create(options?: QueueCreateOptionalParams): Promise<QueueCreateResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
createOperationSpec
) as Promise<QueueCreateResponse>;
return this.client.sendOperationRequest({ options }, createOperationSpec);
}
/**
@ -56,13 +51,7 @@ export class Queue {
* @param options The options parameters.
*/
delete(options?: QueueDeleteOptionalParams): Promise<QueueDeleteResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
deleteOperationSpec
) as Promise<QueueDeleteResponse>;
return this.client.sendOperationRequest({ options }, deleteOperationSpec);
}
/**
@ -73,13 +62,10 @@ export class Queue {
getProperties(
options?: QueueGetPropertiesOptionalParams
): Promise<QueueGetPropertiesResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ options },
getPropertiesOperationSpec
) as Promise<QueueGetPropertiesResponse>;
);
}
/**
@ -90,13 +76,10 @@ export class Queue {
setMetadata(
options?: QueueSetMetadataOptionalParams
): Promise<QueueSetMetadataResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ options },
setMetadataOperationSpec
) as Promise<QueueSetMetadataResponse>;
);
}
/**
@ -107,13 +90,10 @@ export class Queue {
getAccessPolicy(
options?: QueueGetAccessPolicyOptionalParams
): Promise<QueueGetAccessPolicyResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ options },
getAccessPolicyOperationSpec
) as Promise<QueueGetAccessPolicyResponse>;
);
}
/**
@ -123,19 +103,16 @@ export class Queue {
setAccessPolicy(
options?: QueueSetAccessPolicyOptionalParams
): Promise<QueueSetAccessPolicyResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ options },
setAccessPolicyOperationSpec
) as Promise<QueueSetAccessPolicyResponse>;
);
}
}
// Operation Specifications
const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true);
const xmlSerializer = coreClient.createSerializer(Mappers, /* isXml */ true);
const createOperationSpec: coreHttp.OperationSpec = {
const createOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}",
httpMethod: "PUT",
responses: {
@ -161,7 +138,7 @@ const createOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const deleteOperationSpec: coreHttp.OperationSpec = {
const deleteOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}",
httpMethod: "DELETE",
responses: {
@ -183,7 +160,7 @@ const deleteOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const getPropertiesOperationSpec: coreHttp.OperationSpec = {
const getPropertiesOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}",
httpMethod: "GET",
responses: {
@ -205,7 +182,7 @@ const getPropertiesOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const setMetadataOperationSpec: coreHttp.OperationSpec = {
const setMetadataOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}",
httpMethod: "PUT",
responses: {
@ -228,7 +205,7 @@ const setMetadataOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const getAccessPolicyOperationSpec: coreHttp.OperationSpec = {
const getAccessPolicyOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}",
httpMethod: "GET",
responses: {
@ -262,7 +239,7 @@ const getAccessPolicyOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const setAccessPolicyOperationSpec: coreHttp.OperationSpec = {
const setAccessPolicyOperationSpec: coreClient.OperationSpec = {
path: "/{queueName}",
httpMethod: "PUT",
responses: {

Просмотреть файл

@ -6,10 +6,11 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import { Service } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { StorageClientContext } from "../storageClientContext";
import { StorageClient } from "../storageClient";
import {
QueueServiceProperties,
ServiceSetPropertiesOptionalParams,
@ -22,15 +23,15 @@ import {
ServiceListQueuesSegmentResponse
} from "../models";
/** Class representing a Service. */
export class Service {
private readonly client: StorageClientContext;
/** Class containing Service operations. */
export class ServiceImpl implements Service {
private readonly client: StorageClient;
/**
* Initialize a new instance of the class Service class.
* @param client Reference to the service client
*/
constructor(client: StorageClientContext) {
constructor(client: StorageClient) {
this.client = client;
}
@ -44,14 +45,10 @@ export class Service {
properties: QueueServiceProperties,
options?: ServiceSetPropertiesOptionalParams
): Promise<ServiceSetPropertiesResponse> {
const operationArguments: coreHttp.OperationArguments = {
properties,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ properties, options },
setPropertiesOperationSpec
) as Promise<ServiceSetPropertiesResponse>;
);
}
/**
@ -62,13 +59,10 @@ export class Service {
getProperties(
options?: ServiceGetPropertiesOptionalParams
): Promise<ServiceGetPropertiesResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ options },
getPropertiesOperationSpec
) as Promise<ServiceGetPropertiesResponse>;
);
}
/**
@ -80,13 +74,10 @@ export class Service {
getStatistics(
options?: ServiceGetStatisticsOptionalParams
): Promise<ServiceGetStatisticsResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ options },
getStatisticsOperationSpec
) as Promise<ServiceGetStatisticsResponse>;
);
}
/**
@ -96,19 +87,16 @@ export class Service {
listQueuesSegment(
options?: ServiceListQueuesSegmentOptionalParams
): Promise<ServiceListQueuesSegmentResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
{ options },
listQueuesSegmentOperationSpec
) as Promise<ServiceListQueuesSegmentResponse>;
);
}
}
// Operation Specifications
const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true);
const xmlSerializer = coreClient.createSerializer(Mappers, /* isXml */ true);
const setPropertiesOperationSpec: coreHttp.OperationSpec = {
const setPropertiesOperationSpec: coreClient.OperationSpec = {
path: "/",
httpMethod: "PUT",
responses: {
@ -138,7 +126,7 @@ const setPropertiesOperationSpec: coreHttp.OperationSpec = {
mediaType: "xml",
serializer: xmlSerializer
};
const getPropertiesOperationSpec: coreHttp.OperationSpec = {
const getPropertiesOperationSpec: coreClient.OperationSpec = {
path: "/",
httpMethod: "GET",
responses: {
@ -165,7 +153,7 @@ const getPropertiesOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const getStatisticsOperationSpec: coreHttp.OperationSpec = {
const getStatisticsOperationSpec: coreClient.OperationSpec = {
path: "/",
httpMethod: "GET",
responses: {
@ -192,7 +180,7 @@ const getStatisticsOperationSpec: coreHttp.OperationSpec = {
isXML: true,
serializer: xmlSerializer
};
const listQueuesSegmentOperationSpec: coreHttp.OperationSpec = {
const listQueuesSegmentOperationSpec: coreClient.OperationSpec = {
path: "/",
httpMethod: "GET",
responses: {

Просмотреть файл

@ -0,0 +1,12 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
export * from "./service";
export * from "./queue";
export * from "./messages";
export * from "./messageId";

Просмотреть файл

@ -0,0 +1,47 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import {
MessageIdUpdateOptionalParams,
MessageIdUpdateResponse,
MessageIdDeleteOptionalParams,
MessageIdDeleteResponse
} from "../models";
/** Interface representing a MessageId. */
export interface MessageId {
/**
* The Update operation was introduced with version 2011-08-18 of the Queue service API. The Update
* Message operation updates the visibility timeout of a message. You can also use this operation to
* update the contents of a message. A message must be in a format that can be included in an XML
* request with UTF-8 encoding, and the encoded message can be up to 64KB in size.
* @param popReceipt Required. Specifies the valid pop receipt value returned from an earlier call to
* the Get Messages or Update Message operation.
* @param visibilityTimeout Optional. Specifies the new visibility timeout value, in seconds, relative
* to server time. The default value is 30 seconds. A specified value must be larger than or equal to 1
* second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions prior to
* version 2011-08-18. The visibility timeout of a message can be set to a value later than the expiry
* time.
* @param options The options parameters.
*/
update(
popReceipt: string,
visibilityTimeout: number,
options?: MessageIdUpdateOptionalParams
): Promise<MessageIdUpdateResponse>;
/**
* The Delete operation deletes the specified message.
* @param popReceipt Required. Specifies the valid pop receipt value returned from an earlier call to
* the Get Messages or Update Message operation.
* @param options The options parameters.
*/
delete(
popReceipt: string,
options?: MessageIdDeleteOptionalParams
): Promise<MessageIdDeleteResponse>;
}

Просмотреть файл

@ -0,0 +1,53 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import {
MessagesDequeueOptionalParams,
MessagesDequeueResponse,
MessagesClearOptionalParams,
MessagesClearResponse,
QueueMessage,
MessagesEnqueueOptionalParams,
MessagesEnqueueResponse,
MessagesPeekOptionalParams,
MessagesPeekResponse
} from "../models";
/** Interface representing a Messages. */
export interface Messages {
/**
* The Dequeue operation retrieves one or more messages from the front of the queue.
* @param options The options parameters.
*/
dequeue(
options?: MessagesDequeueOptionalParams
): Promise<MessagesDequeueResponse>;
/**
* The Clear operation deletes all messages from the specified queue.
* @param options The options parameters.
*/
clear(options?: MessagesClearOptionalParams): Promise<MessagesClearResponse>;
/**
* The Enqueue operation adds a new message to the back of the message queue. A visibility timeout can
* also be specified to make the message invisible until the visibility timeout expires. A message must
* be in a format that can be included in an XML request with UTF-8 encoding. The encoded message can
* be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size for previous versions.
* @param queueMessage A Message object which can be stored in a Queue
* @param options The options parameters.
*/
enqueue(
queueMessage: QueueMessage,
options?: MessagesEnqueueOptionalParams
): Promise<MessagesEnqueueResponse>;
/**
* The Peek operation retrieves one or more messages from the front of the queue, but does not alter
* the visibility of the message.
* @param options The options parameters.
*/
peek(options?: MessagesPeekOptionalParams): Promise<MessagesPeekResponse>;
}

Просмотреть файл

@ -0,0 +1,67 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import {
QueueCreateOptionalParams,
QueueCreateResponse,
QueueDeleteOptionalParams,
QueueDeleteResponse,
QueueGetPropertiesOptionalParams,
QueueGetPropertiesResponse,
QueueSetMetadataOptionalParams,
QueueSetMetadataResponse,
QueueGetAccessPolicyOptionalParams,
QueueGetAccessPolicyResponse,
QueueSetAccessPolicyOptionalParams,
QueueSetAccessPolicyResponse
} from "../models";
/** Interface representing a Queue. */
export interface Queue {
/**
* creates a new queue under the given account.
* @param options The options parameters.
*/
create(options?: QueueCreateOptionalParams): Promise<QueueCreateResponse>;
/**
* operation permanently deletes the specified queue
* @param options The options parameters.
*/
delete(options?: QueueDeleteOptionalParams): Promise<QueueDeleteResponse>;
/**
* Retrieves user-defined metadata and queue properties on the specified queue. Metadata is associated
* with the queue as name-values pairs.
* @param options The options parameters.
*/
getProperties(
options?: QueueGetPropertiesOptionalParams
): Promise<QueueGetPropertiesResponse>;
/**
* sets user-defined metadata on the specified queue. Metadata is associated with the queue as
* name-value pairs.
* @param options The options parameters.
*/
setMetadata(
options?: QueueSetMetadataOptionalParams
): Promise<QueueSetMetadataResponse>;
/**
* returns details about any stored access policies specified on the queue that may be used with Shared
* Access Signatures.
* @param options The options parameters.
*/
getAccessPolicy(
options?: QueueGetAccessPolicyOptionalParams
): Promise<QueueGetAccessPolicyResponse>;
/**
* sets stored access policies for the queue that may be used with Shared Access Signatures
* @param options The options parameters.
*/
setAccessPolicy(
options?: QueueSetAccessPolicyOptionalParams
): Promise<QueueSetAccessPolicyResponse>;
}

Просмотреть файл

@ -0,0 +1,57 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import {
QueueServiceProperties,
ServiceSetPropertiesOptionalParams,
ServiceSetPropertiesResponse,
ServiceGetPropertiesOptionalParams,
ServiceGetPropertiesResponse,
ServiceGetStatisticsOptionalParams,
ServiceGetStatisticsResponse,
ServiceListQueuesSegmentOptionalParams,
ServiceListQueuesSegmentResponse
} from "../models";
/** Interface representing a Service. */
export interface Service {
/**
* Sets properties for a storage account's Queue service endpoint, including properties for Storage
* Analytics and CORS (Cross-Origin Resource Sharing) rules
* @param properties The StorageService properties.
* @param options The options parameters.
*/
setProperties(
properties: QueueServiceProperties,
options?: ServiceSetPropertiesOptionalParams
): Promise<ServiceSetPropertiesResponse>;
/**
* gets the properties of a storage account's Queue service, including properties for Storage Analytics
* and CORS (Cross-Origin Resource Sharing) rules.
* @param options The options parameters.
*/
getProperties(
options?: ServiceGetPropertiesOptionalParams
): Promise<ServiceGetPropertiesResponse>;
/**
* Retrieves statistics related to replication for the Queue service. It is only available on the
* secondary location endpoint when read-access geo-redundant replication is enabled for the storage
* account.
* @param options The options parameters.
*/
getStatistics(
options?: ServiceGetStatisticsOptionalParams
): Promise<ServiceGetStatisticsResponse>;
/**
* The List Queues Segment operation returns a list of the queues under the specified account
* @param options The options parameters.
*/
listQueuesSegment(
options?: ServiceListQueuesSegmentOptionalParams
): Promise<ServiceListQueuesSegmentResponse>;
}

Просмотреть файл

@ -6,11 +6,20 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import { Service, Queue, Messages, MessageId } from "./operations";
import { StorageClientContext } from "./storageClientContext";
import * as coreHttpCompat from "@azure/core-http-compat";
import {
ServiceImpl,
QueueImpl,
MessagesImpl,
MessageIdImpl
} from "./operations";
import { Service, Queue, Messages, MessageId } from "./operationsInterfaces";
import { StorageClientOptionalParams } from "./models";
export class StorageClient extends StorageClientContext {
export class StorageClient extends coreHttpCompat.ExtendedServiceClient {
url: string;
version: string;
/**
* Initializes a new instance of the StorageClient class.
* @param url The URL of the service account, queue or message that is the target of the desired
@ -18,11 +27,42 @@ export class StorageClient extends StorageClientContext {
* @param options The parameter options
*/
constructor(url: string, options?: StorageClientOptionalParams) {
super(url, options);
this.service = new Service(this);
this.queue = new Queue(this);
this.messages = new Messages(this);
this.messageId = new MessageId(this);
if (url === undefined) {
throw new Error("'url' cannot be null");
}
// Initializing default values for options
if (!options) {
options = {};
}
const defaults: StorageClientOptionalParams = {
requestContentType: "application/json; charset=utf-8"
};
const packageDetails = `azsdk-js-azure-storage-queue/12.20.0`;
const userAgentPrefix =
options.userAgentOptions && options.userAgentOptions.userAgentPrefix
? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
: `${packageDetails}`;
const optionsWithDefaults = {
...defaults,
...options,
userAgentOptions: {
userAgentPrefix
},
endpoint: options.endpoint ?? options.baseUri ?? "{url}"
};
super(optionsWithDefaults);
// Parameter assignments
this.url = url;
// Assigning values to Constant parameters
this.version = options.version || "2021-10-04";
this.service = new ServiceImpl(this);
this.queue = new QueueImpl(this);
this.messages = new MessagesImpl(this);
this.messageId = new MessageIdImpl(this);
}
service: Service;

Просмотреть файл

@ -1,52 +0,0 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import { StorageClientOptionalParams } from "./models";
const packageName = "azure-storage-queue";
const packageVersion = "12.12.0";
export class StorageClientContext extends coreHttp.ServiceClient {
url: string;
version: string;
/**
* Initializes a new instance of the StorageClientContext class.
* @param url The URL of the service account, queue or message that is the target of the desired
* operation.
* @param options The parameter options
*/
constructor(url: string, options?: StorageClientOptionalParams) {
if (url === undefined) {
throw new Error("'url' cannot be null");
}
// Initializing default values for options
if (!options) {
options = {};
}
if (!options.userAgent) {
const defaultUserAgent = coreHttp.getDefaultUserAgentValue();
options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`;
}
super(undefined, options);
this.requestContentType = "application/json; charset=utf-8";
this.baseUri = options.endpoint || "{url}";
// Parameter assignments
this.url = url;
// Assigning values to Constant parameters
this.version = options.version || "2021-10-04";
}
}

Просмотреть файл

@ -1,6 +1,25 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { WithResponse } from "./utils/utils.common";
import {
ListQueuesSegmentResponse,
MessageIdDeleteHeaders,
MessageIdUpdateHeaders,
MessagesClearHeaders,
QueueCreateHeaders,
QueueDeleteHeaders,
QueueGetPropertiesHeaders,
QueueServiceProperties,
QueueServiceStatistics,
QueueSetAccessPolicyHeaders,
QueueSetMetadataHeaders,
ServiceGetPropertiesHeaders,
ServiceGetStatisticsHeaders,
ServiceListQueuesSegmentHeaders,
ServiceSetPropertiesHeaders,
} from "./generated/src";
export {
AccessPolicy,
CorsRule,
@ -10,9 +29,6 @@ export {
GeoReplicationStatusType,
ListQueuesSegmentResponse,
Logging,
MessageIdDeleteResponse,
MessageIdUpdateResponse,
MessagesClearResponse,
MessagesDequeueHeaders,
MessagesEnqueueHeaders,
MessageIdDeleteHeaders,
@ -22,27 +38,80 @@ export {
Metrics,
PeekedMessageItem,
QueueCreateHeaders,
QueueCreateResponse,
QueueDeleteHeaders,
QueueDeleteResponse,
QueueGetAccessPolicyHeaders,
QueueGetPropertiesHeaders,
QueueGetPropertiesResponse,
QueueItem,
QueueServiceProperties,
QueueServiceStatistics,
QueueSetAccessPolicyHeaders,
QueueSetAccessPolicyResponse,
QueueSetMetadataHeaders,
QueueSetMetadataResponse,
RetentionPolicy,
ServiceGetPropertiesHeaders,
ServiceGetPropertiesResponse,
ServiceGetStatisticsHeaders,
ServiceGetStatisticsResponse,
ServiceListQueuesSegmentHeaders,
ServiceListQueuesSegmentResponse,
ServiceSetPropertiesHeaders,
ServiceSetPropertiesResponse,
SignedIdentifier as SignedIdentifierModel,
} from "./generated/src/models";
/** Contains response data for the getProperties operation. */
export type ServiceGetPropertiesResponse = WithResponse<
ServiceGetPropertiesHeaders & QueueServiceProperties,
ServiceGetPropertiesHeaders,
QueueServiceProperties
>;
/**
* Contains response data for the create operation.
*/
export declare type QueueCreateResponse = WithResponse<QueueCreateHeaders, QueueCreateHeaders>;
/** Contains response data for the listQueuesSegment operation. */
export type ServiceListQueuesSegmentResponse = WithResponse<
ServiceListQueuesSegmentHeaders & ListQueuesSegmentResponse,
ServiceListQueuesSegmentHeaders,
ListQueuesSegmentResponse
>;
/** Contains response data for the setProperties operation. */
export type ServiceSetPropertiesResponse = WithResponse<
ServiceSetPropertiesHeaders,
ServiceSetPropertiesHeaders
>;
/** Contains response data for the getStatistics operation. */
export type ServiceGetStatisticsResponse = WithResponse<
ServiceGetStatisticsHeaders & QueueServiceStatistics,
ServiceGetStatisticsHeaders,
QueueServiceStatistics
>;
/** Contains response data for the setMetadata operation. */
export type QueueSetMetadataResponse = WithResponse<
QueueSetMetadataHeaders,
QueueSetMetadataHeaders
>;
/** Contains response data for the setAccessPolicy operation. */
export type QueueSetAccessPolicyResponse = WithResponse<
QueueSetAccessPolicyHeaders,
QueueSetAccessPolicyHeaders
>;
/** Contains response data for the getProperties operation. */
export type QueueGetPropertiesResponse = WithResponse<
QueueGetPropertiesHeaders,
QueueGetPropertiesHeaders
>;
/** Contains response data for the delete operation. */
export type QueueDeleteResponse = WithResponse<QueueDeleteHeaders, QueueDeleteHeaders>;
/** Contains response data for the clear operation. */
export type MessagesClearResponse = WithResponse<MessagesClearHeaders, MessagesClearHeaders>;
/** Contains response data for the update operation. */
export type MessageIdUpdateResponse = WithResponse<MessageIdUpdateHeaders, MessageIdUpdateHeaders>;
/** Contains response data for the delete operation. */
export type MessageIdDeleteResponse = WithResponse<MessageIdDeleteHeaders, MessageIdDeleteHeaders>;

Просмотреть файл

@ -1,21 +1,37 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RestError } from "@azure/core-http";
import { RestError } from "@azure/core-rest-pipeline";
export * from "./credentials/AnonymousCredential";
export * from "./credentials/Credential";
export * from "../../storage-blob/src/credentials/AnonymousCredential";
export * from "../../storage-blob/src/credentials/Credential";
export { SasIPRange } from "./SasIPRange";
export * from "./Pipeline";
export * from "./policies/AnonymousCredentialPolicy";
export * from "./policies/CredentialPolicy";
export * from "./StorageBrowserPolicyFactory";
export * from "./StorageRetryPolicyFactory";
export {
Pipeline,
PipelineLike,
PipelineOptions,
isPipelineLike,
newPipeline,
StoragePipelineOptions,
ServiceClientOptions,
} from "../../storage-blob/src/Pipeline";
export { BaseRequestPolicy } from "../../storage-blob/src/policies/RequestPolicy";
export * from "../../storage-blob/src/policies/AnonymousCredentialPolicy";
export * from "../../storage-blob/src/policies/CredentialPolicy";
export * from "../../storage-blob/src/StorageRetryPolicyFactory";
export * from "../../storage-blob/src/StorageBrowserPolicyFactory";
export { Metadata } from "./models";
export * from "./QueueClient";
export * from "./QueueSASPermissions";
export * from "./QueueServiceClient";
export { CommonOptions } from "./StorageClient";
export * from "./generatedModels";
export {
WithResponse,
ResponseLike,
ResponseWithBody,
ResponseWithHeaders,
HttpResponse,
} from "./utils/utils.common";
export { RestError };
export { logger } from "./log";

Просмотреть файл

@ -1,23 +1,32 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RestError } from "@azure/core-http";
import { RestError } from "@azure/core-rest-pipeline";
export * from "./AccountSASPermissions";
export * from "./AccountSASResourceTypes";
export * from "./AccountSASServices";
export * from "./AccountSASSignatureValues";
export * from "./credentials/AnonymousCredential";
export * from "./credentials/Credential";
export * from "./credentials/StorageSharedKeyCredential";
export * from "../../storage-blob/src/credentials/AnonymousCredential";
export * from "../../storage-blob/src/credentials/Credential";
export * from "../../storage-blob/src/credentials/StorageSharedKeyCredential";
export { SasIPRange } from "./SasIPRange";
export * from "./Pipeline";
export * from "./policies/AnonymousCredentialPolicy";
export * from "./policies/CredentialPolicy";
export * from "./StorageRetryPolicyFactory";
export * from "./StorageBrowserPolicyFactory";
export { BaseRequestPolicy } from "../../storage-blob/src/policies/RequestPolicy";
export {
Pipeline,
PipelineLike,
PipelineOptions,
isPipelineLike,
newPipeline,
StoragePipelineOptions,
ServiceClientOptions,
} from "../../storage-blob/src/Pipeline";
export * from "../../storage-blob/src/policies/AnonymousCredentialPolicy";
export * from "../../storage-blob/src/policies/CredentialPolicy";
export * from "../../storage-blob/src/StorageRetryPolicyFactory";
export * from "../../storage-blob/src/policies/StorageSharedKeyCredentialPolicy";
export * from "../../storage-blob/src/StorageBrowserPolicyFactory";
export { Metadata } from "./models";
export * from "./policies/StorageSharedKeyCredentialPolicy";
export * from "./QueueClient";
export * from "./QueueSASPermissions";
export * from "./QueueSASSignatureValues";
@ -25,5 +34,12 @@ export * from "./QueueServiceClient";
export * from "./SASQueryParameters";
export { CommonOptions, ListQueuesIncludeType } from "./StorageClient";
export * from "./generatedModels";
export {
WithResponse,
ResponseLike,
ResponseWithBody,
ResponseWithHeaders,
HttpResponse,
} from "./utils/utils.common";
export { RestError };
export { logger } from "./log";

Просмотреть файл

@ -1,23 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RequestPolicy, RequestPolicyOptions } from "@azure/core-http";
import { CredentialPolicy } from "./CredentialPolicy";
/**
* AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources
* or for use with Shared Access Signatures (SAS).
*/
export class AnonymousCredentialPolicy extends CredentialPolicy {
/**
* Creates an instance of AnonymousCredentialPolicy.
* @param nextPolicy -
* @param options -
*/
// The base class has a protected constructor. Adding a public one to enable constructing of this class.
/* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions) {
super(nextPolicy, options);
}
}

Просмотреть файл

@ -1,31 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { BaseRequestPolicy, HttpOperationResponse, WebResource } from "@azure/core-http";
/**
* Credential policy used to sign HTTP(S) requests before sending. This is an
* abstract class.
*/
export abstract class CredentialPolicy extends BaseRequestPolicy {
/**
* Sends out request.
*
* @param request -
*/
public sendRequest(request: WebResource): Promise<HttpOperationResponse> {
return this._nextPolicy.sendRequest(this.signRequest(request));
}
/**
* Child classes must implement this method with request signing. This method
* will be executed in {@link sendRequest}.
*
* @param request -
*/
protected signRequest(request: WebResource): WebResource {
// Child classes must override this method with request signing. This method
// will be executed in sendRequest().
return request;
}
}

Просмотреть файл

@ -1,64 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
BaseRequestPolicy,
HttpOperationResponse,
isNode,
RequestPolicy,
RequestPolicyOptions,
WebResource,
} from "@azure/core-http";
import { HeaderConstants, URLConstants } from "../utils/constants";
import { setURLParameter } from "../utils/utils.common";
/**
* StorageBrowserPolicy will handle differences between Node.js and browser runtime, including:
*
* 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'.
* StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL
* thus avoid the browser cache.
*
* 2. Remove cookie header for security
*
* 3. Remove content-length header to avoid browsers warning
*/
export class StorageBrowserPolicy extends BaseRequestPolicy {
/**
* Creates an instance of StorageBrowserPolicy.
* @param nextPolicy -
* @param options -
*/
// The base class has a protected constructor. Adding a public one to enable constructing of this class.
/* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions) {
super(nextPolicy, options);
}
/**
* Sends out request.
*
* @param request -
*/
public async sendRequest(request: WebResource): Promise<HttpOperationResponse> {
if (isNode) {
return this._nextPolicy.sendRequest(request);
}
if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") {
request.url = setURLParameter(
request.url,
URLConstants.Parameters.FORCE_BROWSER_NO_CACHE,
new Date().getTime().toString()
);
}
request.headers.remove(HeaderConstants.COOKIE);
// According to XHR standards, content-length should be fully controlled by browsers
request.headers.remove(HeaderConstants.CONTENT_LENGTH);
return this._nextPolicy.sendRequest(request);
}
}

Просмотреть файл

@ -1,289 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { AbortError } from "@azure/abort-controller";
import {
AbortSignalLike,
BaseRequestPolicy,
HttpOperationResponse,
RequestPolicy,
RequestPolicyFactory,
RequestPolicyOptions,
RestError,
WebResource,
} from "@azure/core-http";
import { StorageRetryOptions } from "../StorageRetryPolicyFactory";
import { URLConstants } from "../utils/constants";
import { delay, setURLHost, setURLParameter } from "../utils/utils.common";
import { logger } from "../log";
/**
* A factory method used to generated a RetryPolicy factory.
*
* @param retryOptions -
*/
export function NewRetryPolicyFactory(retryOptions?: StorageRetryOptions): RequestPolicyFactory {
return {
create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions): StorageRetryPolicy => {
return new StorageRetryPolicy(nextPolicy, options, retryOptions);
},
};
}
/**
* RetryPolicy types.
*/
export enum StorageRetryPolicyType {
/**
* Exponential retry. Retry time delay grows exponentially.
*/
EXPONENTIAL,
/**
* Linear retry. Retry time delay grows linearly.
*/
FIXED,
}
// Default values of StorageRetryOptions
const DEFAULT_RETRY_OPTIONS: StorageRetryOptions = {
maxRetryDelayInMs: 120 * 1000,
maxTries: 4,
retryDelayInMs: 4 * 1000,
retryPolicyType: StorageRetryPolicyType.EXPONENTIAL,
secondaryHost: "",
tryTimeoutInMs: 30 * 1000, // https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations
};
const RETRY_ABORT_ERROR = new AbortError("The operation was aborted.");
/**
* Retry policy with exponential retry and linear retry implemented.
*/
export class StorageRetryPolicy extends BaseRequestPolicy {
/**
* RetryOptions.
*/
private readonly retryOptions: StorageRetryOptions;
/**
* Creates an instance of RetryPolicy.
*
* @param nextPolicy -
* @param options -
* @param retryOptions -
*/
constructor(
nextPolicy: RequestPolicy,
options: RequestPolicyOptions,
retryOptions: StorageRetryOptions = DEFAULT_RETRY_OPTIONS
) {
super(nextPolicy, options);
// Initialize retry options
this.retryOptions = {
retryPolicyType: retryOptions.retryPolicyType
? retryOptions.retryPolicyType
: DEFAULT_RETRY_OPTIONS.retryPolicyType,
maxTries:
retryOptions.maxTries && retryOptions.maxTries >= 1
? Math.floor(retryOptions.maxTries)
: DEFAULT_RETRY_OPTIONS.maxTries,
tryTimeoutInMs:
retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0
? retryOptions.tryTimeoutInMs
: DEFAULT_RETRY_OPTIONS.tryTimeoutInMs,
retryDelayInMs:
retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0
? Math.min(
retryOptions.retryDelayInMs,
retryOptions.maxRetryDelayInMs
? retryOptions.maxRetryDelayInMs
: DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs!
)
: DEFAULT_RETRY_OPTIONS.retryDelayInMs,
maxRetryDelayInMs:
retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0
? retryOptions.maxRetryDelayInMs
: DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs,
secondaryHost: retryOptions.secondaryHost
? retryOptions.secondaryHost
: DEFAULT_RETRY_OPTIONS.secondaryHost,
};
}
/**
* Sends request.
*
* @param request -
*/
public async sendRequest(request: WebResource): Promise<HttpOperationResponse> {
return this.attemptSendRequest(request, false, 1);
}
/**
* Decide and perform next retry. Won't mutate request parameter.
*
* @param request -
* @param response -
* @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then
* the resource was not found. This may be due to replication delay. So, in this
* case, we'll never try the secondary again for this operation.
* @param attempt - How many retries has been attempted to performed, starting from 1, which includes
* the attempt will be performed by this method call.
*/
protected async attemptSendRequest(
request: WebResource,
secondaryHas404: boolean,
attempt: number
): Promise<HttpOperationResponse> {
const newRequest: WebResource = request.clone();
const isPrimaryRetry =
secondaryHas404 ||
!this.retryOptions.secondaryHost ||
!(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") ||
attempt % 2 === 1;
if (!isPrimaryRetry) {
newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost!);
}
// Set the server-side timeout query parameter "timeout=[seconds]"
newRequest.url = setURLParameter(
newRequest.url,
URLConstants.Parameters.TIMEOUT,
Math.floor(this.retryOptions.tryTimeoutInMs! / 1000).toString()
);
let response: HttpOperationResponse | undefined;
try {
logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`);
response = await this._nextPolicy.sendRequest(newRequest);
if (!this.shouldRetry(isPrimaryRetry, attempt, response)) {
return response;
}
secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404);
} catch (err: any) {
logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`);
if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) {
throw err;
}
}
await this.delay(isPrimaryRetry, attempt, request.abortSignal);
return this.attemptSendRequest(request, secondaryHas404, ++attempt);
}
/**
* Decide whether to retry according to last HTTP response and retry counters.
*
* @param isPrimaryRetry -
* @param attempt -
* @param response -
* @param err -
*/
protected shouldRetry(
isPrimaryRetry: boolean,
attempt: number,
response?: HttpOperationResponse,
err?: RestError
): boolean {
if (attempt >= this.retryOptions.maxTries!) {
logger.info(
`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions
.maxTries!}, no further try.`
);
return false;
}
// Handle network failures, you may need to customize the list when you implement
// your own http client
const retriableErrors = [
"ETIMEDOUT",
"ESOCKETTIMEDOUT",
"ECONNREFUSED",
"ECONNRESET",
"ENOENT",
"ENOTFOUND",
"TIMEOUT",
"EPIPE",
"REQUEST_SEND_ERROR", // For default xhr based http client provided in ms-rest-js
];
if (err) {
for (const retriableError of retriableErrors) {
if (
err.name.toUpperCase().includes(retriableError) ||
err.message.toUpperCase().includes(retriableError) ||
(err.code && err.code.toString().toUpperCase() === retriableError)
) {
logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`);
return true;
}
}
}
// If attempt was against the secondary & it returned a StatusNotFound (404), then
// the resource was not found. This may be due to replication delay. So, in this
// case, we'll never try the secondary again for this operation.
if (response || err) {
const statusCode = response ? response.status : err ? err.statusCode : 0;
if (!isPrimaryRetry && statusCode === 404) {
logger.info(`RetryPolicy: Secondary access with 404, will retry.`);
return true;
}
// Server internal error or server timeout
if (statusCode === 503 || statusCode === 500) {
logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`);
return true;
}
}
if (err?.code === "PARSE_ERROR" && err?.message.startsWith(`Error "Error: Unclosed root tag`)) {
logger.info(
"RetryPolicy: Incomplete XML response likely due to service timeout, will retry."
);
return true;
}
return false;
}
/**
* Delay a calculated time between retries.
*
* @param isPrimaryRetry -
* @param attempt -
* @param abortSignal -
*/
private async delay(isPrimaryRetry: boolean, attempt: number, abortSignal?: AbortSignalLike) {
let delayTimeInMs: number = 0;
if (isPrimaryRetry) {
switch (this.retryOptions.retryPolicyType) {
case StorageRetryPolicyType.EXPONENTIAL:
delayTimeInMs = Math.min(
(Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs!,
this.retryOptions.maxRetryDelayInMs!
);
break;
case StorageRetryPolicyType.FIXED:
delayTimeInMs = this.retryOptions.retryDelayInMs!;
break;
}
} else {
delayTimeInMs = Math.random() * 1000;
}
logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`);
return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR);
}
}

Просмотреть файл

@ -1,173 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RequestPolicy, RequestPolicyOptions, WebResource } from "@azure/core-http";
import { StorageSharedKeyCredential } from "../credentials/StorageSharedKeyCredential";
import { HeaderConstants } from "../utils/constants";
import { getURLPath, getURLQueries } from "../utils/utils.common";
import { CredentialPolicy } from "./CredentialPolicy";
/**
* StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key.
*/
export class StorageSharedKeyCredentialPolicy extends CredentialPolicy {
/**
* Reference to {@link StorageSharedKeyCredential} which generates StorageSharedKeyCredentialPolicy
*/
private readonly factory: StorageSharedKeyCredential;
/**
* Creates an instance of StorageSharedKeyCredentialPolicy.
* @param nextPolicy -
* @param options -
* @param factory -
*/
constructor(
nextPolicy: RequestPolicy,
options: RequestPolicyOptions,
factory: StorageSharedKeyCredential
) {
super(nextPolicy, options);
this.factory = factory;
}
/**
* Signs request.
*
* @param request -
*/
protected signRequest(request: WebResource): WebResource {
request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString());
if (request.body && typeof request.body === "string" && request.body.length > 0) {
request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body));
}
const stringToSign: string =
[
request.method.toUpperCase(),
this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE),
this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING),
this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH),
this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5),
this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE),
this.getHeaderValueToSign(request, HeaderConstants.DATE),
this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE),
this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH),
this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH),
this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE),
this.getHeaderValueToSign(request, HeaderConstants.RANGE),
].join("\n") +
"\n" +
this.getCanonicalizedHeadersString(request) +
this.getCanonicalizedResourceString(request);
const signature: string = this.factory.computeHMACSHA256(stringToSign);
request.headers.set(
HeaderConstants.AUTHORIZATION,
`SharedKey ${this.factory.accountName}:${signature}`
);
// console.log(`[URL]:${request.url}`);
// console.log(`[HEADERS]:${request.headers.toString()}`);
// console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`);
// console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`);
return request;
}
/**
* Retrieve header value according to shared key sign rules.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key
*
* @param request -
* @param headerName -
*/
private getHeaderValueToSign(request: WebResource, headerName: string): string {
const value = request.headers.get(headerName);
if (!value) {
return "";
}
// When using version 2015-02-21 or later, if Content-Length is zero, then
// set the Content-Length part of the StringToSign to an empty string.
// https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key
if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") {
return "";
}
return value;
}
/**
* To construct the CanonicalizedHeaders portion of the signature string, follow these steps:
* 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
* 2. Convert each HTTP header name to lowercase.
* 3. Sort the headers lexicographically by header name, in ascending order.
* Each header may appear only once in the string.
* 4. Replace any linear whitespace in the header value with a single space.
* 5. Trim any whitespace around the colon in the header.
* 6. Finally, append a new-line character to each canonicalized header in the resulting list.
* Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
*
* @param request -
*/
private getCanonicalizedHeadersString(request: WebResource): string {
let headersArray = request.headers.headersArray().filter((value) => {
return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE);
});
headersArray.sort((a, b): number => {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});
// Remove duplicate headers
headersArray = headersArray.filter((value, index, array) => {
if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) {
return false;
}
return true;
});
let canonicalizedHeadersStringToSign: string = "";
headersArray.forEach((header) => {
canonicalizedHeadersStringToSign += `${header.name
.toLowerCase()
.trimRight()}:${header.value.trimLeft()}\n`;
});
return canonicalizedHeadersStringToSign;
}
/**
* Retrieves the webResource canonicalized resource string.
*
* @param request -
*/
private getCanonicalizedResourceString(request: WebResource): string {
const path = encodeURI(getURLPath(request.url) || "/");
let canonicalizedResourceString: string = "";
canonicalizedResourceString += `/${this.factory.accountName}${path}`;
const queries = getURLQueries(request.url);
const lowercaseQueries: { [key: string]: string } = {};
if (queries) {
const queryKeys: string[] = [];
for (const key in queries) {
if (Object.prototype.hasOwnProperty.call(queries, key)) {
const lowercaseKey = key.toLowerCase();
lowercaseQueries[lowercaseKey] = queries[key];
queryKeys.push(lowercaseKey);
}
}
queryKeys.sort();
for (const key of queryKeys) {
canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`;
}
}
return canonicalizedResourceString;
}
}

Просмотреть файл

@ -1,53 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
BaseRequestPolicy,
HttpHeaders,
HttpOperationResponse,
isNode,
RequestPolicy,
RequestPolicyOptions,
WebResource,
} from "@azure/core-http";
import { HeaderConstants } from "../utils/constants";
/**
* TelemetryPolicy is a policy used to tag user-agent header for every requests.
*/
export class TelemetryPolicy extends BaseRequestPolicy {
/**
* Telemetry string.
*/
public readonly telemetry: string;
/**
* Creates an instance of TelemetryPolicy.
* @param nextPolicy -
* @param options -
* @param telemetry -
*/
constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, telemetry: string) {
super(nextPolicy, options);
this.telemetry = telemetry;
}
/**
* Sends out request.
*
* @param request -
*/
public async sendRequest(request: WebResource): Promise<HttpOperationResponse> {
if (isNode) {
if (!request.headers) {
request.headers = new HttpHeaders();
}
if (!request.headers.get(HeaderConstants.USER_AGENT)) {
request.headers.set(HeaderConstants.USER_AGENT, this.telemetry);
}
}
return this._nextPolicy.sendRequest(request);
}
}

Просмотреть файл

@ -1,11 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { DefaultHttpClient } from "@azure/core-http";
import { IHttpClient } from "../Pipeline";
const _defaultHttpClient = new DefaultHttpClient();
export function getCachedDefaultHttpClient(): IHttpClient {
return _defaultHttpClient;
}

Просмотреть файл

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export const SDK_VERSION: string = "12.12.0";
export const SDK_VERSION: string = "12.20.0";
export const SERVICE_VERSION: string = "2021-10-04";
/**

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { OperationOptions, RequestOptionsBase } from "@azure/core-http";
import { createSpanFunction } from "@azure/core-tracing";
/**
@ -12,20 +11,3 @@ export const createSpan = createSpanFunction({
packagePrefix: "Azure.Storage.Queue",
namespace: "Microsoft.Storage",
});
/**
* @internal
*
* Adapt the tracing options from OperationOptions to what they need to be for
* RequestOptionsBase (when we update to later OpenTelemetry versions this is now
* two separate fields, not just one).
*/
export function convertTracingToRequestOptionsBase(
options?: OperationOptions
): Pick<RequestOptionsBase, "spanOptions" | "tracingContext"> {
return {
// By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier.
spanOptions: (options?.tracingOptions as any)?.spanOptions,
tracingContext: options?.tracingOptions?.tracingContext,
};
}

Просмотреть файл

@ -1,15 +1,14 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { AbortSignalLike } from "@azure/abort-controller";
import { HttpHeaders, URLBuilder } from "@azure/core-http";
import { HttpHeaders, createHttpHeaders } from "@azure/core-rest-pipeline";
import {
HeaderConstants,
URLConstants,
DevelopmentConnectionString,
PathStylePorts,
} from "./constants";
import { StorageClientContext } from "../generated/src/storageClientContext";
import { Pipeline } from "../Pipeline";
import { HttpHeadersLike, WebResourceLike } from "@azure/core-http-compat";
/**
* Append a string to URL path. Will remove duplicated "/" in front of the string
@ -20,15 +19,14 @@ import { Pipeline } from "../Pipeline";
* @returns An updated URL string
*/
export function appendToURLPath(url: string, name: string): string {
const urlParsed = URLBuilder.parse(url);
const urlParsed = new URL(url);
let path = urlParsed.getPath();
let path = urlParsed.pathname;
path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name;
urlParsed.setPath(path);
urlParsed.pathname = path;
return urlParsed.toString();
}
/**
* Set URL parameter name and value. If name exists in URL parameters, old value
* will be replaced by name key. If not provide value, the parameter will be deleted.
@ -39,8 +37,28 @@ export function appendToURLPath(url: string, name: string): string {
* @returns An updated URL string
*/
export function setURLParameter(url: string, name: string, value?: string): string {
const urlParsed = URLBuilder.parse(url);
urlParsed.setQueryParameter(name, value);
const urlParsed = new URL(url);
const encodedName = encodeURIComponent(name);
const encodedValue = value ? encodeURIComponent(value) : undefined;
// mutating searchParams will change the encoding, so we have to do this ourselves
const searchString = urlParsed.search === "" ? "?" : urlParsed.search;
const searchPieces: string[] = [];
for (const pair of searchString.slice(1).split("&")) {
if (pair) {
const [key] = pair.split("=", 2);
if (key !== encodedName) {
searchPieces.push(pair);
}
}
}
if (encodedValue) {
searchPieces.push(`${encodedName}=${encodedValue}`);
}
urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
return urlParsed.toString();
}
@ -52,8 +70,8 @@ export function setURLParameter(url: string, name: string, value?: string): stri
* @returns Parameter value(s) for the given parameter name.
*/
export function getURLParameter(url: string, name: string): string | string[] | undefined {
const urlParsed = URLBuilder.parse(url);
return urlParsed.getQueryParameterValue(name);
const urlParsed = new URL(url);
return urlParsed.searchParams.get(name) ?? undefined;
}
/**
@ -64,8 +82,8 @@ export function getURLParameter(url: string, name: string): string | string[] |
* @returns An updated URL string
*/
export function setURLHost(url: string, host: string): string {
const urlParsed = URLBuilder.parse(url);
urlParsed.setHost(host);
const urlParsed = new URL(url);
urlParsed.hostname = host;
return urlParsed.toString();
}
@ -76,8 +94,12 @@ export function setURLHost(url: string, host: string): string {
* @returns The path part of the given URL string.
*/
export function getURLPath(url: string): string | undefined {
const urlParsed = URLBuilder.parse(url);
return urlParsed.getPath();
try {
const urlParsed = new URL(url);
return urlParsed.pathname;
} catch (e) {
return undefined;
}
}
/**
@ -87,13 +109,13 @@ export function getURLPath(url: string): string | undefined {
* @returns query key value string pairs from the given URL string.
*/
export function getURLQueries(url: string): { [key: string]: string } {
let queryString = URLBuilder.parse(url).getQuery();
let queryString = new URL(url).search;
if (!queryString) {
return {};
}
queryString = queryString.trim();
queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString;
queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString;
let querySubStrings: string[] = queryString.split("&");
querySubStrings = querySubStrings.filter((value: string) => {
@ -236,7 +258,7 @@ export function extractConnectionStringParts(connectionString: string): Connecti
} else {
// SAS connection string
const accountSas = getValueInConnString(connectionString, "SharedAccessSignature");
let accountSas = getValueInConnString(connectionString, "SharedAccessSignature");
const accountName = getAccountNameFromUrl(queueEndpoint);
if (!queueEndpoint) {
throw new Error("Invalid QueueEndpoint in the provided SAS Connection String");
@ -244,6 +266,11 @@ export function extractConnectionStringParts(connectionString: string): Connecti
throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String");
}
// remove test SAS
if (accountSas === "fakeSasToken") {
accountSas = "";
}
return { kind: "SASConnString", url: queueEndpoint, accountName, accountSas };
}
}
@ -322,14 +349,14 @@ export function sanitizeURL(url: string): string {
* @returns sanitized headers
*/
export function sanitizeHeaders(originalHeader: HttpHeaders): HttpHeaders {
const headers: HttpHeaders = new HttpHeaders();
for (const header of originalHeader.headersArray()) {
if (header.name.toLowerCase() === HeaderConstants.AUTHORIZATION) {
headers.set(header.name, "*****");
} else if (header.name.toLowerCase() === HeaderConstants.X_MS_COPY_SOURCE) {
headers.set(header.name, sanitizeURL(header.value));
const headers: HttpHeaders = createHttpHeaders();
for (const [name, value] of originalHeader) {
if (name.toLowerCase() === HeaderConstants.AUTHORIZATION) {
headers.set(name, "*****");
} else if (name.toLowerCase() === HeaderConstants.X_MS_COPY_SOURCE) {
headers.set(name, sanitizeURL(value));
} else {
headers.set(header.name, header.value);
headers.set(name, value);
}
}
@ -342,17 +369,17 @@ export function sanitizeHeaders(originalHeader: HttpHeaders): HttpHeaders {
* @returns with the account name
*/
export function getAccountNameFromUrl(url: string): string {
const parsedUrl: URLBuilder = URLBuilder.parse(url);
const parsedUrl = new URL(url);
let accountName;
try {
if (parsedUrl.getHost()!.split(".")[1] === "queue") {
if (parsedUrl.hostname.split(".")[1] === "queue") {
// `${defaultEndpointsProtocol}://${accountName}.queue.${endpointSuffix}`;
accountName = parsedUrl.getHost()!.split(".")[0];
accountName = parsedUrl.hostname.split(".")[0];
} else if (isIpEndpointStyle(parsedUrl)) {
// IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/
// Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/
// .getPath() -> /devstoreaccount1/
accountName = parsedUrl.getPath()!.split("/")[1];
accountName = parsedUrl.pathname.split("/")[1];
} else {
// Custom domain case: "https://customdomain.com/containername/blob".
accountName = "";
@ -363,13 +390,8 @@ export function getAccountNameFromUrl(url: string): string {
}
}
export function isIpEndpointStyle(parsedUrl: URLBuilder): boolean {
if (parsedUrl.getHost() === undefined) {
return false;
}
const host =
parsedUrl.getHost()! + (parsedUrl.getPort() === undefined ? "" : ":" + parsedUrl.getPort());
export function isIpEndpointStyle(parsedUrl: URL): boolean {
const host = parsedUrl.host;
// Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'.
// Case 2: localhost(:port), use broad regex to match port part.
@ -379,24 +401,10 @@ export function isIpEndpointStyle(parsedUrl: URLBuilder): boolean {
/^.*:.*:.*$|^localhost(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(
host
) ||
(parsedUrl.getPort() !== undefined && PathStylePorts.includes(parsedUrl.getPort()!))
(Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port))
);
}
/**
* Gets a new StorageClientContext
* @param url - Url used for the StorageClientContext
* @param pipeline - a pipeline containing HTTP request policies
* @returns new StorageClientContext
*/
export function getStorageClientContext(url: string, pipeline: Pipeline): StorageClientContext {
const storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions());
// Override protocol layer's default content-type
(storageClientContext as any).requestContentType = undefined;
return storageClientContext;
}
/**
* Append a string to URL query.
*
@ -405,15 +413,111 @@ export function getStorageClientContext(url: string, pipeline: Pipeline): Storag
* @returns An updated URL string.
*/
export function appendToURLQuery(url: string, queryParts: string): string {
const urlParsed = URLBuilder.parse(url);
const urlParsed = new URL(url);
let query = urlParsed.getQuery();
let query = urlParsed.search;
if (query) {
query += "&" + queryParts;
} else {
query = queryParts;
}
urlParsed.setQuery(query);
urlParsed.search = query;
return urlParsed.toString();
}
/**
* A representation of an HTTP response that
* includes a reference to the request that
* originated it.
*/
export interface HttpResponse {
/**
* The headers from the response.
*/
headers: HttpHeadersLike;
/**
* The original request that resulted in this response.
*/
request: WebResourceLike;
/**
* The HTTP status code returned from the service.
*/
status: number;
}
/**
* An object with a _response property that has
* headers already parsed into a typed object.
*/
export interface ResponseWithHeaders<Headers> {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: Headers;
};
}
/**
* An object with a _response property that has body
* and headers already parsed into known types.
*/
export interface ResponseWithBody<Headers, Body> {
/**
* The underlying HTTP response.
*/
_response: HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: Headers;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Body;
};
}
/**
* An object with a simple _response property.
*/
export interface ResponseLike {
/**
* The underlying HTTP response.
*/
_response: HttpResponse;
}
/**
* A type that represents an operation result with a known _response property.
*/
export type WithResponse<T, Headers = undefined, Body = undefined> = T &
(Body extends object
? ResponseWithBody<Headers, Body>
: Headers extends object
? ResponseWithHeaders<Headers>
: ResponseLike);
/**
* A typesafe helper for ensuring that a given response object has
* the original _response attached.
* @param response - A response object from calling a client operation
* @returns The same object, but with known _response property
*/
export function assertResponse<T extends object, Headers = undefined, Body = undefined>(
response: T
): WithResponse<T, Headers, Body> {
if (`_response` in response) {
return response as WithResponse<T, Headers, Body>;
}
throw new TypeError(`Unexpected response object ${response}`);
}

Просмотреть файл

@ -18,9 +18,10 @@ optional-response-headers: true
v3: true
disable-async-iterators: true
add-credentials: false
core-http-compat-mode: true
use-extension:
"@autorest/typescript": "6.0.0-dev.20210218.1"
package-version: 12.12.0
"@autorest/typescript": "6.0.3"
package-version: 12.20.0
```
## Customizations for Track 2 Generator

Просмотреть файл

@ -42,7 +42,6 @@ describe("Aborter", () => {
assert.fail();
} catch (err: any) {
assert.equal(err.name, "AbortError");
assert.equal(err.message, "The operation was aborted.", "Unexpected error caught: " + err);
}
});
@ -59,7 +58,6 @@ describe("Aborter", () => {
assert.fail();
} catch (err: any) {
assert.equal(err.name, "AbortError");
assert.equal(err.message, "The operation was aborted.", "Unexpected error caught: " + err);
}
});
@ -76,7 +74,6 @@ describe("Aborter", () => {
assert.fail();
} catch (err: any) {
assert.equal(err.name, "AbortError");
assert.equal(err.message, "The operation was aborted.", "Unexpected error caught: " + err);
}
});
});

Просмотреть файл

@ -6,7 +6,6 @@ import { newPipeline } from "../../src";
import { getQSU, getConnectionStringFromEnvironment } from "../utils";
import { record, Recorder } from "@azure-tools/test-recorder";
import { QueueClient } from "../../src/QueueClient";
import { StorageSharedKeyCredential } from "../../src/credentials/StorageSharedKeyCredential";
import { recorderEnvSetup } from "../utils/index.browser";
import { Context } from "mocha";
@ -98,8 +97,7 @@ describe("QueueClient messageId methods, Node.js only", () => {
});
it("can be created with a url and a credential", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const eResult = await queueClient.sendMessage(messageContent);
assert.ok(eResult.messageId);
@ -119,8 +117,7 @@ describe("QueueClient messageId methods, Node.js only", () => {
});
it("can be created with a url and a credential and an option bag", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const eResult = await queueClient.sendMessage(messageContent);
assert.ok(eResult.messageId);
@ -144,8 +141,7 @@ describe("QueueClient messageId methods, Node.js only", () => {
});
it("can be created with a url and a pipeline", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const eResult = await queueClient.sendMessage(messageContent);
assert.ok(eResult.messageId);

Просмотреть файл

@ -5,8 +5,7 @@ import { assert } from "chai";
import { getQSU, getConnectionStringFromEnvironment } from "../utils";
import { record, Recorder } from "@azure-tools/test-recorder";
import { QueueClient } from "../../src/QueueClient";
import { StorageSharedKeyCredential } from "../../src/credentials/StorageSharedKeyCredential";
import { TokenCredential } from "@azure/core-http";
import { TokenCredential } from "@azure/core-auth";
import { assertClientUsesTokenCredential } from "../utils/assert";
import { newPipeline } from "../../src";
import { recorderEnvSetup } from "../utils/index.browser";
@ -107,8 +106,7 @@ describe("QueueClient message methods, Node.js only", () => {
});
it("can be created with a url and a credential", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const newClient = new QueueClient(queueClient.url, credential);
const eResult = await newClient.sendMessage(messageContent);
@ -123,8 +121,7 @@ describe("QueueClient message methods, Node.js only", () => {
});
it("can be created with a url and a credential and an option bag", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const newClient = new QueueClient(queueClient.url, credential, {
retryOptions: {
maxTries: 5,
@ -143,8 +140,7 @@ describe("QueueClient message methods, Node.js only", () => {
});
it("can be created with a url and a pipeline", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const pipeline = newPipeline(credential);
const newClient = new QueueClient(queueClient.url, pipeline);

Просмотреть файл

@ -4,8 +4,8 @@
import { assert } from "chai";
import { getQSU, getConnectionStringFromEnvironment } from "../utils";
import { record, Recorder } from "@azure-tools/test-recorder";
import { newPipeline, QueueClient, StorageSharedKeyCredential } from "../../src";
import { TokenCredential } from "@azure/core-http";
import { newPipeline, QueueClient } from "../../src";
import { TokenCredential } from "@azure/core-auth";
import { assertClientUsesTokenCredential } from "../utils/assert";
import { recorderEnvSetup } from "../utils/testutils.common";
import { Context } from "mocha";
@ -79,8 +79,7 @@ describe("QueueClient Node.js only", () => {
});
it("can be created with a url and a credential", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const newClient = new QueueClient(queueClient.url, credential);
const result = await newClient.getProperties();
@ -92,8 +91,7 @@ describe("QueueClient Node.js only", () => {
});
it("can be created with a url and a credential and an option bag", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const newClient = new QueueClient(queueClient.url, credential, {
retryOptions: {
maxTries: 5,
@ -109,8 +107,7 @@ describe("QueueClient Node.js only", () => {
});
it("can be created with a url and a pipeline", async () => {
const factories = (queueClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueClient["credential"];
const pipeline = newPipeline(credential);
const newClient = new QueueClient(queueClient.url, pipeline);

Просмотреть файл

@ -5,9 +5,8 @@ import { assert } from "chai";
import { getQSU, getConnectionStringFromEnvironment } from "../utils";
import { record, Recorder } from "@azure-tools/test-recorder";
import { QueueServiceClient } from "../../src/QueueServiceClient";
import { StorageSharedKeyCredential } from "../../src/credentials/StorageSharedKeyCredential";
import { newPipeline } from "../../src";
import { TokenCredential } from "@azure/core-http";
import { TokenCredential } from "@azure/core-auth";
import { assertClientUsesTokenCredential } from "../utils/assert";
import { recorderEnvSetup } from "../utils/testutils.common";
import { Context } from "mocha";
@ -25,8 +24,7 @@ describe("QueueServiceClient Node.js only", () => {
it("can be created with a url and a credential", async () => {
const queueServiceClient = getQSU();
const factories = (queueServiceClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueServiceClient["credential"];
const newClient = new QueueServiceClient(queueServiceClient.url, credential);
const result = await newClient.getProperties();
@ -39,8 +37,7 @@ describe("QueueServiceClient Node.js only", () => {
it("can be created with a url and a credential and an option bag", async () => {
const queueServiceClient = getQSU();
const factories = (queueServiceClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueServiceClient["credential"];
const newClient = new QueueServiceClient(queueServiceClient.url, credential, {
retryOptions: {
maxTries: 5,
@ -57,8 +54,7 @@ describe("QueueServiceClient Node.js only", () => {
it("can be created with a url and a pipeline", async () => {
const queueServiceClient = getQSU();
const factories = (queueServiceClient as any).pipeline.factories;
const credential = factories[factories.length - 1] as StorageSharedKeyCredential;
const credential = queueServiceClient["credential"];
const pipeline = newPipeline(credential);
const newClient = new QueueServiceClient(queueServiceClient.url, pipeline);

Просмотреть файл

@ -42,9 +42,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => {
const tmr = recorder.newDate("tmr");
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (queueServiceClient as any).pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
const sharedKeyCredential = queueServiceClient["credential"];
const sas = generateAccountSASQueryParameters(
{
@ -70,9 +68,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => {
const tmr = recorder.newDate("tmr");
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (queueServiceClient as any).pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
const sharedKeyCredential = queueServiceClient["credential"];
const sas = generateAccountSASQueryParameters(
{
@ -104,9 +100,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => {
const tmr = recorder.newDate("tmr");
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (queueServiceClient as any).pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
const sharedKeyCredential = queueServiceClient["credential"];
const sas = generateAccountSASQueryParameters(
{
@ -138,9 +132,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => {
const tmr = recorder.newDate("tmr");
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (queueServiceClient as any).pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
const sharedKeyCredential = queueServiceClient["credential"];
const sas = generateAccountSASQueryParameters(
{
@ -178,9 +170,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => {
const tmr = recorder.newDate("tmr");
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (queueServiceClient as any).pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
const sharedKeyCredential = queueServiceClient["credential"];
const queueName = recorder.getUniqueName("queue");
const queueClient = queueServiceClient.getQueueClient(queueName);
@ -213,9 +203,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => {
const tmr = recorder.newDate("tmr");
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (queueServiceClient as any).pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
const sharedKeyCredential = queueServiceClient["credential"];
const queueName = recorder.getUniqueName("queue");
const queueClient = queueServiceClient.getQueueClient(queueName);
@ -264,9 +252,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => {
const tmr = recorder.newDate("tmr");
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (queueServiceClient as any).pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
const sharedKeyCredential = queueServiceClient["credential"];
const queueName = recorder.getUniqueName("queue");
const queueClient = queueServiceClient.getQueueClient(queueName);

Просмотреть файл

@ -6,7 +6,7 @@ import { getQSU, getSASConnectionStringFromEnvironment } from "./utils";
import { QueueClient, QueueServiceClient } from "../src";
import { setSpan, context } from "@azure/core-tracing";
import { SpanGraph, setTracer } from "@azure/test-utils";
import { RestError } from "@azure/core-http";
import { RestError } from "@azure/core-rest-pipeline";
import { Recorder, record } from "@azure-tools/test-recorder";
import { recorderEnvSetup } from "./utils/testutils.common";
import { Context } from "mocha";
@ -216,12 +216,7 @@ describe("QueueClient", () => {
children: [
{
name: "Azure.Storage.Queue.QueueClient-getProperties",
children: [
{
name: "HTTP GET",
children: [],
},
],
children: [],
},
],
},
@ -235,7 +230,7 @@ describe("QueueClient", () => {
describe("QueueClient - Verify Name Properties", () => {
const queueName = "queueName";
const accountName = "myAccount";
const accountName = "myaccount";
function verifyNameProperties(url: string, inputAccountName: string, inputQueueName: string) {
const newClient = new QueueClient(url);

Просмотреть файл

@ -1,158 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { URLBuilder } from "@azure/core-http";
import { assert } from "chai";
import { QueueClient, RestError, newPipeline, QueueServiceClient } from "../src";
import { AbortController } from "@azure/abort-controller";
import { Pipeline } from "../src/Pipeline";
import { getQSU } from "./utils";
import { InjectorPolicyFactory } from "./utils/InjectorPolicyFactory";
import { record, Recorder } from "@azure-tools/test-recorder";
import { recorderEnvSetup } from "./utils/index.browser";
import { Context } from "mocha";
describe("RetryPolicy", () => {
let queueServiceClient: QueueServiceClient;
let queueName: string;
let queueClient: QueueClient;
let recorder: Recorder;
beforeEach(async function (this: Context) {
recorder = record(this, recorderEnvSetup);
queueServiceClient = getQSU();
queueName = recorder.getUniqueName("queue");
queueClient = queueServiceClient.getQueueClient(queueName);
await queueClient.create();
});
afterEach(async function () {
await queueClient.delete();
await recorder.stop();
});
it("Retry policy should work when first request fails with 500", async () => {
let injectCounter = 0;
const injector = new InjectorPolicyFactory(() => {
if (injectCounter === 0) {
injectCounter++;
return new RestError("Server Internal Error", "ServerInternalError", 500);
}
});
const factories = (queueClient as any).pipeline.factories.slice(); // clone factories array
factories.push(injector);
const pipeline = new Pipeline(factories);
const injectqueueClient = new QueueClient(queueClient.url, pipeline);
const metadata = {
key0: "val0",
keya: "vala",
keyb: "valb",
};
await injectqueueClient.setMetadata(metadata);
const result = await queueClient.getProperties();
assert.deepEqual(result.metadata, metadata);
});
it("Retry Policy should abort when abort event trigger during retry interval", async () => {
let injectCounter = 0;
const injector = new InjectorPolicyFactory(() => {
if (injectCounter < 2) {
injectCounter++;
return new RestError("Server Internal Error", "ServerInternalError", 500);
}
});
const factories = (queueClient as any).pipeline.factories.slice(); // clone factories array
factories.push(injector);
const pipeline = new Pipeline(factories);
const injectqueueClient = new QueueClient(queueClient.url, pipeline);
const metadata = {
key0: "val0",
keya: "vala",
keyb: "valb",
};
let hasError = false;
try {
// Default exponential retry delay is 4000ms. Wait for 2000ms to abort which makes sure the aborter
// happens between 2 requests
await injectqueueClient.setMetadata(metadata, {
abortSignal: AbortController.timeout(2 * 1000),
});
} catch (err: any) {
hasError = true;
}
assert.ok(hasError);
});
it("Retry policy should failed when requests always fail with 500", async () => {
const injector = new InjectorPolicyFactory(() => {
return new RestError("Server Internal Error", "ServerInternalError", 500);
});
const credential = (queueClient as any).pipeline.factories[
(queueClient as any).pipeline.factories.length - 1
];
const factories = newPipeline(credential, {
retryOptions: { maxTries: 3 },
}).factories;
factories.push(injector);
const pipeline = new Pipeline(factories);
const injectqueueClient = new QueueClient(queueClient.url, pipeline);
let hasError = false;
try {
const metadata = {
key0: "val0",
keya: "vala",
keyb: "valb",
};
await injectqueueClient.setMetadata(metadata);
} catch (err: any) {
hasError = true;
}
assert.ok(hasError);
});
it("Retry policy should work for secondary endpoint", async () => {
let injectCounter = 0;
const injector = new InjectorPolicyFactory(() => {
if (injectCounter++ < 1) {
return new RestError("Server Internal Error", "ServerInternalError", 500);
}
});
const url = queueServiceClient.url;
const urlParsed = URLBuilder.parse(url);
const host = urlParsed.getHost()!;
const hostParts = host.split(".");
const account = hostParts.shift();
const secondaryAccount = `${account}-secondary`;
hostParts.unshift(secondaryAccount);
const secondaryHost = hostParts.join(".");
const credential = (queueClient as any).pipeline.factories[
(queueClient as any).pipeline.factories.length - 1
];
const factories = newPipeline(credential, {
retryOptions: { maxTries: 2, secondaryHost },
}).factories;
factories.push(injector);
const pipeline = new Pipeline(factories);
const injectqueueClient = new QueueClient(queueClient.url, pipeline);
let finalRequestURL = "";
try {
const response = await injectqueueClient.getProperties();
finalRequestURL = response._response.request.url;
} catch (err: any) {
finalRequestURL = err.request ? err.request.url : "";
}
assert.deepStrictEqual(URLBuilder.parse(finalRequestURL).getHost(), secondaryHost);
});
});

Просмотреть файл

@ -2,7 +2,6 @@
// Licensed under the MIT license.
import { assert } from "chai";
import { HttpHeaders } from "../src";
import {
sanitizeHeaders,
sanitizeURL,
@ -11,7 +10,7 @@ import {
} from "../src/utils/utils.common";
import { record, Recorder } from "@azure-tools/test-recorder";
import { recorderEnvSetup } from "./utils/testutils.common";
import { URLBuilder } from "@azure/core-http";
import { createHttpHeaders } from "@azure/core-rest-pipeline";
import { Context } from "mocha";
describe("Utility Helpers", () => {
@ -59,7 +58,7 @@ describe("Utility Helpers", () => {
it("sanitizeHeaders redacts SAS token", () => {
const url = "https://some.url.com/container/blob?sig=sasstring";
const headers = new HttpHeaders();
const headers = createHttpHeaders();
headers.set("authorization", "Bearer abcdefg");
headers.set("x-ms-copy-source", url);
headers.set("otherheader", url);
@ -123,44 +122,30 @@ describe("Utility Helpers", () => {
it("isIpEndpointStyle", async () => {
assert.equal(
isIpEndpointStyle(
URLBuilder.parse("https://192.0.0.10:1900/accountName/containerName/blobName")
),
isIpEndpointStyle(new URL("https://192.0.0.10:1900/accountName/containerName/blobName")),
true
);
assert.equal(
isIpEndpointStyle(
URLBuilder.parse(
new URL(
"https://[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443/accountName/containerName/blobName"
)
),
true
);
assert.equal(
isIpEndpointStyle(
URLBuilder.parse("https://localhost:80/accountName/containerName/blobName")
),
isIpEndpointStyle(new URL("https://localhost:80/accountName/containerName/blobName")),
true
);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://192.0.0.10:1900/")), true);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://192.0.0.10")), true);
assert.equal(isIpEndpointStyle(new URL("https://192.0.0.10:1900/")), true);
assert.equal(isIpEndpointStyle(new URL("https://192.0.0.10")), true);
assert.equal(
isIpEndpointStyle(
URLBuilder.parse("https://2001:db8:85a3:8d3:1319:8a2e:370:7348/accountName/containerName")
new URL("https://[2001:db8:85a3:8d3:1319:8a2e:370:7348]/accountName/containerName")
),
true
);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://2001::1")), true);
// assert.equal(isIpEndpointStyle(URLBuilder.parse('https://::1')), true); currently not working due to http url.ts's issue. uncomment after core lib fixed.
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://255")), false);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://255.255")), false);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://a.b.c.d")), false);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://256.1.1.1")), false);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://255.256.1.1")), false);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://255.255.256.1")), false);
assert.equal(isIpEndpointStyle(URLBuilder.parse("https://255.255.255.256")), false);
});
});

Просмотреть файл

@ -1,48 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
BaseRequestPolicy,
HttpOperationResponse,
RequestPolicy,
RequestPolicyOptions,
WebResource,
RestError,
} from "../../src";
export interface NextInjectErrorHolder {
nextInjectError?: RestError;
}
export type Injector = () => RestError | undefined;
/**
* InjectorPolicy will inject a customized error before next HTTP request.
*/
export class InjectorPolicy extends BaseRequestPolicy {
/**
* Creates an instance of InjectorPolicy.
*
* @param nextPolicy -
* @param options -
*/
public constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, injector: Injector) {
super(nextPolicy, options);
this.injector = injector;
}
/**
* Sends request.
*
* @param request -
*/
public async sendRequest(request: WebResource): Promise<HttpOperationResponse> {
const error = this.injector();
if (error) {
throw error;
}
return this._nextPolicy.sendRequest(request);
}
private injector: Injector;
}

Просмотреть файл

@ -1,20 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "../../src";
import { InjectorPolicy, Injector } from "./InjectorPolicy";
/**
* InjectorPolicyFactory is a factory class injects customized errors for retry policy testing.
*/
export class InjectorPolicyFactory implements RequestPolicyFactory {
public readonly injector: Injector;
public constructor(injector: Injector) {
this.injector = injector;
}
public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): InjectorPolicy {
return new InjectorPolicy(nextPolicy, options, this.injector);
}
}

Просмотреть файл

@ -3,9 +3,9 @@
import { assert } from "chai";
import { StorageClient } from "../../src/StorageClient";
import { isTokenCredential } from "@azure/core-auth";
export function assertClientUsesTokenCredential(client: StorageClient): void {
const factories = (client as any).pipeline.factories;
const authPolicy = factories[factories.length - 1].create();
assert.strictEqual(authPolicy.constructor.name, "BearerTokenAuthenticationPolicy");
const credential = client["credential"];
assert.isTrue(isTokenCredential(credential));
}

Просмотреть файл

@ -1,15 +1,23 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { AnonymousCredential } from "../../src/credentials/AnonymousCredential";
import { newPipeline } from "../../src/Pipeline";
import { isLiveMode } from "@azure-tools/test-recorder";
import { AnonymousCredential } from "../../../storage-blob/src/credentials/AnonymousCredential";
import { newPipeline } from "../../../storage-blob/src/Pipeline";
import { QueueServiceClient } from "../../src/QueueServiceClient";
import { createXhrHttpClient } from "@azure/test-utils";
import { setTestOnlySetHttpClient } from "../../src/StorageClient";
export * from "./testutils.common";
export function getGenericQSU(
accountType: string,
accountNameSuffix: string = ""
): QueueServiceClient {
// only needed until we can migrate to test recorder v2
if (!isLiveMode()) {
setTestOnlySetHttpClient(createXhrHttpClient());
}
const accountNameEnvVar = `${accountType}ACCOUNT_NAME`;
const accountSASEnvVar = `${accountType}ACCOUNT_SAS`;
@ -28,11 +36,13 @@ export function getGenericQSU(
accountSAS = accountSAS.startsWith("?") ? accountSAS : `?${accountSAS}`;
}
// don't add the test account SAS value.
if (accountSAS === "?fakeSasToken") {
accountSAS = "";
}
const credentials = new AnonymousCredential();
const pipeline = newPipeline(credentials, {
// Enable logger when debugging
// logger: new ConsoleHttpPipelineLogger(HttpPipelineLogLevel.INFO)
});
const pipeline = newPipeline(credentials);
const filePrimaryURL = `https://${accountName}${accountNameSuffix}.queue.core.windows.net${accountSAS}`;
return new QueueServiceClient(filePrimaryURL, pipeline);
}
@ -113,14 +123,17 @@ export function getBrowserFile(name: string, size: number): File {
}
export function getSASConnectionStringFromEnvironment(): string {
// only needed until we can migrate to test recorder v2
if (!isLiveMode()) {
setTestOnlySetHttpClient(createXhrHttpClient());
}
const env = (self as any).__env__;
return `BlobEndpoint=https://${env.ACCOUNT_NAME}.blob.core.windows.net/;QueueEndpoint=https://${
env.ACCOUNT_NAME
}.queue.core.windows.net/;FileEndpoint=https://${
env.ACCOUNT_NAME
}.file.core.windows.net/;TableEndpoint=https://${
env.ACCOUNT_NAME
}.table.core.windows.net/;SharedAccessSignature=${env.ACCOUNT_SAS.substring(1)}`;
// env.ACCOUNT_SAS.substring(1) - to remove the `?` in ACCOUNT_SAS
// SAS Connection String doesn't have `?` in the `SharedAccessSignature`
let sasToken: string = env.ACCOUNT_SAS;
// connection string SAS doesn't have the prefix
if (sasToken && sasToken.startsWith("?")) {
sasToken = sasToken.slice(1);
}
return `BlobEndpoint=https://${env.ACCOUNT_NAME}.blob.core.windows.net/;QueueEndpoint=https://${env.ACCOUNT_NAME}.queue.core.windows.net/;FileEndpoint=https://${env.ACCOUNT_NAME}.file.core.windows.net/;TableEndpoint=https://${env.ACCOUNT_NAME}.table.core.windows.net/;SharedAccessSignature=${sasToken}`;
}

Просмотреть файл

@ -1,8 +1,8 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { StorageSharedKeyCredential } from "../../src/credentials/StorageSharedKeyCredential";
import { newPipeline } from "../../src/Pipeline";
import { StorageSharedKeyCredential } from "../../../storage-blob/src/credentials/StorageSharedKeyCredential";
import { newPipeline } from "../../../storage-blob/src/Pipeline";
import { QueueServiceClient } from "../../src/QueueServiceClient";
import {
generateAccountSASQueryParameters,
@ -14,10 +14,6 @@ import {
import { extractConnectionStringParts } from "../../src/utils/utils.common";
import { env } from "@azure-tools/test-recorder";
// Uncomment if need to enable logger when debugging
// import {HttpPipelineLogLevel} from "../../src"
// import {ConsoleHttpPipelineLogger} from "./testutils.common"
export function getGenericQSU(
accountType: string,
accountNameSuffix: string = ""
@ -76,9 +72,7 @@ export function getSASConnectionStringFromEnvironment(): string {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
const queueServiceClient = getQSU();
// By default, credential is always the last element of pipeline factories
const factories = (queueServiceClient as any).pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
const sharedKeyCredential = queueServiceClient["credential"];
const sas = generateAccountSASQueryParameters(
{

Просмотреть файл

@ -9,6 +9,7 @@ export function isBrowser(): boolean {
const mockAccountName = "fakestorageaccount";
const mockAccountKey = "aaaaa";
const mockSas = "fakeSasToken";
export const recorderEnvSetup: RecorderEnvironmentSetup = {
replaceableVariables: {
// Used in record and playback modes
@ -16,7 +17,7 @@ export const recorderEnvSetup: RecorderEnvironmentSetup = {
// 2. If the env variables are present in the recordings as plain strings, they will be replaced with the provided values in record mode
ACCOUNT_NAME: `${mockAccountName}`,
ACCOUNT_KEY: `${mockAccountKey}`,
ACCOUNT_SAS: `${mockAccountKey}`,
ACCOUNT_SAS: `${mockSas}`,
STORAGE_CONNECTION_STRING: `DefaultEndpointsProtocol=https;AccountName=${mockAccountName};AccountKey=${mockAccountKey};EndpointSuffix=core.windows.net`,
// Comment following line to skip user delegation key/SAS related cases in record and play
// which depends on this environment variable

Просмотреть файл

@ -24,5 +24,10 @@
"@azure/storage-queue": ["./src/index"]
}
},
"include": ["./src/**/*.ts", "./test/**/*.ts", "./samples-dev/**/*.ts"]
"include": [
"./src/**/*.ts",
"./test/**/*.ts",
"./samples-dev/**/*.ts",
"../storage-blob/src/**/*.ts"
]
}