面对使用可持续的 Azure 函数将文档写入 Cosmos DB 时出现的问题。

huangapple go评论82阅读模式
英文:

Facing Issue writing document to Cosmos DB using Durable Azure Function

问题

I am having a chaining durable Azure function in which I want to write documents to Cosmos DB. I am running the Isolated mode. My function looks like that:

[Function(nameof(ScanLinksAndInsertIntoLinksContainer))]
[CosmosDBOutput(databaseName: "dpubot", containerName: "test", Connection= "CosmosConnection"
    , CreateIfNotExists = true, PartitionKey = "id")]
public static MultiResponse ScanLinksAndInsertIntoLinksContainer
    ([ActivityTrigger] string name, FunctionContext executionContext)
{
    var message = "Life is short";
    return new MultiResponse()
    {
        Document = new MyDocument
        {
            id = System.Guid.NewGuid().ToString(),
            message = message
        },
    };
}

I am getting an error:

Executed 'Functions.ScanLinksAndInsertIntoLinksContainer' (Failed, Id=635107bb-afc7-46e6-ac6b-5e4454f07254, Duration=2040ms)
[2023-07-17T08:26:59.443Z] System.Private.CoreLib: Exception while executing function: Functions.ScanLinksAndInsertIntoLinksContainer. Microsoft.Azure.Cosmos.Client: Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: 94096d64-1801-4193-a0a2-2a7723eac59f; Reason: (Message: {"Errors":["One of the specified inputs is invalid"]}

My Host.json looks like:

"logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    },
    "extensions": {
      "cosmosDB": {
        "connectionMode": "Gateway",
        "userAgentSuffix": "MyDesiredUserAgentStamp"
      }
    }
}

My local setting json file looks like:

"Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "CosmosConnection": ""
}
英文:

I am having a chaining durable Azure function in which I want to write documents to Cosmos DB. I am running the Isolated mode. My function looks like that:

[Function(nameof(ScanLinksAndInsertIntoLinksContainer))]
        [CosmosDBOutput(databaseName: "dpubot", containerName: "test", Connection= "CosmosConnection"
            , CreateIfNotExists = true, PartitionKey = "id")]
        public static MultiResponse ScanLinksAndInsertIntoLinksContainer
            ([ActivityTrigger] string name, FunctionContext executionContext)
        {
        
            var message = "Life is short";
            return new MultiResponse()
            {
                Document = new MyDocument
                {
                    id = System.Guid.NewGuid().ToString(),
                    message = message
                },
                
            };

        }

I am getting an error:

Executed 'Functions.ScanLinksAndInsertIntoLinksContainer' (Failed, Id=635107bb-afc7-46e6-ac6b-5e4454f07254, Duration=2040ms)
[2023-07-17T08:26:59.443Z] System.Private.CoreLib: Exception while executing function: Functions.ScanLinksAndInsertIntoLinksContainer. Microsoft.Azure.Cosmos.Client: Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: 94096d64-1801-4193-a0a2-2a7723eac59f; Reason: (Message: {"Errors":["One of the specified inputs is invalid"]}

My Host.json looks like

    "logging": {
        "applicationInsights": {
          "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": "Request"
          }
        },
        "extensions": {
          "cosmosDB": {
            "connectionMode": "Gateway",
            "userAgentSuffix": "MyDesiredUserAgentStamp"
          }
        }

My local setting json file looks like

    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "CosmosConnection":
    
    }

答案1

得分: 1

我已经在我的环境中重现了这个问题,并且它按预期工作。

最初,我使用VS Code和.NET 7隔离进程创建了一个默认的隔离Durable函数,然后我在其中加入了CosmosDBOutput

以下是您的代码部分:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.DurableTask;
using Microsoft.DurableTask.Client;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Company.Function
{
    public static class DurableFunctionsOrchestrationCSharp1
    {
        [Function(nameof(DurableFunctionsOrchestrationCSharp1))]
        public static async Task<List<string>> RunOrchestrator(
            [OrchestrationTrigger] TaskOrchestrationContext context)
        {
            ILogger logger = context.CreateReplaySafeLogger(nameof(DurableFunctionsOrchestrationCSharp1));

            logger.LogInformation("Saying hello.");

            var outputs = new List<string>();

            outputs.Add(await context.CallActivityAsync<string>(nameof(SayHello), "Tokyo"));
            outputs.Add(await context.CallActivityAsync<string>(nameof(SayHello), "Seattle"));
            outputs.Add(await context.CallActivityAsync<string>(nameof(SayHello), "London"));
            return outputs;
        }

        [Function(nameof(SayHello))]
        [CosmosDBOutput("outDatabase", "mycollection", Connection = "CosmosDBConnection", CreateIfNotExists = true, PartitionKey = "/id")]
        public static MyDocument SayHello([ActivityTrigger] string name, FunctionContext executionContext)
        {
            ILogger logger = executionContext.GetLogger("SayHello");
            logger.LogInformation("Saying hello to {name}.", name);
            var message = "Life is full of Joy";
            var document = new MyDocument
            {
                id = Guid.NewGuid().ToString(),
                message = message
            };
            return document;
        }

        public class MyDocument
        {
            public string? id { get; set; }
            public string? message { get; set; }
        }

        [Function("DurableFunctionsOrchestrationCSharp1_HttpStart")]
        public static async Task<HttpResponseData> HttpStart(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
            [DurableClient] DurableTaskClient client,
            FunctionContext executionContext)
        {
            ILogger logger = executionContext.GetLogger("DurableFunctionsOrchestrationCSharp1_HttpStart");

            // Function input comes from the request content.

            string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(
                nameof(DurableFunctionsOrchestrationCSharp1));
            logger.LogInformation("Started orchestration with ID = '{instanceId}'.", instanceId);
            return client.CreateCheckStatusResponse(req, instanceId);
        }
    }
}

以下是您的local.settings.json文件:

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "CosmosDBConnection": "**********************"
    }
}

以下是您的host.json文件:

{
    "version": "2.0",
    "logging": {
        "applicationInsights": {
            "samplingSettings": {
                "isEnabled": true,
                "excludedTypes": "Request"
            }
        }
    }
}

您的.csproj文件包含以下包:

<ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.10.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.CosmosDB" Version="4.3.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.DurableTask" Version="1.0.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.7.0" />
</ItemGroup>

请根据MS Docs中隔离进程的示例更改您的数据并更改CosmosDBOutput属性的格式。

英文:

I have reproduced the issue at my environment and it worked as expected

Initially I have created a default isolated Durable function using vs code and .NET 7 isolated process, then I incorporated CosmosDBOutput in it.

Code:

using  Microsoft.Azure.Functions.Worker;
using  Microsoft.Azure.Functions.Worker.Http;
using  Microsoft.DurableTask;
using  Microsoft.DurableTask.Client;
using  Microsoft.Extensions.Logging;
namespace  Company.Function
{
public  static  class  DurableFunctionsOrchestrationCSharp1
{
[Function(nameof(DurableFunctionsOrchestrationCSharp1))]
public  static  async  Task&lt;List&lt;string&gt;&gt; RunOrchestrator(
[OrchestrationTrigger] TaskOrchestrationContext  context)
{
ILogger  logger  =  context.CreateReplaySafeLogger(nameof(DurableFunctionsOrchestrationCSharp1));
logger.LogInformation(&quot;Saying hello.&quot;);
var  outputs  =  new  List&lt;string&gt;();
outputs.Add(await  context.CallActivityAsync&lt;string&gt;(nameof(SayHello), &quot;Tokyo&quot;));
outputs.Add(await  context.CallActivityAsync&lt;string&gt;(nameof(SayHello), &quot;Seattle&quot;));
outputs.Add(await  context.CallActivityAsync&lt;string&gt;(nameof(SayHello), &quot;London&quot;));
return  outputs;
} 
[Function(nameof(SayHello))]
[CosmosDBOutput(&quot;outDatabase&quot;, &quot;mycollection&quot;, Connection  =  &quot;CosmosDBConnection&quot;, CreateIfNotExists  =  true, PartitionKey  =  &quot;/id&quot;)]
public  static  MyDocument  SayHello([ActivityTrigger] string  name, FunctionContext  executionContext)
{
ILogger  logger  =  executionContext.GetLogger(&quot;SayHello&quot;);
logger.LogInformation(&quot;Saying hello to {name}.&quot;, name);
var  message  =  &quot;Life is full of Joy&quot;;
var  document  =  new  MyDocument
{
id  =  Guid.NewGuid().ToString(),
message  =  message
};
return  document;
}
public  class  MyDocument
{
public  string?  id { get; set; }
public  string?  message { get; set; }
}
[Function(&quot;DurableFunctionsOrchestrationCSharp1_HttpStart&quot;)]
public  static  async  Task&lt;HttpResponseData&gt; HttpStart(
[HttpTrigger(AuthorizationLevel.Anonymous, &quot;get&quot;, &quot;post&quot;)] HttpRequestData  req,
[DurableClient] DurableTaskClient  client,
FunctionContext  executionContext)
{
ILogger  logger  =  executionContext.GetLogger(&quot;DurableFunctionsOrchestrationCSharp1_HttpStart&quot;);
// Function input comes from the request content.
string  instanceId  =  await  client.ScheduleNewOrchestrationInstanceAsync(
nameof(DurableFunctionsOrchestrationCSharp1));
logger.LogInformation(&quot;Started orchestration with ID = &#39;{instanceId}&#39;.&quot;, instanceId);
return  client.CreateCheckStatusResponse(req, instanceId);
}
}
}

local.settings.json

{
&quot;IsEncrypted&quot;: false,
&quot;Values&quot;: {
&quot;AzureWebJobsStorage&quot;: &quot;UseDevelopmentStorage=true&quot;,
&quot;FUNCTIONS_WORKER_RUNTIME&quot;: &quot;dotnet-isolated&quot;,
&quot;CosmosDBConnection&quot;: &quot;**********************&quot;
}
}

host.json

{
&quot;version&quot;: &quot;2.0&quot;,
&quot;logging&quot;: {
&quot;applicationInsights&quot;: {
&quot;samplingSettings&quot;: {
&quot;isEnabled&quot;: true,
&quot;excludedTypes&quot;: &quot;Request&quot;
}
}
}
}

My .csproj file contains below packages

&lt;ItemGroup&gt;
&lt;PackageReference  Include=&quot;Microsoft.Azure.Functions.Worker&quot;  Version=&quot;1.10.0&quot;  /&gt;
&lt;PackageReference  Include=&quot;Microsoft.Azure.Functions.Worker.Extensions.CosmosDB&quot;  Version=&quot;4.3.0&quot;  /&gt;
&lt;PackageReference  Include=&quot;Microsoft.Azure.Functions.Worker.Extensions.DurableTask&quot;  Version=&quot;1.0.0&quot;  /&gt;
&lt;PackageReference  Include=&quot;Microsoft.Azure.Functions.Worker.Extensions.Http&quot;  Version=&quot;3.0.13&quot;  /&gt;
&lt;PackageReference  Include=&quot;Microsoft.Azure.Functions.Worker.Sdk&quot;  Version=&quot;1.7.0&quot;  /&gt;
&lt;/ItemGroup&gt;

Output:

面对使用可持续的 Azure 函数将文档写入 Cosmos DB 时出现的问题。

面对使用可持续的 Azure 函数将文档写入 Cosmos DB 时出现的问题。

Cosmos DB

面对使用可持续的 Azure 函数将文档写入 Cosmos DB 时出现的问题。

Please make some modification in your data and change the format of CosmosDBOutput attribute as shown in ms docs for isolated process.

huangapple
  • 本文由 发表于 2023年7月17日 16:42:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定