aboutsummaryrefslogtreecommitdiff
path: root/lib/VNLib.Plugins.Extensions.Loading/src/Events/EventManagment.cs
blob: 57e4a9c7b12000f868abe152dc9c62d17e736aff (plain)
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
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Extensions.Loading
* File: EventManagment.cs 
*
* EventManagment.cs is part of VNLib.Plugins.Extensions.Loading which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Extensions.Loading is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Extensions.Loading is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.Threading;
using System.Threading.Tasks;

using VNLib.Utils.Logging;

namespace VNLib.Plugins.Extensions.Loading.Events
{

    /// <summary>
    /// A deletage to form a method signature for shedulable interval callbacks
    /// </summary>
    /// <param name="log">The plugin's default log provider</param>
    /// <param name="pluginExitToken">The plugin's exit token</param>
    /// <returns>A task the represents the asynchronous work</returns>
    public delegate Task AsyncSchedulableCallback(ILogProvider log, CancellationToken pluginExitToken);

    /// <summary>
    /// Provides event schedueling extensions for plugins
    /// </summary>
    public static class EventManagment
    {
        /// <summary>
        /// Schedules an asynchronous event interval for the current plugin, that is active until canceled or until the plugin unloads
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="asyncCallback">An asyncrhonous callback method.</param>
        /// <param name="interval">The event interval</param>
        /// <param name="immediate">A value that indicates if the callback should be run as soon as possible</param>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <remarks>If exceptions are raised during callback execution, they are written to the plugin's default log provider</remarks>
        public static void ScheduleInterval(this PluginBase plugin, AsyncSchedulableCallback asyncCallback, TimeSpan interval, bool immediate = false)
        {
            plugin.ThrowIfUnloaded();
            
            plugin.Log.Verbose("Interval for {t} scheduled", interval);
            
            //Run interval on plugins bg scheduler
            _ = plugin.ObserveWork(() => RunIntervalOnPluginScheduler(plugin, asyncCallback, interval, immediate));
        }

        private static async Task RunIntervalOnPluginScheduler(PluginBase plugin, AsyncSchedulableCallback callback, TimeSpan interval, bool immediate)
        {

            static async Task RunCallbackAsync(PluginBase plugin, AsyncSchedulableCallback callback)
            {
                try
                {
                    //invoke interval callback
                    await callback(plugin.Log, plugin.UnloadToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    //unloaded
                    plugin.Log.Verbose("Interval callback canceled due to plugin unload or other event cancellation");
                }
                catch (Exception ex)
                {
                    plugin.Log.Error(ex, "Unhandled exception raised during timer callback");
                }
            }

            //Run callback immediatly if requested
            if (immediate)
            {
                await RunCallbackAsync(plugin, callback);
            }

            //Timer loop
            while (true)
            {
                try
                {
                    //await delay and wait for plugin cancellation
                    await Task.Delay(interval, plugin.UnloadToken);
                }
                catch (TaskCanceledException)
                {
                    //Unload token canceled, exit loop
                    break;
                }

                await RunCallbackAsync(plugin, callback);
            }
        }

        /// <summary>
        /// Registers an <see cref="IIntervalScheduleable"/> type's event handler for 
        /// raising timed interval events
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="scheduleable">The instance to schedule for timeouts</param>
        /// <param name="interval">The timeout interval</param>
        /// <param name="immediate">A value that indicates if the callback should be run as soon as possible</param>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <remarks>If exceptions are raised during callback execution, they are written to the plugin's default log provider</remarks>
        public static void ScheduleInterval(this PluginBase plugin, IIntervalScheduleable scheduleable, TimeSpan interval, bool immediate = false) => 
            ScheduleInterval(plugin, scheduleable.OnIntervalAsync, interval, immediate);
    }
}