diff options
author | Nat Goodspeed <nat@lindenlab.com> | 2024-08-20 21:22:46 -0400 |
---|---|---|
committer | Nat Goodspeed <nat@lindenlab.com> | 2024-08-20 21:22:46 -0400 |
commit | d37aa5c1823fcb202e87b1457842e49655c72b95 (patch) | |
tree | 25e32e9343c361daf3cea5c57cab58dc7100d4e7 /indra/newview/scripts/lua | |
parent | 376c890c095fbc59b83402255cc1036c411150b9 (diff) |
Defend timers.Timer(iterate=True) against long callbacks.
Specifically, defend against a callback that runs so long it suspends at a
point after the next timer tick.
Diffstat (limited to 'indra/newview/scripts/lua')
-rw-r--r-- | indra/newview/scripts/lua/require/timers.lua | 34 |
1 files changed, 26 insertions, 8 deletions
diff --git a/indra/newview/scripts/lua/require/timers.lua b/indra/newview/scripts/lua/require/timers.lua index e4938078dc..ab1615ffbf 100644 --- a/indra/newview/scripts/lua/require/timers.lua +++ b/indra/newview/scripts/lua/require/timers.lua @@ -34,35 +34,53 @@ function timers.Timer:new(delay, callback, iterate) callback = callback or function() obj:tick() end - local first = true + local calls = 0 if iterate then + -- With iterative timers, beware of running a timer callback which + -- performs async actions lasting longer than the timer interval. The + -- lengthy callback suspends, allowing leap to retrieve the next + -- event, which is a timer tick. leap calls a new instance of the + -- callback, even though the previous callback call is still + -- suspended... etc. 'in_callback' defends against that recursive + -- case. Rather than re-enter the suspended callback, drop the + -- too-soon timer event. (We could count the too-soon timer events and + -- iterate calling the callback, but it's a bathtub problem: the + -- callback could end up getting farther and farther behind.) + local in_callback = false obj.id = leap.eventstream( 'Timers', {op='scheduleEvery', every=delay}, function (event) local reqid = event.reqid - if first then - first = false + calls += 1 + if calls == 1 then dbg('timer(%s) first callback', reqid) -- discard the first (immediate) response: don't call callback return nil else - dbg('timer(%s) nth callback', reqid) - return callback(event) + if in_callback then + dbg('dropping timer(%s) callback %d', reqid, calls) + else + dbg('timer(%s) callback %d', reqid, calls) + in_callback = true + local ret = callback(event) + in_callback = false + return ret + end end end ).reqid - else + else -- (not iterate) obj.id = leap.eventstream( 'Timers', {op='scheduleAfter', after=delay}, function (event) + calls += 1 -- Arrange to return nil the first time, true the second. This -- callback is called immediately with the response to -- 'scheduleAfter', and if we immediately returned true, we'd -- be done, and the subsequent timer event would be discarded. - if first then - first = false + if calls == 1 then -- Caller doesn't expect an immediate callback. return nil else |