using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace HRM.UI.Realtime.Jobs { public enum JobAccess { Ok = 1, NotFound = 2, Forbidden = 3 } /// /// Every job of this process, in memory. A restart forgets them (the work itself is cut off too), which is the same /// as a long synchronous request that dies with the process. For more than one server this would move to the database. /// internal sealed class JobStore { private readonly ConcurrentDictionary _jobs = new ConcurrentDictionary(); private readonly Dictionary _activeByKey = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly object _keyLock = new object(); /// Adds a new job, unless one with the same key is still queued or running - then that one comes back. public JobState Register(JobRequest request, out bool alreadyRunning) { lock (_keyLock) { if (!string.IsNullOrEmpty(request.Key) && _activeByKey.TryGetValue(request.Key, out string activeRunId) && _jobs.TryGetValue(activeRunId, out JobState active)) { lock (active.Sync) { if (!active.IsFinished) { alreadyRunning = true; return active; } } } JobState state = new JobState(Guid.NewGuid().ToString("N"), request); _jobs[state.RunId] = state; if (!string.IsNullOrEmpty(request.Key)) _activeByKey[request.Key] = state.RunId; alreadyRunning = false; return state; } } public JobState Get(string runId) { if (string.IsNullOrEmpty(runId)) return null; return _jobs.TryGetValue(runId, out JobState state) ? state : null; } /// The job of this key that is queued or running now, or null. public JobState GetActive(string key) { if (string.IsNullOrEmpty(key)) return null; lock (_keyLock) { if (!_activeByKey.TryGetValue(key, out string runId)) return null; JobState state = Get(runId); if (state == null) return null; lock (state.Sync) { return state.IsFinished ? null : state; } } } public void Finished(JobState state) { lock (_keyLock) { if (!string.IsNullOrEmpty(state.Request.Key) && _activeByKey.TryGetValue(state.Request.Key, out string runId) && runId == state.RunId) { _activeByKey.Remove(state.Request.Key); } } } /// Drops finished jobs older than the retention, so memory does not grow for ever. public void Purge(TimeSpan retention) { DateTime limit = DateTime.Now - retention; foreach (JobState state in _jobs.Values.ToList()) { bool expired; lock (state.Sync) { expired = state.IsFinished && state.FinishedAt.HasValue && state.FinishedAt.Value < limit; } if (expired) _jobs.TryRemove(state.RunId, out _); } } /// The owner may always watch; others only when the job is shared with their payroll type. public static bool CanView(JobState state, int userId, int? payrollTypeId) { JobRequest request = state.Request; if (request.OwnerUserId == userId) return true; return request.Audience == JobAudience.PayrollType && request.PayrollTypeId.HasValue && payrollTypeId.HasValue && request.PayrollTypeId.Value == payrollTypeId.Value; } } }