-
Notifications
You must be signed in to change notification settings - Fork 287
/
InMemoryTransmitter.cs
196 lines (174 loc) · 6.91 KB
/
InMemoryTransmitter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// <copyright file="InMemoryTransmitter.cs" company="Microsoft">
// Copyright © Microsoft. All Rights Reserved.
// </copyright>
namespace Microsoft.ApplicationInsights.Channel
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing;
/// <summary>
/// A transmitter that will immediately send telemetry over HTTP.
/// Telemetry items are being sent when Flush is called, or when the buffer is full (An OnFull "event" is raised) or every 30 seconds.
/// </summary>
internal class InMemoryTransmitter : IDisposable
{
private readonly TelemetryBuffer buffer;
/// <summary>
/// A lock object to serialize the sending calls from Flush, OnFull event and the Runner.
/// </summary>
private object sendingLockObj = new object();
private AutoResetEvent startRunnerEvent;
private bool enabled = true;
/// <summary>
/// The number of times this object was disposed.
/// </summary>
private int disposeCount = 0;
private TimeSpan sendingInterval = TimeSpan.FromSeconds(30);
private Uri endpointAddress = new Uri(Constants.TelemetryServiceEndpoint);
internal InMemoryTransmitter(TelemetryBuffer buffer)
{
this.buffer = buffer;
this.buffer.OnFull = this.OnBufferFull;
// Starting the Runner
Task.Factory.StartNew(this.Runner, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(
task =>
{
string msg = string.Format(CultureInfo.InvariantCulture, "InMemoryTransmitter: Unhandled exception in Runner: {0}", task.Exception);
CoreEventSource.Log.LogVerbose(msg);
},
TaskContinuationOptions.OnlyOnFaulted);
}
internal Uri EndpointAddress
{
get { return this.endpointAddress; }
set { Property.Set(ref this.endpointAddress, value); }
}
internal TimeSpan SendingInterval
{
get { return this.sendingInterval; }
set { this.sendingInterval = value; }
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Flushes the in-memory buffer and sends it.
/// </summary>
internal void Flush(TimeSpan timeout)
{
SdkInternalOperationsMonitor.Enter();
try
{
this.DequeueAndSend(timeout);
}
finally
{
SdkInternalOperationsMonitor.Exit();
}
}
/// <summary>
/// Flushes the in-memory buffer and sends the telemetry items in <see cref="sendingInterval"/> intervals or when
/// <see cref="startRunnerEvent" /> is set.
/// </summary>
private void Runner()
{
SdkInternalOperationsMonitor.Enter();
try
{
using (this.startRunnerEvent = new AutoResetEvent(false))
{
while (this.enabled)
{
// Pulling all items from the buffer and sending as one transmission.
this.DequeueAndSend(timeout: default(TimeSpan)); // when default(TimeSpan) is provided, value is ignored and default timeout of 100 sec is used
// Waiting for the flush delay to elapse
this.startRunnerEvent.WaitOne(this.sendingInterval);
}
}
}
finally
{
SdkInternalOperationsMonitor.Exit();
}
}
/// <summary>
/// Happens when the in-memory buffer is full. Flushes the in-memory buffer and sends the telemetry items.
/// </summary>
private void OnBufferFull()
{
this.startRunnerEvent.Set();
CoreEventSource.Log.LogVerbose("StartRunnerEvent set as Buffer is full.");
}
/// <summary>
/// Flushes the in-memory buffer and send it.
/// </summary>
private void DequeueAndSend(TimeSpan timeout)
{
lock (this.sendingLockObj)
{
IEnumerable<ITelemetry> telemetryItems = this.buffer.Dequeue();
try
{
// send request
this.Send(telemetryItems, timeout).Wait();
}
catch (Exception e)
{
CoreEventSource.Log.FailedToSend(e.Message);
}
}
}
/// <summary>
/// Serializes a list of telemetry items and sends them.
/// </summary>
private Task Send(IEnumerable<ITelemetry> telemetryItems, TimeSpan timeout)
{
byte[] data = null;
if (telemetryItems != null)
{
data = JsonSerializer.Serialize(telemetryItems);
}
if (data == null || data.Length == 0)
{
CoreEventSource.Log.LogVerbose("No Telemetry Items passed to Enqueue");
return Task.FromResult<object>(null);
}
var transmission = new Transmission(this.endpointAddress, data, JsonSerializer.ContentType, JsonSerializer.CompressionType, timeout);
return transmission.SendAsync();
}
private void Dispose(bool disposing)
{
if (disposing && Interlocked.Increment(ref this.disposeCount) == 1)
{
// Stops the runner loop.
this.enabled = false;
if (this.startRunnerEvent != null)
{
// Call Set to prevent waiting for the next interval in the runner.
try
{
this.startRunnerEvent.Set();
}
catch (ObjectDisposedException)
{
// We need to try catch the Set call in case the auto-reset event wait interval occurs between setting enabled
// to false and the call to Set then the auto-reset event will have already been disposed by the runner thread.
}
}
this.Flush(default(TimeSpan));
}
}
}
}