Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[@azure-rest/batch] update service api version to 2024-07-01 #31468

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .vscode/cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@
"Cifs",
"dataserviceid",
"uefi",
"Uefi"
"Uefi",
"Reimage"
],
"allowCompoundWords": true,
"overrides": [
Expand Down
6 changes: 6 additions & 0 deletions sdk/batch/batch-rest/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Release History

## 1.0.0-beta.2 (2024-11-07)

### Features Added

- Update API version to `2024-07-01.20.0` for Azure Batch service.

## 1.0.0-beta.1 (2024-08-07)

### Features Added
Expand Down
21 changes: 21 additions & 0 deletions sdk/batch/batch-rest/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2024 Microsoft

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
265 changes: 265 additions & 0 deletions sdk/batch/batch-rest/MigrationGuide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
# Guide for migrating to `@azure-rest/batch` from `@azure/batch`

This guide is intended to assist customers in the migration to `@azure-rest/batch` from the legacy `@azure/batch` package. It will focus on side-by-side comparisons for similar operations between the two packages.

Familiarity with the legacy client library is assumed. For those new to the Azure Batch JavaScript client library, please refer to [README](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/batch/batch-rest/README.md) and [samples](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/batch/batch-rest/samples) of `@azure-rest/batch` instead of this guide.

## Table of contents

- [Migration benefits](#migration-benefits)
- [Constructing the clients](#constructing-the-clients)
- [Authenticate with shared key credentials](#authenticate-with-shared-key-credentials)
- [Authenticate with Microsoft Entra ID](#authenticate-with-microsoft-entra-id)
- [Operation response differences](#operation-response-differences)
- [Error handling](#error-handling)
- [More Examples](#more-examples)
- [Create pools](#create-pools)
- [Create jobs](#create-jobs)
- [Submit tasks](#submit-tasks)

## Migration benefits

- Reduced package sizes, `@azure-rest/batch` comes in a form called Rest Level Client(RLC), which is much more lightwight than the traditional Modular Client like `@azure/batch`. It take advantages of Typescript type inferences and reduce bundle size if you were to use it in a browser environment. For more referece of RLC, please see this [doc](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/rest-clients.md) and our introduction [blog](https://devblogs.microsoft.com/azure-sdk/azure-rest-libraries-for-javascript/).

- Embrace the lastest Azure JavaScript SDK ecosystem, for example it works [`@azure/identiy`](https://www.npmjs.com/package/@azure/identity) to simplify authentication during local development and with Azure Entra. It also benefit from the onsistant paging API and unified logging with [`@azure/logger`](https://www.npmjs.com/package/@azure/logger) across all Azure Javascript SDKs.

- Get the latest features/ API versions of Azure Batch service, as we are planing to deprecate the `@azure/batch` package, it may not contain the lastes updates of the Azure Batch service, while with `@azure-rest/batch` you can use the latest API version of Azure Batch service.

## Constructing the clients

### Authenticate with shared key credentials

Both `@azure/batch` and `@azure-rest/batch` support shared key authentication.

Previously in `@azure/batch`, you can use the `BatchSharedKeyCredentials` class exported from `@azure/batch` to construct a shared key credential, then pass the credential and account endpoint to the `BatchServiceClient` constructor to create a client instance.

```typescript
import { BatchSharedKeyCredentials, BatchServiceClient } from '@azure/batch';

const credential = new BatchSharedKeyCredentials("<account-name>", "<account-key>");
const client = new BatchServiceClient(credential, "<account-endpoint>");
```

Now in `@azure-rest/batch`, you need to install [`@azure/core-auth`](https://www.npmjs.com/package/@azure/core-auth) package and use the `AzureNamedKeyCredential` class exported from `@azure/core-auth` to construct a shared key credential, then pass the credential and account endpoint to the default exported `createClient` method from `@azure-rest/batch` to create a client instance.

```typescript
import { AzureNamedKeyCredential } from "@azure/core-auth";
import createClient from "@azure-rest/batch";

const credential = new AzureNamedKeyCredential("<account-name>", "<account-key>");
const client = createClient("<account-endpoint>", credential);
```

### Authenticate with Microsoft Entra ID

Previously in `@azure/batch`, it only support the legacy [@azure/ms-rest-nodeauth](https://www.npmjs.com/package/@azure/ms-rest-nodeauth) package, and the browser environment is not supported. The following example use the `loginWithVmMSI` method exported from `@azure/ms-rest-nodeauth` to authenticate with the Azure Batch service using MSI (Managed Service Identity) based login from a virtual machine created in Azure.

```typescript
import { BatchServiceClient } from "@azure/batch";
import { loginWithVmMSI } from "@azure/ms-rest-nodeauth";

const credential = await loginWithVmMSI({
resource: "https://batch.core.windows.net/"
});
const client = new BatchServiceClient(credential, "<account-endpoint>");
```

Now in `@azure-rest/batch`, you can pass any of the [credentials from the `@azure/identity` package](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md) to the `createClient` method to make use of your Microsft Entra ID credentials. In following sample, it creates an instance of [`DefaultAzureCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/defaultazurecredential) to authenticate with the Azure Batch service.

```typescript
import { DefaultAzureCredential } from "@azure/identity";
import createClient from "@azure-rest/batch";

const credential = new DefaultAzureCredential();
const client = createClient("<account-endpoint>", credential);
```

## Operation response differences

Previously in `@azure/batch`, the client operation return a `Promise` that resolves to the result of the response body JSON. The following example demonstrates how to get a job with the `BatchServiceClient` instance.

```typescript
const job = await client.job.get("<job-id>");
console.log(`Job id: ${job.id}, state: ${job.state}`);
```

Now in `@azure-rest/batch`, the client operation return a `Promise` that resolves to the response object, which contains the response body and the status code. In order to get the response body JSON, you need to first check if the response is unexpected with the `isUnexpected` helper method, then access the response body. The following example demonstrates how to get a job in `@azure-rest/batch`.

```typescript
import { isUnexpected } from '@azure-rest/batch';
const response = await client.path("/jobs/{jobId}", "<job-id>").get();
if (isUnexpected(response)) {
throw new Error(`Failed to get job: ${response.body.message}`);
}
console.log(`Response status code: ${response.status}`);

const job = response.body;
console.log(`Job id: ${job.id}, state: ${job.state}`);
```

## Error handling

Previously in `@azure/batch`, the client operation succeed only when service return expected HTTP status code, for example `201` for create resources operations or `200` for general HTTP GET requests. Unexpected HTTP status code will throw a `RestError` from `@azure/ms-rest-js` package. The following example demonstrate how to handle different errors might occur in the get pool request.

```typescript
import { RestError } from "@azure/ms-rest-js";

try {
const pool = await client.pool.get("<pool-id>");
console.log("Get pool success: ", pool)
} catch (error) {
if (error instanceof RestError) {
// Returned HTTP status is not 200
console.log(`Service return unexpected status code ${error.statusCode}: ${error.body}`)
} else {
// Other errors like connection errors or other exceptions
console.log("Failed to get pool with error: ", error)
}
}
```

Now, for `@azure-rest/batch`, the client operation won't throw errors even when the returned HTTP status code is unexpected, instead it exports a helper method `isUnexpected` to help you check if the response is unexpected. The following example demostarte how to handle different errors might occur in the get pool request.

```typescript
try {
const response = await client.path("/pools/{poolId}", "<pool-id>").get();
if (isUnexpected(response)) {
// Returned HTTP status is not 200
console.log(`Service return unexpected status code ${response.status}: ${response.body}`)
} {
console.log("Get pool success: ", response.body)
}
} catch (error) {
// Other errors like connection errors or other exceptions
console.log("Failed to get pool with error: ", error)
}
```

## More examples

### Create pools

Previously in `@azure/batch`, you can use the `BatchServiceClient` instance to create a pool with the `pool.add` method. The following example demonstrates how to create a pool with the `BatchServiceClient` instance.

```typescript
import { BatchServiceModels } from "@azure/batch";
import { RestError } from "@azure/ms-rest-js";
const poolParams: BatchServiceModels.PoolAddParameter = {
id: "<pool-name>",
vmSize: "Standard_D1_v2",
virtualMachineConfiguration: {
nodeAgentSKUId: "batch.node.windows amd64",
imageReference: {
publisher: "microsoftwindowsserver",
offer: "windowsserver",
sku: "2022-datacenter",
},
},
networkConfiguration: {
enableAcceleratedNetworking: true,
},
targetDedicatedNodes: 1,
};
const result = await client.pool.add(poolParams);
console.log("Pool created");
```

Now in `@azure-rest/batch`, you can use the `path` method of the client instance to send a POST request to the `/pools` endpoint with the pool parameters. Note the `CreatePoolParameters` interface has a `body` field to hold the request body and a `contentType` field to specify the content type of the request.

```typescript
import { CreatePoolParameters, isUnexpected } from "@azure-rest/batch"

const poolParams: CreatePoolParameters = {
body: {
id: "<pool-name>",
vmSize: "Standard_D1_v2",
virtualMachineConfiguration: {
nodeAgentSKUId: "batch.node.windows amd64",
imageReference: {
publisher: "microsoftwindowsserver",
offer: "windowsserver",
sku: "2022-datacenter",
},
},
networkConfiguration: {
enableAcceleratedNetworking: true,
},
targetDedicatedNodes: 1,
},
contentType: "application/json; odata=minimalmetadata",
};

const result = await client.path("/pools").post(poolParams);
if (isUnexpected(result)) {
throw new Error(`Failed to create pool: ${result.body.message}`);
}
console.log("Pool created");
```

## Create jobs

Previously in `@azure/batch`, you can use the `BatchServiceClient` instance to create a job with the `job.add` method. The following example demonstrates how to create a job with the `BatchServiceClient` instance.

```typescript
import { BatchServiceModels } from "@azure/batch"
const jobAddParam: BatchServiceModels.JobAddParameter = {
id: "<job-id>",
poolInfo: { poolId: "<pool-id>" },
};
const result = await client.job.add(JobAddParameter);
console.log("Job created");
```

Now in `@azure-rest/batch`, you can use the `path` method of the client instance to send a POST request to the `/jobs` endpoint with the job parameters.

```typescript
import { CreateJobParameters, isUnexpected } from "@azure-rest/batch"

const jobAddParam: CreateJobParameters = {
body: {
id: "<job-id>",
poolInfo: { poolId: "<pool-id>" },
},
contentType: "application/json; odata=minimalmetadata",
};

const result = await client.path("/jobs").post(jobAddParam);
if (isUnexpected(result)) {
throw new Error(`Failed to create job: ${result.body.message}`);
}
console.log(`Job created`);
```

## Submit tasks

Previously in `@azure/batch`, you can use the `BatchServiceClient` instance to submit a task to a job with the `task.add` method. The following example demonstrates how to submit a task with the `BatchServiceClient` instance.

```typescript
import { BatchServiceModels } from "@azure/batch"
const taskAddParam: BatchServiceModels.TaskAddParameter = {
id: "<task-id>",
commandLine: "cmd /c echo hello",
};
const result = await client.task.add("<job-id>", taskAddParam);
console.log("Task submitted");
```

Now in `@azure-rest/batch`, you can use the `path` method of the client instance to send a POST request to the `/jobs/{jobId}/tasks` endpoint with the task parameters.

```typescript
import { CreateTaskParameters, isUnexpected } from "@azure-rest/batch"

const taskAddParam: CreateTaskParameters = {
body: {
id: "<task-id>",
commandLine: "cmd /c echo hello",
},
contentType: "application/json; odata=minimalmetadata",
};

const result = await client.path("/jobs/{jobId}/tasks", "<job-id>").post(taskAddParam);
if (isUnexpected(result)) {
throw new Error(`Failed to submit task: ${result.body.message}`);
}
console.log("Task submitted");
```
3 changes: 2 additions & 1 deletion sdk/batch/batch-rest/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ Azure Batch provides Cloud-scale job scheduling and compute management.

Key links:

TODO: Add links back when the package is published
- [Package (NPM)](https://www.npmjs.com/package/@azure-rest/batch)
- [API reference documentation](https://docs.microsoft.com/javascript/api/@azure-rest/batch?view=azure-node-preview)

## Getting started

Expand Down
2 changes: 1 addition & 1 deletion sdk/batch/batch-rest/assets.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "js",
"TagPrefix": "js/batch/batch-rest",
"Tag": "js/batch/batch-rest_dee9657e"
"Tag": "js/batch/batch-rest_f23a4f3e48"
}
2 changes: 1 addition & 1 deletion sdk/batch/batch-rest/generated/batchClient.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading