Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,20 @@ public class TwilioConversationRelayController : TwilioController
private readonly TwilioSetting _settings;
private readonly IServiceProvider _services;
private readonly ConversationRelaySessions _sessions;
private readonly ConversationRelayResumes _resumes;
private readonly ILogger _logger;

public TwilioConversationRelayController(
TwilioSetting settings,
IServiceProvider services,
ConversationRelaySessions sessions,
ConversationRelayResumes resumes,
ILogger<TwilioConversationRelayController> logger)
{
_settings = settings;
_services = services;
_sessions = sessions;
_resumes = resumes;
_logger = logger;
}

Expand Down Expand Up @@ -52,6 +55,18 @@ await HookEmitter.Emit<ITwilioSessionHook>(_services,

var callStillUp = !string.Equals(request.CallStatus, "completed", StringComparison.OrdinalIgnoreCase);
var canReconnect = request.Reconnects < _settings.ConversationRelay.MaxReconnects;

// A session whose playback was stuck dropped its socket and kept what never finished playing: a new session says it.
// Nothing is told to the hooks, as the call goes on. Whatever status Twilio gives the dropped session.
var resume = action == null && callStillUp && canReconnect ? await _resumes.TakeAsync(request.ConversationId) : null;
if (resume != null)
{
_logger.LogWarning($"Reconnecting ConversationRelay for conversation {request.ConversationId}: its playback was " +
$"stuck (attempt {request.Reconnects + 1}).");
return TwiML(twilio.ReturnConversationRelay(request.AgentId, request.ConversationId, welcomeGreeting: null,
request.Reconnects + 1, resume));
}

if (request.SessionStatus == "failed" && callStillUp && canReconnect)
{
_logger.LogWarning($"Reconnecting ConversationRelay for conversation {request.ConversationId} " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,14 @@ namespace BotSharp.Plugin.Twilio.Models.Relay;
public static class ConversationRelayParameters
{
public const string WelcomeGreetingLength = "welcome-greeting-length";

/// <summary>
/// How many times the call's relay has been connected again
/// </summary>
public const string Reconnects = "reconnects";

/// <summary>
/// What a session connected again in place of one whose playback was stuck starts with (<see cref="ConversationRelayResume"/>)
/// </summary>
public const string Resume = "resume";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
namespace BotSharp.Plugin.Twilio.Models.Relay;

/// <summary>
/// What a session connected again in place of one whose playback was stuck starts with: the lines the caller never heard
/// all of, and how the flow last said to treat a silent caller
/// </summary>
/// <remarks>
/// The stuck session keeps it (ConversationRelayResumes), Twilio's callback takes it into the new relay's TwiML as a
/// Parameter, and the new session reads it from its setup, so each may run on another instance.
/// </remarks>
public class ConversationRelayResume
{
/// <summary>
/// The lines said since Twilio last said playback stopped, in order, but fillers and idle prompts
/// </summary>
public List<ConversationRelayResumeLine> Lines { get; set; } = [];

/// <summary>
/// The flow was waiting quietly for the caller (ConversationRelayStates.QuietWait)
/// </summary>
public bool QuietWait { get; set; }

/// <summary>
/// What the flow said to say if the caller stays silent until the hang-up (ConversationRelayStates.GoodbyeOnSilence)
/// </summary>
public string? GoodbyeOnSilence { get; set; }
}

public class ConversationRelayResumeLine
{
public string Text { get; set; } = string.Empty;

/// <summary>
/// It went out to play to the end whoever speaks over it, and goes out so again
/// </summary>
public bool KeepUninterrupted { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using StackExchange.Redis;
using System.Collections.Concurrent;
using Task = System.Threading.Tasks.Task;

namespace BotSharp.Plugin.Twilio.Services;

/// <summary>
/// What a session connected again in place of one whose playback was stuck starts with
/// (<see cref="Models.Relay.ConversationRelayResume"/>), from the stuck session to Twilio's callback asking what next
/// </summary>
/// <remarks>
/// Why kept here and not sent with the session's end: Twilio acts on an "end" message only once what is queued has played,
/// and a stuck playback never has, so the stuck session drops its socket instead, which carries nothing. The callback may
/// run on another instance: kept in Redis when there is one, in this instance otherwise.
/// </remarks>
public class ConversationRelayResumes
{
// Long enough for Twilio's callback, which comes within seconds of the socket dropping
private static readonly TimeSpan Kept = TimeSpan.FromMinutes(5);

private readonly IServiceProvider _services;
private readonly ILogger _logger;
private readonly ConcurrentDictionary<string, (string Json, DateTime UntilUtc)> _here = new();

public ConversationRelayResumes(IServiceProvider services, ILogger<ConversationRelayResumes> logger)
{
_services = services;
_logger = logger;
}

/// <summary>
/// Keeps what the session taking the place of <paramref name="conversationId"/>'s stuck one starts with
/// </summary>
public async Task KeepAsync(string conversationId, string json)
{
if (_services.GetService<IConnectionMultiplexer>() is { } redis)
{
try
{
await redis.GetDatabase().StringSetAsync(Key(conversationId), json, Kept);
return;
}
catch (RedisException ex)
{
_logger.LogWarning(ex, $"Could not keep the resume of conversation {conversationId} in Redis; kept on this instance.");
}
}
_here[conversationId] = (json, DateTime.UtcNow + Kept);
}

/// <summary>
/// Takes what was kept for <paramref name="conversationId"/>, once: null when nothing was, or it is gone
/// </summary>
public async Task<string?> TakeAsync(string conversationId)
{
if (string.IsNullOrEmpty(conversationId))
{
return null;
}

if (_services.GetService<IConnectionMultiplexer>() is { } redis)
{
try
{
// Read and deleted in one transaction, so two callbacks at once (Twilio retrying one) can't both take it.
// Not GETDEL, which needs Redis 6.2.
var transaction = redis.GetDatabase().CreateTransaction();
var kept = transaction.StringGetAsync(Key(conversationId));
var deleted = transaction.KeyDeleteAsync(Key(conversationId));
await transaction.ExecuteAsync();
await deleted;
var value = await kept;
if (value.HasValue)
{
return value.ToString();
}
}
catch (RedisException ex)
{
_logger.LogWarning(ex, $"Could not read the resume of conversation {conversationId} from Redis.");
}
}
return _here.TryRemove(conversationId, out var here) && here.UntilUtc > DateTime.UtcNow ? here.Json : null;
}

private static string Key(string conversationId) => $"twilio:relay:resume:{conversationId}";
}
Loading
Loading