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
6 changes: 3 additions & 3 deletions acceleration/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2314,7 +2314,7 @@ components:
name:
type: string
paused_reason:
description: 'Why the router paused the campaign itself: the code of what refused its next call, for example telephony_suspended, account_suspended, insufficient_credits, system_limit_reached, spend_limit_reached, user_limit_reached or spend_check_unavailable, config_missing when its agent config was deleted, session_refused when its agent config makes a session that cannot open, or voicemail_needs_exact_words when its step leaves a voicemail message and its agent config became speech-to-speech. The contact that call was for is rung once the campaign is resumed. Absent for a campaign somebody paused, and cleared by resuming it.'
description: 'Why the router paused the campaign itself: the code of what refused its next call, for example telephony_suspended, account_suspended, insufficient_credits, system_limit_reached, spend_limit_reached, user_limit_reached or spend_check_unavailable, stream_app_disconnected or stream_app_moved when the app''s Stream app was disconnected or moved, config_missing when its agent config was deleted, session_refused when its agent config makes a session that cannot open, or voicemail_needs_exact_words when its step leaves a voicemail message and its agent config became speech-to-speech. The contact that call was for is rung once the campaign is resumed. Absent for a campaign somebody paused, and cleared by resuming it.'
type: string
sequence:
$ref: '#/components/schemas/CampaignSequence'
Expand Down Expand Up @@ -2399,7 +2399,7 @@ components:
CampaignAttempt:
properties:
delay_minutes:
description: Minutes after the previous attempt started, pushed into the calling hours.
description: Minutes after the previous attempt started, pushed into the calling hours. At most 43200 (30 days).
format: int64
type: integer
required:
Expand Down Expand Up @@ -4147,7 +4147,7 @@ components:
description: 'The outcome an answered call was read as: no_response when nobody but the agent spoke.'
type: string
result:
description: 'Why the dial placed no call: invalid_number, refused, deferred, paused or not_placed (the router stopped before the call went out). voicemail for a call an answering machine took. Empty for any other call, whose end call_outcome says.'
description: 'Why the dial placed no call: invalid_number, refused, deferred, paused, not_placed (the router stopped before the call went out) or dial_failed (it failed before anything rang, and is tried again shortly). voicemail for a call an answering machine took. Empty for any other call, whose end call_outcome says.'
type: string
started_at:
format: date-time
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/campaign_contacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ type ContactAttempt struct {
Attempt int `json:"attempt" doc:"Which attempt of the sequence, from 1."`
Dial int `json:"dial" doc:"1, or 2 for the second call of a double dial."`
CallId *string `json:"call_id,omitempty"`
Result string `json:"result" doc:"Why the dial placed no call: invalid_number, refused, deferred, paused or not_placed (the router stopped before the call went out). voicemail for a call an answering machine took. Empty for any other call, whose end call_outcome says."`
Result string `json:"result" doc:"Why the dial placed no call: invalid_number, refused, deferred, paused, not_placed (the router stopped before the call went out) or dial_failed (it failed before anything rang, and is tried again shortly). voicemail for a call an answering machine took. Empty for any other call, whose end call_outcome says."`
CallOutcome *CallOutcome `json:"call_outcome,omitempty" doc:"How the call the dial placed ended, as the phone says. Absent while it is happening and for a dial that placed none."`
Outcome *string `json:"outcome,omitempty" doc:"The outcome an answered call was read as: no_response when nobody but the agent spoke."`
StartedAt time.Time `json:"started_at"`
Expand Down
4 changes: 2 additions & 2 deletions acceleration/internal/api/campaigns.go
Original file line number Diff line number Diff line change
Expand Up @@ -890,7 +890,7 @@ type Campaign struct {
Sequence CampaignSequence `json:"sequence"`
CallingHours CallingHours `json:"calling_hours"`
Tags map[string]string `json:"tags" nullable:"false"`
PausedReason *string `json:"paused_reason,omitempty" doc:"Why the router paused the campaign itself: the code of what refused its next call, for example telephony_suspended, account_suspended, insufficient_credits, system_limit_reached, spend_limit_reached, user_limit_reached or spend_check_unavailable, config_missing when its agent config was deleted, session_refused when its agent config makes a session that cannot open, or voicemail_needs_exact_words when its step leaves a voicemail message and its agent config became speech-to-speech. The contact that call was for is rung once the campaign is resumed. Absent for a campaign somebody paused, and cleared by resuming it."`
PausedReason *string `json:"paused_reason,omitempty" doc:"Why the router paused the campaign itself: the code of what refused its next call, for example telephony_suspended, account_suspended, insufficient_credits, system_limit_reached, spend_limit_reached, user_limit_reached or spend_check_unavailable, stream_app_disconnected or stream_app_moved when the app's Stream app was disconnected or moved, config_missing when its agent config was deleted, session_refused when its agent config makes a session that cannot open, or voicemail_needs_exact_words when its step leaves a voicemail message and its agent config became speech-to-speech. The contact that call was for is rung once the campaign is resumed. Absent for a campaign somebody paused, and cleared by resuming it."`
StartAt *time.Time `json:"start_at,omitempty" doc:"When it was launched to start ringing."`
LaunchedAt *time.Time `json:"launched_at,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty" doc:"When it first rang anybody."`
Expand Down Expand Up @@ -968,7 +968,7 @@ type CampaignVoicemail struct {

// CampaignAttempt is one try at reaching a contact.
type CampaignAttempt struct {
DelayMinutes int `json:"delay_minutes" doc:"Minutes after the previous attempt started, pushed into the calling hours."`
DelayMinutes int `json:"delay_minutes" doc:"Minutes after the previous attempt started, pushed into the calling hours. At most 43200 (30 days)."`
}

// CampaignOutcome is one way an answered call can end.
Expand Down
15 changes: 15 additions & 0 deletions acceleration/internal/api/campaigns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -764,3 +764,18 @@ func (s *CampaignsSuite) TestLeavingAMessageWithASpeechToSpeechAgentIsRefusedAtL
map[string]any{"sequence": sequence}, nil))
s.launch(created)
}

// A delay is made a duration in nanoseconds, which a delay of 200 million minutes overflows:
// the next attempt would land decades in the past and the rest would ring back to back.
func (s *CampaignsSuite) TestADelayOverThirtyDaysIsRefused() {
created := s.create(map[string]any{"name": "may"})
sequence := created.Sequence
sequence.Steps[0].Attempts = []CampaignAttempt{{0}, {200000000}}

status, failure := s.serverClient.failure(http.MethodPatch, "/v1/agents/campaigns/"+created.Id,
map[string]any{"sequence": sequence})

s.Equal(http.StatusBadRequest, status)
s.Contains(failure, "43200 minutes")
s.Len(s.get(created.Id).Sequence.Steps[0].Attempts, 4, "the sequence stored is unchanged")
}
65 changes: 57 additions & 8 deletions acceleration/internal/campaign/campaign.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"github.com/GetStream/Vision-Agents/acceleration/internal/session"
"github.com/GetStream/Vision-Agents/acceleration/internal/stack"
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
"github.com/GetStream/Vision-Agents/acceleration/internal/streamapp"
)

// callTimeout bounds one conversation. Nothing else ends a campaign call: the agent is
Expand Down Expand Up @@ -90,7 +91,8 @@ type Dial struct {
}

// Dialer places a call and returns once it is over. An error is a dial that could not be
// tried; a refusal is a Dialed.
// tried; a refusal is a Dialed. A call that ended with no outcome, its CallID set, is read
// from the phone's record by the runner.
type Dialer interface {
Dial(ctx context.Context, dial Dial) (Dialed, error)
}
Expand Down Expand Up @@ -367,13 +369,16 @@ func (r *Runner) attempt(ctx context.Context, claimed store.Claimed) {
for number := 1; ; number++ {
dialed, err := r.ring(ctx, current, contact, step, number)
if err != nil {
r.logger.Error("could not record a campaign dial", "contact", contact.ID, "error", err)
r.logger.Error("could not record a campaign dial or read how it ended", "contact", contact.ID, "error", err)
return
}
if dialed.Result == Paused {
r.pause(ctx, current, dialed.Reason)
}
settle, again := afterDial(sequence, hours, zone, contact, number, dialed, started, r.now())
if dialed.Result == DialFailed && number == 1 && r.failingStill(ctx, contact) {
settle = unanswered(step, hours, zone, contact, started, store.Settle{StepID: step.ID, Attempt: contact.Attempt})
}
if again {
// The first dial took a while to ring out, and the campaign may have been paused
// or stopped meanwhile: nobody is rung again then, but the first dial rang them.
Expand All @@ -397,6 +402,17 @@ func (r *Runner) attempt(ctx context.Context, claimed store.Claimed) {
}
}

// failingStill reports whether the attempt's dials failed before anything rang maxDialFailures
// times, so the attempt is to be used. Unread, the dial is deferred again.
func (r *Runner) failingStill(ctx context.Context, contact store.Contact) bool {
failed, err := r.store.CampaignAttempts.CountResult(ctx, contact.ID, max(contact.Attempt, 1), string(DialFailed))
if err != nil {
r.logger.Error("could not count a campaign contact's failed dials", "contact", contact.ID, "error", err)
return false
}
return failed >= maxDialFailures
}

// mayRing reads campaign and contact again, since either may have been paused or stopped
// since the contact was claimed. A stopped contact settled as enrolled ends stopped.
func (r *Runner) mayRing(ctx context.Context, campaign store.Campaign, contact store.Contact) (store.Campaign, bool, error) {
Expand Down Expand Up @@ -455,6 +471,17 @@ func (r *Runner) ring(ctx context.Context, campaign store.Campaign, contact stor

r.countDial(campaign, dialed, err)

// Unknown would ring a double dial's person again at once, maybe just after they hung up,
// so an outcome that cannot be read leaves the dial unended and the contact leased: the
// router that takes it over reads the outcome again and never dials.
if dialed.CallID != "" && dialed.Outcome == "" && (dialed.Result == "" || dialed.Result == Voicemail) {
read, err := readOutcome(context.WithoutCancel(ctx), r.store, campaign.CustomerID, dialed.CallID)
if err != nil {
return Dialed{}, err
}
dialed.Outcome = read
}

written, cancel := context.WithTimeout(context.WithoutCancel(ctx), writeTimeout)
defer cancel()
ended := r.now()
Expand All @@ -473,6 +500,11 @@ func (r *Runner) ring(ctx context.Context, campaign store.Campaign, contact stor
// refused under.
const codeDialFailed = "dial_failed"

// maxDialFailures is how many dials of one attempt may fail before anything rang, five minutes
// apart, before the attempt is used anyway: a failure that never passes would otherwise retry
// for ever.
const maxDialFailures = 12

// countDial counts a dial in the activity record, refused when it could not be tried or placed
// no call, with its reason. A dial a shutdown cut off rang nobody and leaves the contact to be
// rung again, so it is counted when that dial is.
Expand Down Expand Up @@ -501,8 +533,16 @@ func (r *Runner) takeOver(ctx context.Context) {
return
}
for _, one := range claimed {
if err := r.recover(ctx, one); err != nil {
r.logger.Error("could not settle a campaign contact taken over", "contact", one.Contact.ID, "error", err)
err := r.recover(ctx, one)
if err == nil {
continue
}
r.logger.Error("could not settle a campaign contact taken over", "contact", one.Contact.ID, "error", err)
// A shard that does not answer would hold up the tick once per contact, each read
// waiting out its timeout, before the tick claims anybody. The rest keep the lease
// taken here and are taken over again once it runs out.
if errors.Is(err, errOutcomeUnread) {
return
}
}
}
Expand Down Expand Up @@ -531,7 +571,7 @@ func (r *Runner) recover(ctx context.Context, claimed store.Claimed) error {
if latest.EndedAt == nil {
dialed.Outcome, err = callOutcome(ctx, r.store, campaign.CustomerID, latest.CallID)
if err != nil {
return err
return fmt.Errorf("%w: %w", errOutcomeUnread, err)
}
var classifyAfter *time.Time
if dialed.answered() {
Expand Down Expand Up @@ -646,21 +686,25 @@ func (r *Runner) classify(ctx context.Context, claimed store.Classifying) error
return err
}
}
settle.LeaseUntil = contact.LeaseUntil
return r.store.CampaignContacts.ClassifyAndSettle(ctx, r.owner,
store.Classification{AttemptID: attempt.ID, Outcome: settle.Outcome, Converted: settle.Converted}, contact.ID, settle)
}

// unanswered settles an answered call nobody spoke on like a dial nobody picked up: the next
// attempt goes on schedule.
func (r *Runner) unanswered(ctx context.Context, sequence Sequence, hours CallingHours, zone *time.Location, contact store.Contact, attempt store.CampaignAttempt) error {
settle := afterSilence(sequence, hours, zone, contact, attempt.StartedAt, r.now())
settle.LeaseUntil = contact.LeaseUntil
return r.store.CampaignContacts.ClassifyAndSettle(ctx, r.owner, store.Classification{AttemptID: attempt.ID, Outcome: OutcomeNoResponse},
contact.ID, afterSilence(sequence, hours, zone, contact, attempt.StartedAt, r.now()))
contact.ID, settle)
}

// settle writes where a call left a contact, even once the call's context is gone.
func (r *Runner) settle(ctx context.Context, contact store.Contact, settle store.Settle) {
written, cancel := context.WithTimeout(context.WithoutCancel(ctx), writeTimeout)
defer cancel()
settle.LeaseUntil = contact.LeaseUntil
err := r.store.CampaignContacts.Settle(written, r.owner, contact.ID, settle)
switch {
case err == nil:
Expand Down Expand Up @@ -748,12 +792,17 @@ func meet(spec *session.Spec, placed phone.Placed) {
}

// pausing is why a refused call pauses the whole campaign rather than fails one contact: a
// suspended app's telephony, or an organization that may not pay, refuses every call after it
// too. It is the code the campaign records, or "" for a refusal of this contact alone.
// suspended app's telephony, an organization that may not pay, or a Stream app disconnected or
// moved away from refuses every call after it too. It is the code the campaign records, or ""
// for a refusal of this contact alone.
func pausing(err error) string {
switch {
case errors.Is(err, phone.ErrSuspended):
return "telephony_suspended"
case errors.Is(err, streamapp.ErrStreamAppDisconnected):
return "stream_app_disconnected"
case errors.Is(err, streamapp.ErrStreamAppMoved):
return "stream_app_moved"
case errors.Is(err, dlc.ErrUnpaid):
// The gate's refusal always wraps one of the policy's; a refusal it cannot name is
// still a refusal of money.
Expand Down
39 changes: 34 additions & 5 deletions acceleration/internal/campaign/dialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,15 @@ func NewPhoneDialer(phone *phone.Service, sessions *session.Manager, store *stor
}

// Dial places one call and stays on the line until the conversation is over. The agent config
// is read at each dial, so a change to it reaches the next person rung.
// is read at each dial, so a change to it reaches the next person rung. How a call that held
// a session ended is left for the runner to read.
func (d *phoneDialer) Dial(ctx context.Context, dial Dial) (Dialed, error) {
config, err := d.store.AgentConfigs.Get(ctx, dial.Campaign.CustomerID, cmp.Or(dial.Step.ConfigID, dial.Campaign.ConfigID))
if errors.Is(err, store.ErrNoAgentConfig) {
return Dialed{Result: Paused, Reason: reasonConfigMissing}, nil
}
if err != nil {
return Dialed{}, err
return Dialed{Result: DialFailed, Reason: codeDialFailed}, err
}

if !dial.Step.Voicemail.hangsUp() && session.FromConfig(config).Native() {
Expand All @@ -73,7 +74,8 @@ func (d *phoneDialer) Dial(ctx context.Context, dial Dial) (Dialed, error) {
placed, err := d.phone.Call(ctx, request)
if err != nil {
dialed := resultOf(err)
if dialed.Result == "" {
// A failure, as opposed to a refusal, is returned to be logged.
if dialed.Result == "" || dialed.Result == DialFailed {
return dialed, err
}
return dialed, nil
Expand Down Expand Up @@ -103,8 +105,7 @@ func (d *phoneDialer) Dial(ctx context.Context, dial Dial) (Dialed, error) {
if created.EndReason() == session.EndVoicemail {
dialed.Result = Voicemail
}
dialed.Outcome, err = callOutcome(context.WithoutCancel(ctx), d.store, dial.Campaign.CustomerID, placed.SessionID)
return dialed, err
return dialed, nil
}

// hold waits for the conversation to end, and ends it if nothing else does.
Expand Down Expand Up @@ -144,6 +145,34 @@ func (d *phoneDialer) close(created *session.Session) {
}
}

// outcomeRetries are the waits between reads of how a call ended. A database blip passes in
// well under a second, and a read that fails every time leaves the contact leased for the
// router that takes it over to read again.
var outcomeRetries = []time.Duration{200 * time.Millisecond, time.Second}

// errOutcomeUnread is a call whose outcome could not be read.
var errOutcomeUnread = errors.New("campaign: how the call ended could not be read")

// readOutcome is callOutcome, read again after each of outcomeRetries while it fails.
func readOutcome(ctx context.Context, st *store.Store, customerID, callID string) (outcome.Outcome, error) {
read, err := callOutcome(ctx, st, customerID, callID)
for _, wait := range outcomeRetries {
if err == nil {
break
}
select {
case <-ctx.Done():
return "", ctx.Err()
case <-time.After(wait):
}
read, err = callOutcome(ctx, st, customerID, callID)
}
if err != nil {
return "", fmt.Errorf("%w: %w", errOutcomeUnread, err)
}
return read, nil
}

// callOutcome is how the call placed into callID ended, as the phone keeps it. A phone that
// joined is completed, which the keeper decides only once its leg ends. One it has not decided
// yet, from a vendor that never reports or one whose report is late, is unknown.
Expand Down
Loading
Loading