microsoft/teams.net

Public

mirrored from https://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
99620f7f6ecccb78c4ebfb54686bb2a4e56dcea8

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

core/src/Microsoft.Teams.Bot.Core/BotApplication.cs

163lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using System.Diagnostics;
5using Microsoft.AspNetCore.Http;
6using Microsoft.Extensions.Logging;
7using Microsoft.Extensions.Logging.Abstractions;
8using Microsoft.Teams.Bot.Core.Hosting;
9using Microsoft.Teams.Bot.Core.Schema;
10
11namespace Microsoft.Teams.Bot.Core;
12
13/// <summary>
14/// Represents a bot application.
15/// </summary>
16public class BotApplication
17{
18 private readonly ILogger<BotApplication> _logger;
19 private readonly ConversationClient? _conversationClient;
20 private readonly UserTokenClient? _userTokenClient;
21 private readonly TimeSpan _processActivityTimeout = TimeSpan.FromMinutes(5);
22 internal TurnMiddleware MiddleWare { get; }
23
24 /// <summary>
25 /// Creates a default instance, primarily for testing purposes. The ConversationClient and UserTokenClient properties will not be initialized
26 /// </summary>
27 protected BotApplication()
28 {
29 _logger = NullLogger<BotApplication>.Instance;
30 MiddleWare = new TurnMiddleware();
31 }
32
33 /// <summary>
34 /// Initializes a new instance of the BotApplication class with the specified conversation client, app ID,
35 /// and logger.
36 /// Initializes a new instance of the BotApplication class with the specified conversation client, app ID,
37 /// and logger.
38 /// </summary>
39 /// <param name="conversationClient">The client used to manage and interact with conversations for the bot.</param>
40 /// <param name="userTokenClient">The client used to manage user tokens for authentication.</param>
41 /// <param name="logger">The logger used to record operational and diagnostic information for the bot application.</param>
42 /// <param name="options">Options containing the application (client) ID, used for logging and diagnostics. Defaults to an empty instance if not provided.</param>
43 public BotApplication(ConversationClient conversationClient, UserTokenClient userTokenClient, ILogger<BotApplication> logger, BotApplicationOptions? options = null)
44 {
45 options ??= new();
46 _logger = logger;
47 MiddleWare = new TurnMiddleware();
48 MiddleWare.SetLogger(logger);
49 _conversationClient = conversationClient;
50 _userTokenClient = userTokenClient;
51 _processActivityTimeout = options.ProcessActivityTimeout;
52 logger.LogInformationGuarded("Started {ThisType} listener for AppID:{AppId} with SDK version {SdkVersion}", GetType().Name, options.AppId, Version);
53 }
54
55
56 /// <summary>
57 /// Gets the client used to manage and interact with conversations.
58 /// </summary>
59 /// <remarks>Accessing this property before the client is initialized will result in an exception. Ensure
60 /// that the client is properly configured before use.</remarks>
61 public ConversationClient ConversationClient => _conversationClient ?? throw new InvalidOperationException("ConversationClient not initialized");
62
63 /// <summary>
64 /// Gets the client used to manage user tokens for authentication.
65 /// </summary>
66 /// <remarks>Accessing this property before the client is initialized will result in an exception. Ensure
67 /// that the client is properly configured before use.</remarks>
68 public UserTokenClient UserTokenClient => _userTokenClient ?? throw new InvalidOperationException("UserTokenClient not registered");
69
70 /// <summary>
71 /// Gets or sets the delegate that is invoked to handle an incoming activity asynchronously.
72 /// </summary>
73 /// <remarks>Assign a delegate to process activities as they are received. The delegate should accept an
74 /// <see cref="CoreActivity"/> and a <see cref="CancellationToken"/>, and return a <see cref="Task"/> representing the
75 /// asynchronous operation. If <see langword="null"/>, incoming activities will not be handled.</remarks>
76 public virtual Func<CoreActivity, CancellationToken, Task>? OnActivity { get; set; }
77
78 /// <summary>
79 /// Processes an incoming HTTP request containing a bot activity.
80 /// </summary>
81 /// <param name="httpContext"></param>
82 /// <param name="cancellationToken"></param>
83 /// <returns></returns>
84 /// <exception cref="InvalidOperationException"></exception>
85 /// <exception cref="BotHandlerException"></exception>
86 public virtual async Task ProcessAsync(HttpContext httpContext, CancellationToken cancellationToken = default)
87 {
88 ArgumentNullException.ThrowIfNull(httpContext);
89 ArgumentNullException.ThrowIfNull(_conversationClient);
90
91 _logger.LogDebug("Start processing HTTP request for activity");
92
93 CoreActivity activity = await CoreActivity.FromJsonStreamAsync(httpContext.Request.Body, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Invalid Activity");
94
95 _logger.LogInformationGuarded("Activity received: Type={Type} Id={Id} ServiceUrl={ServiceUrl} MSCV={MSCV}",
96 activity.Type,
97 activity.Id,
98 activity.ServiceUrl,
99 httpContext.Request.GetCorrelationVector());
100
101 _logger.LogTraceGuarded("Received activity: {Activity}", activity.ToJson());
102
103 // TODO: Replace with structured scope data, ensure it works with OpenTelemetry and other logging providers
104 using (_logger.BeginScope("ActivityType={ActivityType} ActivityId={ActivityId} ServiceUrl={ServiceUrl} MSCV={MSCV}",
105 activity.Type, activity.Id, activity.ServiceUrl, httpContext.Request.GetCorrelationVector()))
106 {
107 // Use a dedicated timeout instead of the HTTP request's cancellation token.
108 // The HTTP token fires when the client disconnects, which is expected for
109 // streaming handlers that outlive the original request.
110 using var cts = new CancellationTokenSource(_processActivityTimeout);
111 try
112 {
113 CancellationToken token = Debugger.IsAttached ? CancellationToken.None : cts.Token;
114 await MiddleWare.RunPipelineAsync(this, activity, this.OnActivity, 0, token).ConfigureAwait(false);
115 }
116 catch (OperationCanceledException) when (cts.IsCancellationRequested)
117 {
118 _logger.LogWarning("Activity processing timed out after {Timeout}: Id={Id}", _processActivityTimeout, activity.Id);
119 }
120 catch (Exception ex)
121 {
122 _logger.LogError(ex, "Error processing activity: Id={Id}", activity.Id);
123 throw new BotHandlerException("Error processing activity", ex, activity);
124 }
125 finally
126 {
127 _logger.LogInformationGuarded("Finished processing activity: Id={Id}", activity.Id);
128 }
129 }
130 }
131
132 /// <summary>
133 /// Adds the specified turn middleware to the middleware pipeline.
134 /// </summary>
135 /// <param name="middleware">The middleware component to add to the pipeline. Cannot be null.</param>
136 /// <returns>An ITurnMiddleWare instance representing the updated middleware pipeline.</returns>
137 public ITurnMiddleware UseMiddleware(ITurnMiddleware middleware)
138 {
139 ArgumentNullException.ThrowIfNull(middleware);
140 MiddleWare.Use(middleware);
141 return MiddleWare;
142 }
143
144 /// <summary>
145 /// Sends the specified activity to the conversation asynchronously.
146 /// </summary>
147 /// <param name="activity">The activity to send to the conversation. Cannot be null.</param>
148 /// <param name="cancellationToken">A cancellation token that can be used to cancel the send operation.</param>
149 /// <returns>A task that represents the asynchronous operation. The task result contains the identifier of the sent activity.</returns>
150 /// <exception cref="Exception">Thrown if the conversation client has not been initialized.</exception>
151 public async Task<SendActivityResponse?> SendActivityAsync(CoreActivity activity, CancellationToken cancellationToken = default)
152 {
153 ArgumentNullException.ThrowIfNull(activity);
154 ArgumentNullException.ThrowIfNull(_conversationClient, "ConversationClient not initialized");
155
156 return await _conversationClient.SendActivityAsync(activity, cancellationToken: cancellationToken).ConfigureAwait(false);
157 }
158
159 /// <summary>
160 /// Gets the version of the SDK.
161 /// </summary>
162 public static string Version => ThisAssembly.NuGetPackageVersion;
163}
164