Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 58 additions & 17 deletions src/Orleans.DurableJobs/DurableJobRunResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,27 @@ public sealed class DurableJobRunResult
public bool IsFailed => Status == DurableJobRunStatus.Failed;

/// <summary>
/// Gets a value indicating whether the job should be polled again after a delay.
/// Gets a value indicating whether the job is still running and should be polled after a delay.
/// </summary>
[MemberNotNullWhen(true, nameof(PollAfterDelay))]
public bool IsPending => Status == DurableJobRunStatus.PollAfter;
public bool IsRunning => Status == DurableJobRunStatus.Running;

Comment thread
ReubenBond marked this conversation as resolved.
Resolved
private DurableJobRunResult(DurableJobRunStatus status, TimeSpan? pollAfter, Exception? exception)
/// <summary>
/// Gets a value indicating whether the successfully handled job requested durable rescheduling.
/// </summary>
[MemberNotNullWhen(true, nameof(RescheduleTime))]
public bool IsRescheduleRequested => Status == DurableJobRunStatus.RescheduleRequested && RescheduleTime is not null;

private DurableJobRunResult(
DurableJobRunStatus status,
TimeSpan? pollAfterDelay,
Exception? exception,
DateTimeOffset? rescheduleTime)
{
Status = status;
PollAfterDelay = pollAfter;
PollAfterDelay = pollAfterDelay;
Exception = exception;
RescheduleTime = rescheduleTime;
}

/// <summary>
Expand All @@ -35,7 +46,7 @@ private DurableJobRunResult(DurableJobRunStatus status, TimeSpan? pollAfter, Exc
public DurableJobRunStatus Status { get; }

/// <summary>
/// Gets the delay before the next status check when <see cref="Status"/> is <see cref="DurableJobRunStatus.PollAfter"/>.
/// Gets the delay before the executor polls the ongoing run when <see cref="Status"/> is <see cref="DurableJobRunStatus.Running"/>.
/// </summary>
[Id(1)]
public TimeSpan? PollAfterDelay { get; }
Expand All @@ -46,28 +57,49 @@ private DurableJobRunResult(DurableJobRunStatus status, TimeSpan? pollAfter, Exc
[Id(2)]
public Exception? Exception { get; }

private static readonly DurableJobRunResult CompletedInstance = new(DurableJobRunStatus.Completed, null, null);
/// <summary>
/// Gets the time at which the job should be durably rescheduled after the current execution completes successfully.
/// </summary>
[Id(3)]
public DateTimeOffset? RescheduleTime { get; }

private static readonly DurableJobRunResult CompletedInstance = new(DurableJobRunStatus.Completed, null, null, null);

/// <summary>
/// Gets a result indicating the job completed successfully.
/// </summary>
public static DurableJobRunResult Completed => CompletedInstance;

/// <summary>
/// Creates a result indicating the job should be polled again after the specified delay.
/// Creates a result indicating the job is still running and should be polled after the specified delay.
/// </summary>
/// <param name="delay">The time to wait before checking the job status again.</param>
/// <returns>A poll-after job result.</returns>
/// <param name="delay">The time to wait before polling the run again.</param>
/// <returns>A running job result.</returns>
/// <remarks>
/// The job will remain in an inline polling loop without being re-queued.
/// The polling loop will hold a concurrency slot until the job completes or fails.
/// The executor keeps the current run and its concurrency slot active, then polls the receiver again after the delay.
/// TODO: Add validation for minimum/maximum poll delays to prevent abuse.
/// TODO: Consider concurrency slot management for long-running polls.
/// </remarks>
public static DurableJobRunResult PollAfter(TimeSpan delay)
public static DurableJobRunResult Running(TimeSpan delay)
{
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(delay, TimeSpan.Zero, nameof(delay));
return new(DurableJobRunStatus.PollAfter, delay, null);
return new(DurableJobRunStatus.Running, delay, null, null);
}

/// <summary>
/// Creates a result indicating that the current execution completed successfully and requested durable rescheduling.
/// </summary>
/// <param name="dueTime">The time at which the next execution should become due.</param>
/// <returns>A durable rescheduling result.</returns>
/// <remarks>
/// Rescheduling resets the failure-attempt count, so the next dequeue count is one.
/// During a mixed-version rolling upgrade, callers emit this result after every durable job executor
/// understands <see cref="DurableJobRunStatus.RescheduleRequested"/> (serialized value 3).
/// This rollout order preserves compatibility with executors that understand serialized values 0 through 2.
/// </remarks>
public static DurableJobRunResult RescheduleAt(DateTimeOffset dueTime)
{
return new(DurableJobRunStatus.RescheduleRequested, null, null, dueTime);
}

/// <summary>
Expand All @@ -81,7 +113,7 @@ public static DurableJobRunResult PollAfter(TimeSpan delay)
public static DurableJobRunResult Failed(Exception exception)
{
ArgumentNullException.ThrowIfNull(exception);
return new(DurableJobRunStatus.Failed, null, exception);
return new(DurableJobRunStatus.Failed, null, exception, null);
}
}

Expand All @@ -93,15 +125,24 @@ public enum DurableJobRunStatus
/// <summary>
/// The job completed successfully and should be removed from the queue.
/// </summary>
Completed,
Completed = 0,

/// <summary>
/// The job is still running and should be polled again after the specified delay.
/// </summary>
PollAfter,
Running = 1,

/// <summary>
/// The job failed and should be processed through the retry policy.
/// </summary>
Failed
Failed = 2,

/// <summary>
/// The current execution completed successfully and requested durable rescheduling with its failure-attempt count reset.
/// </summary>
/// <remarks>
/// This value is serialized as 3. During rolling upgrades, emit it after all durable job executors support it.
/// Newer executors treat unknown disposition values as failures and route them through the configured retry policy.
/// </remarks>
RescheduleRequested = 3
}
8 changes: 8 additions & 0 deletions src/Orleans.DurableJobs/DurableJobsInstruments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ internal sealed class DurableJobsInstruments(OrleansInstruments instruments)
private const string StatusCompleted = "completed";
private const string StatusFailed = "failed";
private const string StatusRetried = "retried";
private const string StatusRescheduled = "rescheduled";
private const string StatusCanceled = "canceled";
private const string StatusError = "error";
private const string StatusOk = "ok";
Expand All @@ -34,6 +35,7 @@ internal static DurableJobsInstruments CreateForDirectConstruction()
private readonly Counter<long> JobsCompleted = instruments.Meter.CreateCounter<long>("orleans-durablejobs-jobs-completed");
private readonly Counter<long> JobsFailed = instruments.Meter.CreateCounter<long>("orleans-durablejobs-jobs-failed");
private readonly Counter<long> JobsRetried = instruments.Meter.CreateCounter<long>("orleans-durablejobs-jobs-retried");
private readonly Counter<long> JobsRescheduled = instruments.Meter.CreateCounter<long>("orleans-durablejobs-jobs-rescheduled");
private readonly Counter<long> JobsCanceled = instruments.Meter.CreateCounter<long>("orleans-durablejobs-jobs-canceled");
private readonly Counter<long> ShardsProcessed = instruments.Meter.CreateCounter<long>("orleans-durablejobs-shards-processed");
private readonly Counter<long> ScheduleJobCalls = instruments.Meter.CreateCounter<long>("orleans-durablejobs-schedule-job-calls");
Expand Down Expand Up @@ -86,6 +88,12 @@ internal void OnJobRetried(TimeSpan latency)
Record(JobAttemptDuration, latency, StatusRetried);
}

internal void OnJobRescheduled(TimeSpan latency)
{
JobsRescheduled.Add(1);
Record(JobAttemptDuration, latency, StatusRescheduled);
}

internal void OnJobCanceled()
{
JobsCanceled.Add(1);
Expand Down
4 changes: 2 additions & 2 deletions src/Orleans.DurableJobs/IDurableJobReceiverExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ private ValueTask<DurableJobRunResult> GetJobStatusAsync((string JobId, int Dequ
return LongPollGetJobStatusAsync(key, context, state);
}

return new(DurableJobRunResult.PollAfter(_shared.Options.JobStatusPollInterval));
return new(DurableJobRunResult.Running(_shared.Options.JobStatusPollInterval));
}

RecordCompletedJobAttempt(key, state);
Expand Down Expand Up @@ -137,7 +137,7 @@ async ValueTask<DurableJobRunResult> LongPollGetJobStatusAsync((string JobId, in

if (!state.Task.IsCompleted)
{
return DurableJobRunResult.PollAfter(_shared.Options.JobStatusPollInterval);
return DurableJobRunResult.Running(_shared.Options.JobStatusPollInterval);
}
}

Expand Down
18 changes: 17 additions & 1 deletion src/Orleans.DurableJobs/JobShard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public interface IJobShard : IAsyncDisposable
/// <summary>
/// Base implementation of <see cref="IJobShard"/> that provides common functionality for job shard implementations.
/// </summary>
public abstract class JobShard : IJobShard
public abstract class JobShard : IJobShard, IResettableJobShard
{
private readonly InMemoryJobQueue _jobQueue;

Expand Down Expand Up @@ -194,6 +194,17 @@ public async Task RetryJobLaterAsync(IJobRunContext jobContext, DateTimeOffset n
_jobQueue.RetryJobLater(jobContext, newDueTime);
}

async Task IResettableJobShard.RescheduleJobAsync(
IJobRunContext jobContext,
DateTimeOffset newDueTime,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(jobContext);
var resetContext = new JobRunContext(jobContext.Job, jobContext.RunId, retryCount: 0);
await PersistRetryJobAsync(resetContext, newDueTime, cancellationToken);
_jobQueue.RetryJobLater(jobContext.Job.Id, newDueTime, dequeueCount: 0);
}

/// <summary>
/// Enqueues a job into the in-memory queue with the specified dequeue count.
/// </summary>
Expand Down Expand Up @@ -239,3 +250,8 @@ public virtual ValueTask DisposeAsync()
return default;
}
}

internal interface IResettableJobShard
{
Task RescheduleJobAsync(IJobRunContext jobContext, DateTimeOffset newDueTime, CancellationToken cancellationToken);
}
35 changes: 31 additions & 4 deletions src/Orleans.DurableJobs/JournaledJobShard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Orleans.DurableJobs;
/// <summary>
/// Journaled implementation of <see cref="IJobShard"/> that stores shard state in Orleans journaling storage.
/// </summary>
internal sealed class JournaledJobShard : IJobShard
internal sealed class JournaledJobShard : IJobShard, IResettableJobShard
{
private readonly JournaledJobShardState _state;
private readonly IJournaledStateManager _stateManager;
Expand Down Expand Up @@ -149,7 +149,27 @@ public async Task RetryJobLaterAsync(IJobRunContext jobContext, DateTimeOffset n
ArgumentNullException.ThrowIfNull(jobContext);
ThrowIfDisposed();

var operation = new RetryJobLaterOperation(jobContext, newDueTime, cancellationToken);
var operation = new RetryJobLaterOperation(jobContext, newDueTime, resetDequeueCount: false, cancellationToken);
try
{
EnqueueOperation(operation);
await operation.Task.ConfigureAwait(false);
}
finally
{
operation.Dispose();
}
}

async Task IResettableJobShard.RescheduleJobAsync(
IJobRunContext jobContext,
DateTimeOffset newDueTime,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(jobContext);
ThrowIfDisposed();

var operation = new RetryJobLaterOperation(jobContext, newDueTime, resetDequeueCount: true, cancellationToken);
try
{
EnqueueOperation(operation);
Expand Down Expand Up @@ -668,14 +688,21 @@ protected override bool Apply(JournaledJobShard shard, out bool result)
}
}

private sealed class RetryJobLaterOperation(IJobRunContext jobContext, DateTimeOffset newDueTime, CancellationToken cancellationToken)
private sealed class RetryJobLaterOperation(
IJobRunContext jobContext,
DateTimeOffset newDueTime,
bool resetDequeueCount,
CancellationToken cancellationToken)
: PendingMutationOperation<bool>(cancellationToken)
{
protected override bool NotOwnedResult => true;

protected override bool Apply(JournaledJobShard shard, out bool result)
{
shard._state.RetryJobLater(jobContext, newDueTime);
shard._state.RetryJobLater(
jobContext.Job.Id,
newDueTime,
resetDequeueCount ? 0 : jobContext.DequeueCount);
result = true;
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/Orleans.DurableJobs/ShardExecutor.Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ internal sealed partial class ShardExecutor
)]
private static partial void LogRetryingJob(ILogger logger, string jobId, string jobName, DateTimeOffset retryTime, int dequeueCount);

[LoggerMessage(
Level = LogLevel.Information,
Message = "Rescheduling job {JobId} (Name: '{JobName}') at {RescheduleTime}"
)]
private static partial void LogReschedulingJob(ILogger logger, string jobId, string jobName, DateTimeOffset rescheduleTime);

[LoggerMessage(
Level = LogLevel.Debug,
Message = "Polling job {JobId} (Name: '{JobName}') - will check status again in {PollDelay}"
Expand Down
61 changes: 47 additions & 14 deletions src/Orleans.DurableJobs/ShardExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ private async Task ExecuteJobAsync(
var result = await target.HandleDurableJobAsync(jobContext, cancellationToken);

// Handle the result based on status
while (result.IsPending)
while (result.IsRunning)
{
// Enter polling loop
LogPollingJob(_logger, jobContext.Job.Id, jobContext.Job.Name, result.PollAfterDelay.Value);
Expand All @@ -264,22 +264,49 @@ private async Task ExecuteJobAsync(
result = await target.HandleDurableJobAsync(jobContext, cancellationToken);
}

if (result.Status == DurableJobRunStatus.Completed)
switch (result.Status)
{
await shard.RemoveJobAsync(jobContext.Job.Id, cancellationToken);
LogJobExecutedSuccessfully(_logger, jobContext.Job.Id, jobContext.Job.Name);
_durableJobsInstruments.OnJobCompleted(_timeProvider.GetElapsedTime(attemptStartTimestamp));
activity?.SetTag(ActivityTagKeys.DurableJobStatus, "completed");
activity?.SetStatus(ActivityStatusCode.Ok);
}
else if (result.IsFailed)
{
// Handle failed result through retry policy
LogJobFailedWithResult(_logger, jobContext.Job.Id, jobContext.Job.Name);
failureException = result.Exception;
case DurableJobRunStatus.Completed:
await shard.RemoveJobAsync(jobContext.Job.Id, cancellationToken);
LogJobExecutedSuccessfully(_logger, jobContext.Job.Id, jobContext.Job.Name);
_durableJobsInstruments.OnJobCompleted(_timeProvider.GetElapsedTime(attemptStartTimestamp));
activity?.SetTag(ActivityTagKeys.DurableJobStatus, "completed");
activity?.SetStatus(ActivityStatusCode.Ok);
break;
case DurableJobRunStatus.RescheduleRequested when result.RescheduleTime is { } rescheduleTime:
if (shard is not IResettableJobShard resettableShard)
{
throw new ResettableJobShardNotSupportedException(shard.GetType());
}

LogReschedulingJob(_logger, jobContext.Job.Id, jobContext.Job.Name, rescheduleTime);
await resettableShard.RescheduleJobAsync(jobContext, rescheduleTime, cancellationToken);
_durableJobsInstruments.OnJobRescheduled(_timeProvider.GetElapsedTime(attemptStartTimestamp));
activity?.SetTag(ActivityTagKeys.DurableJobStatus, "rescheduled");
activity?.SetStatus(ActivityStatusCode.Ok);
break;
case DurableJobRunStatus.RescheduleRequested:
failureException = new InvalidOperationException(
$"Durable job '{jobContext.Job.Id}' returned RescheduleRequested without a reschedule time.");
LogErrorExecutingJob(_logger, failureException, jobContext.Job.Id);
break;
case DurableJobRunStatus.Failed when result.Exception is { } exception:
LogJobFailedWithResult(_logger, jobContext.Job.Id, jobContext.Job.Name);
failureException = exception;
break;
case DurableJobRunStatus.Failed:
failureException = new InvalidOperationException(
$"Durable job '{jobContext.Job.Id}' returned Failed without an exception.");
LogErrorExecutingJob(_logger, failureException, jobContext.Job.Id);
break;
default:
failureException = new InvalidOperationException(
$"Durable job '{jobContext.Job.Id}' returned unsupported status value {(int)result.Status}.");
LogErrorExecutingJob(_logger, failureException, jobContext.Job.Id);
break;
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
catch (Exception ex) when (ex is not OperationCanceledException and not ResettableJobShardNotSupportedException)
{
LogErrorExecutingJob(_logger, ex, jobContext.Job.Id);
failureException = ex;
Expand All @@ -305,6 +332,7 @@ private async Task ExecuteJobAsync(
DurableJobsDiagnostics.SetError(activity, failureException);
}
}

}
catch (OperationCanceledException exception) when (cancellationToken.IsCancellationRequested)
{
Expand All @@ -323,4 +351,9 @@ private async Task ExecuteJobAsync(
runningTasks?.TryRemove(jobContext.Job.Id, out _);
}
}

private sealed class ResettableJobShardNotSupportedException(Type shardType)
: NotSupportedException(
$"Job shard implementation '{shardType}' does not support successful reset-rescheduling. "
+ "RescheduleRequested cannot be processed without changing failure-attempt semantics.");
}
Loading
Loading