Skip to content

Commit b1fecb8

Browse files
jmdjmd
jmd
authored and
jmd
committed
calls should also be tracked.
1 parent 6c76a07 commit b1fecb8

File tree

1 file changed

+66
-1
lines changed

1 file changed

+66
-1
lines changed

src/DotJEM.Json.Index2.Management/Writer/IJsonIndexWriter.cs

+66-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,6 @@ public void Delete(JObject entity)
7979
public void Commit()
8080
{
8181
throttledCommit.Invoke();
82-
//Writer.Commit();
8382
DebugInfo($"Writer.Commit()");
8483
}
8584

@@ -108,6 +107,7 @@ public class ThrottledCommit
108107
private long lastInvocation = 0;
109108
private long lastRequest = 0;
110109
private long writes = 0;
110+
private long calls = 0;
111111

112112
public ThrottledCommit(JsonIndexWriter target)
113113
{
@@ -137,6 +137,9 @@ private void Commit()
137137
if(Interlocked.Exchange(ref writes, 0) < 1)
138138
return;
139139

140+
if (Interlocked.Exchange(ref calls, 0) < 1)
141+
return;
142+
140143
try
141144
{
142145
target.Writer.Commit();
@@ -150,6 +153,7 @@ private void Commit()
150153

151154
public void Invoke()
152155
{
156+
Interlocked.Increment(ref calls);
153157
lastRequest = Stopwatch.GetTimestamp();
154158
}
155159

@@ -158,4 +162,65 @@ public void Increment()
158162
Interlocked.Increment(ref writes);
159163
}
160164
}
165+
}
166+
public class ThrottledAction
167+
{
168+
private readonly Action target;
169+
private readonly Action<Exception> onException;
170+
private readonly WaitHandle handle = new AutoResetEvent(false);
171+
private readonly long upperBound = Stopwatch.Frequency * 10;
172+
private readonly long lowerBound = Stopwatch.Frequency / 5;
173+
174+
private long lastInvocation = 0;
175+
private long lastRequest = 0;
176+
private long writes = 0;
177+
178+
public ThrottledAction(Action target, Action<Exception> onException)
179+
{
180+
this.target = target;
181+
this.onException = onException;
182+
ThreadPool.RegisterWaitForSingleObject(handle, (_, _) => Tick(), null, 200, false);
183+
}
184+
185+
private void Tick()
186+
{
187+
long time = Stopwatch.GetTimestamp();
188+
if (time - lastInvocation > upperBound)
189+
{
190+
Commit();
191+
lastInvocation = time;
192+
return;
193+
}
194+
195+
if (time - lastRequest > lowerBound)
196+
{
197+
Commit();
198+
lastInvocation = time;
199+
}
200+
}
201+
202+
private void Commit()
203+
{
204+
if (Interlocked.Exchange(ref writes, 0) < 1)
205+
return;
206+
207+
try
208+
{
209+
target();
210+
}
211+
catch (Exception e)
212+
{
213+
onException(e);
214+
}
215+
}
216+
217+
public void Invoke()
218+
{
219+
lastRequest = Stopwatch.GetTimestamp();
220+
}
221+
222+
public void Increment()
223+
{
224+
Interlocked.Increment(ref writes);
225+
}
161226
}

0 commit comments

Comments
 (0)