Idle Timer with Resolution
View as MarkdownRecord every incoming message, and end when someone resolves the conversation or when no message arrives for a while (formerly Inbound Event Loop).
Use this pattern when a Flow takes inbound messages until a resolution arrives or the conversation goes quiet. Examples are replies in a support ticket, messages in a chat session, or answers in a review thread. It extends the Idle Timer: each message restarts the inactivity Timer, and a separate resolution message ends the loop.
How it works
- An RPC validates each reply and publishes it to a reply Channel. Another RPC validates the resolution and publishes it to a resolution Channel.
- One waiting Step returns
AnyOfover the reply Channel, the resolution Channel, and the inactivity Timer. - When replies win, its
Executeappends them to the transcript and moves back to the same Step. The new execution registers a new wait, so the inactivity Timer restarts. - When the resolution wins,
Executemoves to the Step that closes the resolved ticket. When the Timer wins, it moves to the Step that closes the quiet ticket. - Each closing Step completes the Flow with
ForceCompleteIfChannelsEmpty. The close decision checks the Channels the Step names and accepts the close in one atomic commit. When a message committed before that check is still in a checked Channel, Dex moves back to the waiting Step instead of closing.
Rules
- The RPC only validates its input and publishes it to a Channel. It writes no Attribute that the waiting Step reads or locks.
- One waiting Step waits on
AnyOfover the reply Channel, the resolution Channel, and the inactivity Timer. - Declare the reply Channel before the resolution Channel. When several Channel Conditions are ready at once, the first one declared wins, and only the winner's messages are consumed. Replies accepted before the resolution are therefore recorded first.
- A Channel Condition consumes messages only when it wins. A reply that arrives while
Executeruns stays queued for the next execution, so no reply is lost. Executeappends the consumed messages to an Attribute, such as a transcript. The waiting Step is the only writer of that Attribute.Executethen moves back to the same Step. The new execution registers a new wait, so the inactivity Timer restarts after each message.- To take every queued reply at once, use an at-least-one Channel Condition. You can also take one reply per execution.
- Keep the transcript bounded. A long conversation stores its messages in a sequentially chunked AttributeMap. The example's waiting Step loads only the current chunk.
Why the Step owns the transcript
If the RPC appended to the transcript, the waiting Step would have to lock the transcript, and the RPC would have to lock it too for its read-modify-write. Locks do not queue. Every RPC that arrives while the Step holds the lock, or while another RPC holds it, is rejected with a lock conflict, and the client must retry. Publishing to a Channel needs no lock, so concurrent replies never conflict.
Messages at the close
Every closing Step completes with ForceCompleteIfChannelsEmpty on the reply Channel, as in Drain External Channels. Its fallback moves back to the waiting Step.
- The resolution closes only when the reply Channel is empty at the atomic check. A reply committed before that check, still queued or taken by a Step that has not finished, triggers the fallback, which carries the resolution back to the waiting Step. That Step waits only for replies, writes them to the transcript, and moves to the resolution close again.
- The inactivity close also checks the resolution Channel. A reply or a resolution can commit after the Timer won, before the inactivity close runs. Its check finds the message, and the fallback reopens the wait. A reply is then written to the transcript, and a resolution moves to the resolution close.
- Keep the waiting Step the only consumer of the reply Channel.
The resolution RPC rejects an empty reason, because an empty pending resolution means "none".
An RPC that publishes after the check, while the close is pending, fails with FLOW_CLOSING and commits nothing; see Pending close. A request that arrives while the Flow closes follows Requests during Flow close.
A successful RPC confirms that the message was published. Confirming that it was handled is a separate step. When the caller must confirm each reply was handled, the waiting Step records the reply's business ID in the same commit, and the caller reads that record. To retry the same delivery, reuse its RPC request ID. Before a new delivery of a reply, check that record for its business ID. See Confirm that a message was handled.
Example
SupportTicketConversationFlow takes replies to a support ticket. sendTicketReply rejects empty and overlong replies. resolveTicket rejects an empty reason. AwaitTicketMessage records replies, or moves to CloseResolvedTicket or CloseInactiveTicket. Its input is the pending resolution, which is empty until a resolution close falls back. The inactivity Timer is 24 hours. The tests skip it with the Client SkipTimer instead of shortening it.
TICKET_REPLIES = Channel("ticketReplies", str)
TICKET_RESOLUTIONS = Channel("ticketResolutions", str)
TRANSCRIPT_CHUNKS = AttributeMap("transcriptChunks", TranscriptChunk)
class AwaitTicketMessage(Step[str]):
"""Waits for replies, a resolution, or inactivity; the input is a pending resolution."""
def wait_for(self, context: Context, pending_resolution: str) -> Wait:
if pending_resolution:
return Wait.until(TICKET_REPLIES.at_least(1))
# Replies come before the resolution, so earlier replies are recorded first.
return Wait.any_of(
TICKET_REPLIES.at_least(1),
TICKET_RESOLUTIONS.for_one(),
Timer.by_duration(INACTIVITY_TIMEOUT),
)
def execute(self, context: Context, pending_resolution: str) -> StepDecision:
replies = TICKET_REPLIES.results(context)
if replies:
# Appends replies to the current chunk and archives each full chunk.
chunk = TRANSCRIPT_CHUNKS.get(context, CURRENT_TRANSCRIPT_CHUNK) or TranscriptChunk()
next_sequence = chunk.replies[-1].sequence + 1 if chunk.replies else 1
for text in replies:
if len(chunk.replies) == TRANSCRIPT_CHUNK_SIZE:
archive_token = archive_chunk_token(chunk.replies[0].sequence)
TRANSCRIPT_CHUNKS.set(context, archive_token, chunk)
chunk = TranscriptChunk()
chunk.replies.append(TicketReply(next_sequence, text))
Example: examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py
var (
TicketReplies = dex.DefineChannel[string]("ticketReplies")
TicketResolutions = dex.DefineChannel[string]("ticketResolutions")
TranscriptChunks = dex.DefineAttributeMap[TranscriptChunk]("transcriptChunks")
)
// SendTicketReply validates one reply and queues it for the waiting Step.
func (*SupportTicketConversationFlow) SendTicketReply(ctx dex.Context, text string) (*dex.RPCResult[dex.None], error) {
if strings.TrimSpace(text) == "" {
return nil, fmt.Errorf("reply text is required")
}
if utf8.RuneCountInString(text) > MaxReplyLength {
return nil, fmt.Errorf("reply text exceeds %d characters", MaxReplyLength)
}
if err := TicketReplies.Publish(ctx, text); err != nil {
return nil, err
}
return &dex.RPCResult[dex.None]{}, nil
}
// ResolveTicket queues the resolution; an empty reason would mean no resolution.
func (*SupportTicketConversationFlow) ResolveTicket(ctx dex.Context, reason string) (*dex.RPCResult[dex.None], error) {
if strings.TrimSpace(reason) == "" {
return nil, fmt.Errorf("resolution reason is required")
}
if err := TicketResolutions.Publish(ctx, reason); err != nil {
return nil, err
}
return &dex.RPCResult[dex.None]{}, nil
}
Example: examples/go/patterns/inbound-event-loop/workflow.go
public static final Channel<String> ticketReplies =
Channel.define("ticketReplies", String.class);
public static final Channel<String> ticketResolutions =
Channel.define("ticketResolutions", String.class);
public static final AttributeMap<TranscriptChunk> transcriptChunks =
AttributeMap.define("transcriptChunks", TranscriptChunk.class);
/** Validates one reply and queues it for the waiting Step. */
@RPC
public void sendTicketReply(final Context context, final String text) {
if (text == null || text.isBlank()) {
throw new IllegalArgumentException("reply text is required");
}
if (text.codePointCount(0, text.length()) > MAX_REPLY_LENGTH) {
throw new IllegalArgumentException(
"reply text exceeds " + MAX_REPLY_LENGTH + " characters");
}
ticketReplies.publish(context, text);
}
/** Queues the resolution; an empty reason would mean no resolution. */
@RPC
public void resolveTicket(final Context context, final String reason) {
if (reason == null || reason.isBlank()) {
throw new IllegalArgumentException("resolution reason is required");
}
ticketResolutions.publish(context, reason);
}
/** Waits for replies, a resolution, or inactivity; the input is a pending resolution. */
export const ticketReplies = new Channel("ticketReplies", stringCodec);
export const ticketResolutions = new Channel("ticketResolutions", stringCodec);
export const transcriptChunks = new AttributeMap(
"transcriptChunks",
jsonCodec<TranscriptChunk>(),
);
class AwaitTicketMessage implements Step<string> {
public readonly inputCodec = stringCodec;
public getStepType(): string {
return "AwaitTicketMessage";
}
public getStepOptions(): StepOptions {
return {
executeLoadAttributeMapInstances: [transcriptChunks.load(CURRENT_TRANSCRIPT_CHUNK)],
};
}
public waitFor(_context: Context, pendingResolution: string): Wait {
if (pendingResolution !== "") {
return Wait.until(ticketReplies.atLeast(1));
}
// Replies come before the resolution, so earlier replies are recorded first.
return Wait.anyOf(
ticketReplies.atLeast(1),
ticketResolutions.forOne(),
Timer.byDuration(INACTIVITY_TIMEOUT_MS),
);
Example: examples/typescript/src/patterns/inbound-event-loop/support-ticket-flow.ts
pub static TICKET_REPLIES: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("ticketReplies"));
pub static TICKET_RESOLUTIONS: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("ticketResolutions"));
pub static TRANSCRIPT_CHUNKS: LazyLock<AttributeMap<TranscriptChunk>> =
LazyLock::new(|| AttributeMap::new("transcriptChunks"));
impl SupportTicketConversationFlow {
/// Validates one reply and queues it for the waiting Step.
fn send_ticket_reply(&self, context: &mut Context, text: String) -> HandlerResult<()> {
if text.trim().is_empty() {
return Err(HandlerError::new(
"SupportTicketConversationFlow",
"reply text is required",
));
}
if text.chars().count() > MAX_REPLY_LENGTH {
return Err(HandlerError::new(
"SupportTicketConversationFlow",
format!("reply text exceeds {MAX_REPLY_LENGTH} characters"),
));
}
TICKET_REPLIES.publish(context, text)
}
/// Queues the resolution; an empty reason would mean no resolution.
fn resolve_ticket(&self, context: &mut Context, reason: String) -> HandlerResult<()> {
if reason.trim().is_empty() {
return Err(HandlerError::new(
"SupportTicketConversationFlow",
Example: examples/rust/src/control_patterns/inbound_event_loop/flow.rs
The transcript update, the HTTP controller, and the tests are in the example folders. Run the HTTP sample from the examples playground.