Azure / Azure/azure-functions-host
Analyzer: Suggested DocumentDB Use Pattern
- Dominant language
- C#
- Stars
- 2k
- Forks
- 482
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 38
Description
**Conditions to Trigger Analyzer**
Within a `[Function]`-decorated method, where a new DocumentClient is instantiated..
```csharp
public static class CosmosDBWrong
{
[FunctionName("CosmosDBWrong")]
public static async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string endpointUri = "testCosmosDB";
string primaryKey =
var docDBClient = new DocumentClient(new Uri(endpointUri), primaryKey, new ConnectionPolicy()
{
MaxConnectionLimit = 100,
ConnectionMode = ConnectionMode.Gateway,
ConnectionProtocol = Protocol.Tcp,
RetryOptions = new RetryOptions() { MaxRetryAttemptsOnThrottledRequests = 3, MaxRetryWaitTimeInSeconds = 60 }
});
string responseMessage = "Hello from CosmosDB";
return new OkObjectResult(responseMessage);
}
}
```
**Diagnostic Level**
Warning
**How to Fix Violations**
1. Lazy static instantiation outside of [Function] method:
```csharp
using Microsoft.Azure.Documents.Client;
private static Lazy lazyClient = new Lazy(InitializeDocumentClient);
private static DocumentClient documentClient => lazyClient.Value;
private static DocumentClient InitializeDocumentClient()
{
// Perform any initialization here
var uri = new Uri("example");
var authKey = "authKey";
return new DocumentClient(uri, authKey);
}
public static async Task Run(string input)
{
Uri collectionUri = UriFactory.CreateDocumentCollectionUri("database", "collection");
object document = new { Data = "example" };
await documentClient.UpsertDocumentAsync(collectionUri, document);
// Rest of function
}
```
2. Inject DocumentClient using DI, ex. https://github.com/jeffhollan/functions-csharp-cosmosdb-di
**Whether to Supply Codefix**
Yes for 1, if possible for 2.
**Associated Documentation**
https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections
**When to Suppress Analyzer Rule**
This rule should not be suppressed.
Contributor guide
Research direction
No source files or tests are named. Start by locating the analyzer rules for [Function]-decorated methods and DocumentClient construction, then review the linked Azure Functions connection-management documentation; done means a warning is reported and the requested lazy-static or DI guidance is represented in the analyzer/codefix behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- azure, csharp
- Domain
- cloud, tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100