Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,4 @@ jobs:
dotnet-repo-path: ${{github.event.pull_request.head.repo.full_name}}
version: ${{github.event.pull_request.head.ref}}
version-is-repo-ref: true
features-repo-ref: standalone-activities-dotnet

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note, we will need to merge this branch into features repo right after this PR is merged.

36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Extensions:
- [Activity Execution Context](#activity-execution-context)
- [Activity Heartbeating and Cancellation](#activity-heartbeating-and-cancellation)
- [Activity Worker Shutdown](#activity-worker-shutdown)
- [Invoking Standalone Activities](#invoking-standalone-activities)
- [Activity Testing](#activity-testing)
- [Nexus](#nexus)
- [Nexus Operations Backed by Workflows](#nexus-operations-backed-by-workflows)
Expand Down Expand Up @@ -1126,6 +1127,41 @@ still-running activities via `ActivityExecutionContext.CancellationToken`.
Worker shutdown will wait on all activities to complete, so if a long-running activity does not respect cancellation,
the shutdown may never complete.

#### Invoking Standalone Activities

Activities can also be started directly from a client, independent of a workflow. These are called "standalone
activities". For example:

```csharp
using Temporalio.Client;

// Start a standalone activity via lambda
var handle = await client.StartActivityAsync(
() => MyActivities.MyActivityAsync("some-arg"),
new(id: "my-activity-id", taskQueue: "my-task-queue")
{
ScheduleToCloseTimeout = TimeSpan.FromMinutes(5),
});

// Wait for the result
var result = await handle.GetResultAsync();
```

Notes about the above code:

* `StartActivityAsync` accepts a lambda expression that invokes the activity method, similar to
`Workflow.ExecuteActivityAsync`.
* `Id` and `TaskQueue` are required on `StartActivityOptions`. Either `ScheduleToCloseTimeout` or
`StartToCloseTimeout` must also be set.
* Non-type-safe forms of `StartActivityAsync` exist that accept a string activity name and an object array for
arguments.
* A shortcut extension `ExecuteActivityAsync` is available that is just `StartActivityAsync` + `GetResultAsync`.
* The `handle` is an `ActivityHandle` which has `GetResultAsync`, `DescribeAsync`, `CancelAsync`, and `TerminateAsync`
methods. For existing activities, handles can be obtained via `client.GetActivityHandle`.
* If the activity fails, `GetResultAsync` throws `ActivityFailedException`.
* If the activity already exists according to the ID reuse/conflict policy, `StartActivityAsync` throws
`ActivityAlreadyStartedException`.

#### Activity Testing

Unit testing an activity or any code that could run in an activity is done via the
Expand Down
2 changes: 1 addition & 1 deletion src/Temporalio/Activities/ActivityExecutionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ internal ActivityExecutionContext(
{
return runtimeMetricMeter.Value.WithTags(new Dictionary<string, object>()
{
{ "namespace", info.WorkflowNamespace },
{ "namespace", info.Namespace },
{ "task_queue", info.TaskQueue },
{ "activity_type", info.ActivityType },
});
Expand Down
36 changes: 24 additions & 12 deletions src/Temporalio/Activities/ActivityInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ namespace Temporalio.Activities
/// <param name="HeartbeatDetails">Details from the last heartbeat of the last attempt.</param>
/// <param name="HeartbeatTimeout">Heartbeat timeout set by the caller.</param>
/// <param name="IsLocal">Whether the activity is a local activity or not.</param>
/// <param name="Namespace">Namespace this activity is on.</param>
/// <param name="Priority">The Priority of this activity.</param>
/// <param name="RetryPolicy">
/// The retry policy of this activity.
Expand All @@ -34,10 +35,14 @@ namespace Temporalio.Activities
/// <param name="StartedTime">When the activity started.</param>
/// <param name="TaskQueue">Task queue this activity is on.</param>
/// <param name="TaskToken">Task token uniquely identifying this activity.</param>
/// <param name="WorkflowId">Workflow ID that started this activity.</param>
/// <param name="WorkflowNamespace">Namespace this activity is on.</param>
/// <param name="WorkflowRunId">Workflow run ID that started this activity.</param>
/// <param name="WorkflowType">Workflow type name that started this activity.</param>
/// <param name="WorkflowId">Workflow ID that started this activity, or null for standalone
/// activities.</param>
/// <param name="WorkflowNamespace">Namespace of the workflow that started this activity, or
/// null for standalone activities.</param>
/// <param name="WorkflowRunId">Workflow run ID that started this activity, or null for
/// standalone activities.</param>
/// <param name="WorkflowType">Workflow type name that started this activity, or null for
/// standalone activities.</param>
/// <remarks>
/// WARNING: This constructor may have required properties added. Do not rely on the exact
/// constructor, only use "with" clauses.
Expand All @@ -51,6 +56,7 @@ public record ActivityInfo(
IReadOnlyCollection<Payload> HeartbeatDetails,
TimeSpan? HeartbeatTimeout,
bool IsLocal,
string Namespace,
Temporalio.Common.Priority Priority,
Temporalio.Common.RetryPolicy? RetryPolicy,
TimeSpan? ScheduleToCloseTimeout,
Expand All @@ -59,11 +65,17 @@ public record ActivityInfo(
DateTime StartedTime,
string TaskQueue,
byte[] TaskToken,
string WorkflowId,
string WorkflowNamespace,
string WorkflowRunId,
string WorkflowType)
string? WorkflowId,
string? WorkflowNamespace,
string? WorkflowRunId,
string? WorkflowType)
{
/// <summary>
/// Gets a value indicating whether this activity was started by a workflow.
/// </summary>
/// <remarks>WARNING: Standalone activities are experimental.</remarks>
public bool IsWorkflowActivity => WorkflowId != null;

/// <summary>
/// Gets the value that is set on
/// <see cref="Microsoft.Extensions.Logging.ILogger.BeginScope" /> before this activity is
Expand All @@ -74,10 +86,10 @@ public record ActivityInfo(
["ActivityId"] = ActivityId,
["ActivityType"] = ActivityType,
["Attempt"] = Attempt,
["WorkflowNamespace"] = WorkflowNamespace,
["WorkflowId"] = WorkflowId,
["WorkflowRunId"] = WorkflowRunId,
["WorkflowType"] = WorkflowType,
["Namespace"] = Namespace,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we maybe preserve WorkflowNamespace and only fill it if it's workflow activity? That way we don't wholesale break anyone who is scraping logs, especially for those who aren't using this experimental feature yet.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can, though the question is whether we should also emit a Namespace at that time? Is it worth the redundant scope?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking this through...

Previously, WorkflowNamespace was always added as a scope value and always had a value. Log scraping/queries who look for it a likely relying on it being there. With this change as-is, that key will no longer be there at all. So they would have to adjust their code to find the new kew.

With my suggestion, WorkflowNamespace would still be provided under those circumstances IF they don't start using standalone activities. Once they start using standalone activities, some of their log entries won't have WorkflowNamespace (for those that are standalone activities). This would avoid a break until they start using the experimental feature.

So questions are:

  • do we break now while the feature is still experimental and probably not used in environments where log scraping is occurring? Maybe we can defer the break until standalone activities is GA?
  • do we break only for standalone activities?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, all of that makes sense, and I don't have a strong opinion on whether to break existing log scope keys now, later, or not at all. It makes sense for me to put WorkflowNamespace back for now.

What I was asking was a followup question - do we emit Namespace always or only for standalone activities?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we always emit Namespace and say that we're deprecating WorkflowNamespace.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I will add the redundant log tag for the majority of users

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Meaning all workflow logs will have Namespace and WorkflowNamespace, but all new standalone activity logs will have just Namespace, assuming that is what you meant.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine with theremoval of WorkflowNamespace now as you have in this PR. If we are ever going to remove it, I think now is better than later.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Same for other workflow tags. Can you take a look at 287ed97 and confirm it is what you were thinking?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm :shipit:

["WorkflowId"] = WorkflowId ?? string.Empty,
["WorkflowRunId"] = WorkflowRunId ?? string.Empty,
["WorkflowType"] = WorkflowType ?? string.Empty,
};

/// <summary>
Expand Down
35 changes: 35 additions & 0 deletions src/Temporalio/Client/ActivityCancelOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;

namespace Temporalio.Client
{
/// <summary>
/// Options for canceling a standalone activity.
/// </summary>
/// <remarks>WARNING: Standalone activities are experimental.</remarks>
public class ActivityCancelOptions : ICloneable
{
/// <summary>
/// Gets or sets the reason for the cancellation request.
/// </summary>
public string? Reason { get; set; }

/// <summary>
/// Gets or sets RPC options for canceling the activity.
/// </summary>
public RpcOptions? Rpc { get; set; }

/// <summary>
/// Create a shallow copy of these options.
/// </summary>
/// <returns>A shallow copy of these options and any transitive options fields.</returns>
public virtual object Clone()
{
var copy = (ActivityCancelOptions)MemberwiseClone();
if (Rpc != null)
{
copy.Rpc = (RpcOptions)Rpc.Clone();
}
return copy;
}
}
}
30 changes: 30 additions & 0 deletions src/Temporalio/Client/ActivityCountOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;

namespace Temporalio.Client
{
/// <summary>
/// Options for <see cref="ITemporalClient.CountActivitiesAsync" />.
/// </summary>
/// <remarks>WARNING: Standalone activities are experimental.</remarks>
public class ActivityCountOptions : ICloneable
{
/// <summary>
/// Gets or sets RPC options for counting activities.
/// </summary>
public RpcOptions? Rpc { get; set; }

/// <summary>
/// Create a shallow copy of these options.
/// </summary>
/// <returns>A shallow copy of these options and any transitive options fields.</returns>
public virtual object Clone()
{
var copy = (ActivityCountOptions)MemberwiseClone();
if (Rpc != null)
{
copy.Rpc = (RpcOptions)Rpc.Clone();
}
return copy;
}
}
}
36 changes: 36 additions & 0 deletions src/Temporalio/Client/ActivityDescribeOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;

namespace Temporalio.Client
{
/// <summary>
/// Options for describing a standalone activity.
/// </summary>
/// <remarks>WARNING: Standalone activities are experimental.</remarks>
public class ActivityDescribeOptions : ICloneable
{
/// <summary>
/// Gets or sets a long-poll token from a previous describe response. When set, the
/// describe call will long-poll for state changes.
/// </summary>
public byte[]? LongPollToken { get; set; }

/// <summary>
/// Gets or sets RPC options for describing the activity.
/// </summary>
public RpcOptions? Rpc { get; set; }

/// <summary>
/// Create a shallow copy of these options.
/// </summary>
/// <returns>A shallow copy of these options and any transitive options fields.</returns>
public virtual object Clone()
{
var copy = (ActivityDescribeOptions)MemberwiseClone();
if (Rpc != null)
{
copy.Rpc = (RpcOptions)Rpc.Clone();
}
return copy;
}
}
}
144 changes: 144 additions & 0 deletions src/Temporalio/Client/ActivityExecution.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
using System;
using System.Threading;
using Temporalio.Api.Activity.V1;
using Temporalio.Api.Enums.V1;
using Temporalio.Common;

namespace Temporalio.Client
{
/// <summary>
/// Representation of a standalone activity execution from a list call.
/// </summary>
/// <remarks>WARNING: Standalone activities are experimental.</remarks>
public class ActivityExecution
{
private readonly Lazy<SearchAttributeCollection> searchAttributes;

/// <summary>
/// Initializes a new instance of the <see cref="ActivityExecution"/> class from list info.
/// </summary>
/// <param name="rawInfo">Raw proto list info.</param>
/// <param name="clientNamespace">Client namespace.</param>
/// <remarks>WARNING: This constructor may be mutated in backwards incompatible ways.</remarks>
protected internal ActivityExecution(
ActivityExecutionListInfo rawInfo, string clientNamespace)
: this(
clientNamespace: clientNamespace,
activityId: rawInfo.ActivityId,
activityRunId: string.IsNullOrEmpty(rawInfo.RunId) ? null : rawInfo.RunId,
activityType: rawInfo.ActivityType?.Name ?? string.Empty,
Comment thread
jmaeagle99 marked this conversation as resolved.
Resolved
closeTime: rawInfo.CloseTime?.ToDateTime(),
executionDuration: rawInfo.ExecutionDuration?.ToTimeSpan(),
scheduledTime: rawInfo.ScheduleTime?.ToDateTime() ?? default,
Comment thread
jmaeagle99 marked this conversation as resolved.
Resolved
stateTransitionCount: rawInfo.StateTransitionCount,
status: rawInfo.Status,
taskQueue: rawInfo.TaskQueue,
searchAttributesFactory: () => rawInfo.SearchAttributes == null ?
SearchAttributeCollection.Empty :
SearchAttributeCollection.FromProto(rawInfo.SearchAttributes))
{
RawInfo = rawInfo;
}

/// <summary>
/// Initializes a new instance of the <see cref="ActivityExecution"/> class.
/// </summary>
/// <param name="clientNamespace">Client namespace.</param>
/// <param name="activityId">Activity ID.</param>
/// <param name="activityRunId">Activity run ID.</param>
/// <param name="activityType">Activity type name.</param>
/// <param name="closeTime">Close time.</param>
/// <param name="executionDuration">Execution duration.</param>
/// <param name="scheduledTime">Scheduled time.</param>
/// <param name="stateTransitionCount">State transition count.</param>
/// <param name="status">Activity status.</param>
/// <param name="taskQueue">Task queue.</param>
/// <param name="searchAttributesFactory">Factory for lazy search attribute creation.</param>
private protected ActivityExecution(
string clientNamespace,
string activityId,
string? activityRunId,
string activityType,
DateTime? closeTime,
TimeSpan? executionDuration,
DateTime scheduledTime,
long stateTransitionCount,
ActivityExecutionStatus status,
string taskQueue,
Func<SearchAttributeCollection> searchAttributesFactory)
{
Namespace = clientNamespace;
ActivityId = activityId;
ActivityRunId = activityRunId;
ActivityType = activityType;
CloseTime = closeTime;
ExecutionDuration = executionDuration;
ScheduledTime = scheduledTime;
StateTransitionCount = stateTransitionCount;
Status = status;
TaskQueue = taskQueue;
searchAttributes = new(searchAttributesFactory, LazyThreadSafetyMode.PublicationOnly);
}

/// <summary>
/// Gets the activity ID.
/// </summary>
public string ActivityId { get; private init; }

/// <summary>
/// Gets the activity run ID.
/// </summary>
public string? ActivityRunId { get; private init; }

/// <summary>
/// Gets the activity type name.
/// </summary>
public string ActivityType { get; private init; }

/// <summary>
/// Gets when the activity was closed if in a terminal state.
/// </summary>
public DateTime? CloseTime { get; private init; }

/// <summary>
/// Gets the total execution duration if the activity is closed.
/// </summary>
public TimeSpan? ExecutionDuration { get; private init; }

/// <summary>
/// Gets the namespace.
/// </summary>
public string Namespace { get; private init; }

/// <summary>
/// Gets when the activity was originally scheduled.
/// </summary>
public DateTime ScheduledTime { get; private init; }

/// <summary>
/// Gets the number of state transitions.
/// </summary>
public long StateTransitionCount { get; private init; }

/// <summary>
/// Gets the status of the activity.
/// </summary>
public ActivityExecutionStatus Status { get; private init; }

/// <summary>
/// Gets the task queue for the activity.
/// </summary>
public string TaskQueue { get; private init; }

/// <summary>
/// Gets the search attributes on the activity.
/// </summary>
/// <remarks>This is lazily converted on first access.</remarks>
public SearchAttributeCollection TypedSearchAttributes => searchAttributes.Value;

/// <summary>
/// Gets the raw proto list info, or null if this was created from a describe call.
/// </summary>
internal ActivityExecutionListInfo? RawInfo { get; private init; }
}
}
Loading
Loading