Skip to content

Commit

Permalink
Final fixes for v1 to support Codespaces
Browse files Browse the repository at this point in the history
  • Loading branch information
jmatthiesen committed Oct 28, 2024
1 parent abae645 commit b90fed5
Show file tree
Hide file tree
Showing 13 changed files with 218 additions and 80 deletions.
43 changes: 35 additions & 8 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,56 @@

// Features to add to the dev container. More info: https://containers.dev/features.
"features": {
"ghcr.io/devcontainers/features/azure-cli:1": {
"installBicep": true,
"version": "latest"
},
"ghcr.io/azure/azure-dev/azd:latest": {
"version": "stable"
},
"ghcr.io/devcontainers/features/dotnet:2": {
}
"ghcr.io/devcontainers/features/dotnet:2": {}
},

"customizations": {
"vscode": {
"codespaces": {
"openFiles": ["docs/get-started-codespaces.md"]
},
"vscode": {
"extensions": [
"ms-dotnettools.csdevkit",
"ms-dotnettools.vscode-dotnet-runtime",
"GitHub.vscode-github-actions",
"ms-azuretools.azure-dev",
"ms-azuretools.vscode-bicep",
"ms-azuretools.vscode-docker",
"ms-vscode.js-debug" ]
"ms-vscode.js-debug"],
"settings": {
"remote.autoForwardPorts": false
}
}
},

// Workarounds to run .NET Aspire in CodeSpaces until future support is added
"containerEnv": {
"ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true",
"DOTNET_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS ": "true"
},

"forwardPorts": [7243, 17099],

"portsAttributes": {
"17099": {
"label": "Dashboard HTTPS",
"protocol": "https"
},
"7243": {
"label": "Web HTTPS",
"protocol": "https"
},
"5153": {
"label": "Web HTTPS"
},
"15282": {
"label": "Dashboard HTTP"
}
},

"postCreateCommand": "dotnet dev-certs https --trust" // Enable HTTPS support

// Use 'forwardPorts' to make a list of ports inside the container available locally.
Expand Down
5 changes: 3 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
"version": "0.2.0",
"configurations": [
{
"name": "C#: AppHost Debug",
"name": "C#: AIChatApp.AppHost [https]",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/AIChatApp.AppHost/AIChatApp.AppHost.csproj"
"projectPath": "${workspaceFolder}/src/AIChatApp.AppHost/AIChatApp.AppHost.csproj",
"launchConfigurationId": "TargetFramework=;https"
}

]
Expand Down
33 changes: 21 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,24 @@ since the local app needs credentials for Azure OpenAI to work properly.

You have a few options for getting started with this template.

### GitHub Codespaces

You can run this template virtually by using GitHub Codespaces. The button will open a web-based VS Code instance in your browser:

1. Open the template (this may take several minutes):

[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/Azure-Samples/ai-chat-aspire-sk-csharp)

2. Open a terminal window
3. Continue with the [deploying steps](#deploying)

### Local Environment

If you're not using one of the above options for opening the project, then you'll need to:

1. Make sure the following tools are installed:

* [.NET 8](https://dotnet.microsoft.com/downloads/)
* With the [.NET Aspire workload installed](https://learn.microsoft.com/dotnet/aspire/fundamentals/setup-tooling?tabs=windows&pivots=visual-studio#install-net-aspire) using `dotnet workload install aspire`
* [Git](https://git-scm.com/downloads)
* [Azure Developer CLI (azd)](https://aka.ms/install-azd)
* [VS Code](https://code.visualstudio.com/Download) or [Visual Studio](https://visualstudio.microsoft.com/downloads/)
Expand Down Expand Up @@ -77,10 +87,6 @@ Visual Stuido Code Dev Containers can also be used locally, which will open the

4. Continue with the [deploying steps](#deploying)

### GitHub Codespaces

**Coming soon** - GitHub Codespaces support works best with Aspire 9, which is coming soon. For now, you can load the project and build in CodeSpaces, but won't be able to run.
## Deploying

Once you've opened the project [locally](#local-environment) or in [Dev Containers](#vs-code-dev-containers), you can deploy it to Azure.
Expand All @@ -103,13 +109,14 @@ From a Terminal window, open the folder with the clone of this repo and run the
azd auth login
```

2. Provision and deploy all the resources:
2. Provision and deploy dependencies for the project:

```shell
azd up
azd env new <environment>
azd provision
```

It will prompt you to provide an `azd` environment name (like "chat-app"), select a subscription from your Azure account, and select a [location where OpenAI is available](https://azure.microsoft.com/explore/global-infrastructure/products-by-region/?products=cognitive-services&regions=all) (like "francecentral"). Then it will provision the resources in your account and deploy the latest code. If you get an error or timeout with deployment, changing the location can help, as there may be availability constraints for the OpenAI resource.
You'll need to replace <envrionment> with an environment name you want to use (like "chat-app"), which will be used as a prefix for resources in Azure. Select a subscription from your Azure account, and select a [location where OpenAI is available](https://azure.microsoft.com/explore/global-infrastructure/products-by-region/?products=cognitive-services&regions=all) (like "francecentral"). Then it will provision the resources in your account and deploy the latest code. If you get an error or timeout with deployment, changing the location can help, as there may be availability constraints for the OpenAI resource.
3. When `azd` has finished deploying, you'll see an endpoint URI in the command output. Visit that URI, and you should see the chat app! 🎉

Expand All @@ -121,16 +128,18 @@ From a Terminal window, open the folder with the clone of this repo and run the
## Run the application
Start the project:
Start the project by pressing the F5 key (or clicking the Run button in the Run & Debug sidebar).
**If using Visual Studio**, choose the `Debug > Start Debugging` menu.
**If using VS Code or GitHub CodeSpaces***, choose the `Run > Start Debugging` menu.
Finally, if using the command line, run the following from the project directory:
If using the command line, run the following from the `src` directory:
```shell
dotnet run
```
In the Debug Console (or Terminal window) that appears, you'll see status messages written as the .NET Aspire application starts up. When it's finished starting, look for the text that says something like `Login to the dashboard at https://localhost:17099/login?t=8e08b4369732034c8d67dc80f54fa1db`. Copy the text after "t=" - in this example you'd copy the text "8e08b4369732034c8d67dc80f54fa1db" this is a token you'll use to login to the .NET Aspire Dashboard. Then, click on the https://localhost:17099 URL, paste the token you just copied, and login.
Finally, in the dashboard that appears you'll see the aichatapp-web resource listed. Click on the URL under the Endpoints column to launch the web application and try the chat experience.

## Using an existing deployment

In order to run this app, you need to have an Azure OpenAI account deployed (from the [deploying steps](#deploying)). After deployment, Azure OpenAI is configured for you using [User Secrets](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets). If you could not run the deployment steps here, or you want to use an existing Azure OpenAI resource and deployment, open a terminal from the root of this repo and run the following
Expand Down
2 changes: 1 addition & 1 deletion azure.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ hooks:
posix:
shell: sh
run: ./infra/post-script/store-env-variables.sh
interactive: false
interactive: true
continueOnError: true
63 changes: 63 additions & 0 deletions docs/get-started-codespaces.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Provision Azure resources

Once you've opened the project, you can deploy its dependencies to Azure.

## Azure account setup

1. Sign up for a [free Azure account](https://azure.microsoft.com/free/) and create an Azure Subscription.
2. Check that you have the necessary permissions:

* Your Azure account must have `Microsoft.Authorization/roleAssignments/write` permissions, such as [Role Based Access Control Administrator](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles#role-based-access-control-administrator-preview), [User Access Administrator](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles#user-access-administrator), or [Owner](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles#owner). If you don't have subscription-level permissions, you must be granted [RBAC](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles#role-based-access-control-administrator-preview) for an existing resource group and [deploy to that existing group](/docs/deploy_existing.md#resource-group).
* Your Azure account also needs `Microsoft.Resources/deployments/write` permissions on the subscription level.

## Deploying with azd

From a Terminal window, open the folder with the clone of this repo and run the following commands.

1. Login to Azure:

```shell
azd auth login
```

2. Provision and deploy dependencies for the project:

```shell
azd env new <environment>
azd provision
```

You'll need to replace <envrionment> with an environment name you want to use (like "chat-app"), which will be used as a prefix for resources in Azure. Select a subscription from your Azure account, and select a [location where OpenAI is available](https://azure.microsoft.com/explore/global-infrastructure/products-by-region/?products=cognitive-services&regions=all) (like "francecentral"). Then it will provision the resources in your account and deploy the latest code. If you get an error or timeout with deployment, changing the location can help, as there may be availability constraints for the OpenAI resource.
3. When `azd` has finished deploying, you'll see an endpoint URI in the command output. Visit that URI, and you should see the chat app! 🎉

4. When you've made any changes to the app code, you can just run:
```shell
azd deploy
```
## Run the application
Start the project by pressing the F5 key (or clicking the Run button in the Run & Debug sidebar).
If using the command line, run the following from the `src` directory:
```shell
dotnet run
```
In the Debug Console (or Terminal window) that appears, you'll see status messages written as the .NET Aspire application starts up. When it's finished starting, look for the text that says something like `Login to the dashboard at https://localhost:17099/login?t=8e08b4369732034c8d67dc80f54fa1db`. Copy the text after "t=" - in this example you'd copy the text "8e08b4369732034c8d67dc80f54fa1db" this is a token you'll use to login to the .NET Aspire Dashboard. Then, click on the https://localhost:17099 URL, paste the token you just copied, and login.
Finally, in the dashboard that appears you'll see the aichatapp-web resource listed. Click on the URL under the Endpoints column to launch the web application and try the chat experience.

## Using an existing deployment

In order to run this app, you need to have an Azure OpenAI account deployed (using the instructions above). After deployment, Azure OpenAI is configured for you using [User Secrets](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets). If you could not run the deployment steps here, or you want to use an existing Azure OpenAI resource and deployment, open a terminal from the root of this repo and run the following

```bash
cd ./src/AIChatApp.AppHost
dotnet user-secrets set "ConnectionStrings:openai" "https://{account_name}.openai.azure.com/"
```

The value for the connection string can be found in the Keys & Endpoint section when examining your resource from the Azure portal. Alternatively, you can find the value in the Azure OpenAI Studio > Playground > Code View. An example endpoint is: https://docs-test-001.openai.azure.com/.
11 changes: 11 additions & 0 deletions infra/main.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ param environmentName string

@minLength(1)
@description('The location used for all deployed resources')
// Look for the desired model in availability table. Default model is gpt-4o-mini:
// https://learn.microsoft.com/azure/ai-services/openai/concepts/models#standard-deployment-model-availability
@allowed([
'eastus'
'eastus2'
'northcentralus'
'southcentralus'
'swedencentral'
'westus'
'westus3'
])
param location string

@description('Id of the user or app to assign application roles')
Expand Down
3 changes: 3 additions & 0 deletions infra/main.parameters.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
},
"location": {
"value": "${AZURE_LOCATION=eastus}"
},
"createRoleForUser": {
"value": "${CREATE_ROLE_FOR_USER=true}"
}
}
}
Expand Down
25 changes: 0 additions & 25 deletions src/AIChatApp.AppHost/AIChatApp.AppHost.sln

This file was deleted.

71 changes: 70 additions & 1 deletion src/AIChatApp.AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Projects;
using System.Collections.Immutable;
using System.Security.Cryptography;

var builder = DistributedApplication.CreateBuilder(args);
var builder = DistributedApplication.CreateBuilder(args)
.WithCodespacesSupport();

var chatDeploymentName = "chat";

Expand All @@ -22,3 +27,67 @@
.WithExternalHttpEndpoints();

builder.Build().Run();

// WORKAROUND: Enables GitHub Codespaces when running in that environment. This will be fixed in a future .NET Aspire release.
public static class CodespaceExtensions
{
public static IDistributedApplicationBuilder WithCodespacesSupport(this IDistributedApplicationBuilder builder)
{
if (!builder.Configuration.GetValue<bool>("CODESPACES"))
{
return builder;
}

builder.Eventing.Subscribe<BeforeStartEvent>((e, ct) => {
_ = Task.Run(() => UrlRewriterAsync(e.Services, ct));
return Task.CompletedTask;
});

return builder;
}

private static async Task UrlRewriterAsync(IServiceProvider services, CancellationToken cancellationToken)
{
var configuration = services.GetRequiredService<IConfiguration>();
var gitHubCodespacesPortForwardingDomain = configuration.GetValue<string>("GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN") ?? throw new DistributedApplicationException("Codespaces was detected but GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN environment missing.");
var codespaceName = configuration.GetValue<string>("CODESPACE_NAME") ?? throw new DistributedApplicationException("Codespaces was detected but CODESPACE_NAME environment missing.");

var rns = services.GetRequiredService<ResourceNotificationService>();

var resourceEvents = rns.WatchAsync(cancellationToken);

await foreach (var resourceEvent in resourceEvents)
{
Dictionary<UrlSnapshot, UrlSnapshot>? remappedUrls = null;

foreach (var originalUrlSnapshot in resourceEvent.Snapshot.Urls)
{
var uri = new Uri(originalUrlSnapshot.Url);

if (!originalUrlSnapshot.IsInternal && (uri.Scheme == "http" || uri.Scheme == "https") && uri.Host == "localhost")
{
if (remappedUrls is null)
{
remappedUrls = new();
}

var newUrlSnapshot = originalUrlSnapshot with {
Url = $"{uri.Scheme}://{codespaceName}-{uri.Port}.{gitHubCodespacesPortForwardingDomain}{uri.AbsolutePath}"
};

remappedUrls.Add(originalUrlSnapshot, newUrlSnapshot);
}
}

if (remappedUrls is not null)
{
var transformedUrls = from originalUrl in resourceEvent.Snapshot.Urls
select remappedUrls.TryGetValue(originalUrl, out var remappedUrl) ? remappedUrl : originalUrl;

await rns.PublishUpdateAsync(resourceEvent.Resource, resourceEvent.ResourceId, s => s with {
Urls = transformedUrls.ToImmutableArray()
});
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireSharedProject>true</IsAspireSharedProject>
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.0.0-preview.9.24507.7" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.0.0-rc.1.24511.1" />

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="8.7.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="8.2.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
</ItemGroup>

</Project>
Loading

0 comments on commit b90fed5

Please sign in to comment.