Skip to content
Open
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
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
# engine

## Email commands — EM-25

Workspace sends the Email attempt commands of an operator over WebSocket in
one action, `cc_email_attempt`, with `operation`: `take`, `postpone`, `resume`,
`return`, `complete`, `renew` or `transfer`. Each command has
`thread_id`, `attempt_id`, `expected_version` and a UUID `command_id` (the same
id for a repeat of the same intent). Postpone adds `postponed_until` (Unix ms) or
`postpone_for_sec`, Renew `renewal_sec`, Return a `reason` (1–500 characters),
Transfer exactly one of `queue_id` and `agent_id` and an optional `comment`.
`cc_email_transfer_agents` with `attempt_id` lists the agents a direct transfer
may offer the email to, from `call_center.cc_email_transfer_candidates`.

The domain, the user and the agent come from the session, never from the
client. Every command needs `email_thread` update and an agent of the user
(`engine.email_attempt.agent_not_found` otherwise); a transfer to a queue also
needs `cc_queue` read and, with RBAC, read access to that queue. `call_center`
checks the owner, the version and a repeat, so a repeat after a lost reply gets
the first result even when the sender is no longer the owner.

A reply carries the attempt (`attempt_id`, `thread_id`, `state`,
`attempt_version`, `projection_version`, `result`, `queue_id`,
`postponed_until`, `replayed`); a transfer carries `email` and `transferred_to`.
An error keeps the stable id of `call_center` and maps its gRPC code to HTTP:
`InvalidArgument`/`FailedPrecondition` 400, `Unauthenticated` 401,
`PermissionDenied` 403, `NotFound` 404, `Aborted`/`AlreadyExists` 409,
`ResourceExhausted` 429, `Canceled` 499, `Internal` 500, `Unavailable` 503,
`DeadlineExceeded` 504. A status without a stable id gets
`engine.email_attempt.<code>`. `email_command_timeout` (`EMAIL_COMMAND_TIMEOUT`,
10 seconds) bounds a call to `call_center`. This is the WebSocket contract; an
HTTP entry and the Gateway answer are not part of it.

## Email Agent API — EM-21

Substeps 5.1–5.4 are prepared on `feature/EM-21-email-distribution`.
Expand Down
10 changes: 10 additions & 0 deletions app/cc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ type MemberApi interface {
InterceptAttempt(ctx context.Context, domainId int64, attemptId int64, agentId int32) error
TransferAttempt(ctx context.Context, domainId int64, attemptId int64, agentId, queueId int32) error
ResumeAttempt(ctx context.Context, attemptId int64, domainId int64) error

// Email commands of an operator; errors are model.AppError mapped from the call_center status
// with its stable id and an HTTP code.
EmailAttemptTake(ctx context.Context, in *cc.EmailAttemptTakeRequest) (*cc.EmailAttemptResponse, model.AppError)
EmailAttemptPostpone(ctx context.Context, in *cc.EmailAttemptPostponeRequest) (*cc.EmailAttemptResponse, model.AppError)
EmailAttemptReturn(ctx context.Context, in *cc.EmailAttemptReturnRequest) (*cc.EmailAttemptResponse, model.AppError)
EmailAttemptComplete(ctx context.Context, in *cc.EmailAttemptCompleteRequest) (*cc.EmailAttemptResponse, model.AppError)
EmailAttemptResume(ctx context.Context, in *cc.ResumeAttemptRequest) (*cc.ResumeAttemptResponse, model.AppError)
EmailAttemptRenew(ctx context.Context, in *cc.AttemptRenewalResultRequest) (*cc.AttemptRenewalResultResponse, model.AppError)
EmailAttemptTransfer(ctx context.Context, in *cc.TransferRequest) (*cc.TransferResponse, model.AppError)
}

type CCManager interface {
Expand Down
76 changes: 76 additions & 0 deletions app/cc/email_error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package cc

import (
"context"
"errors"
"net/http"
"regexp"
"strings"
"unicode"

"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

"github.com/webitel/engine/model"
)

// emailStableId matches the stable ids call_center sends as the status message.
var emailStableId = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$`)

var emailHttpCodes = map[codes.Code]int{
Comment thread
dbahachuk marked this conversation as resolved.
Resolved
codes.InvalidArgument: http.StatusBadRequest,
codes.FailedPrecondition: http.StatusBadRequest,
codes.Unauthenticated: http.StatusUnauthorized,
codes.PermissionDenied: http.StatusForbidden,
codes.NotFound: http.StatusNotFound,
codes.Aborted: http.StatusConflict,
codes.AlreadyExists: http.StatusConflict,
codes.ResourceExhausted: http.StatusTooManyRequests,
codes.Canceled: 499,
codes.Internal: http.StatusInternalServerError,
codes.Unavailable: http.StatusServiceUnavailable,
codes.DeadlineExceeded: http.StatusGatewayTimeout,
}

// emailGrpcError keeps the stable id of call_center and the code of its status; free text gets
// the fallback id of the code, and the end of the caller's context keeps its own code.
func emailGrpcError(ctx context.Context, err error) model.AppError {
code := codes.Unknown
message := ""
if st, ok := status.FromError(err); ok {
code, message = st.Code(), st.Message()
}
switch {
case errors.Is(ctx.Err(), context.DeadlineExceeded):
code = codes.DeadlineExceeded
case errors.Is(ctx.Err(), context.Canceled):
code = codes.Canceled
}

httpCode, known := emailHttpCodes[code]
if !known {
code, httpCode = codes.Internal, http.StatusInternalServerError
}
id := message
if !emailStableId.MatchString(id) {
id = "engine.email_attempt." + snakeCase(code.String())
}

return model.NewCustomCodeError(id, message, httpCode)
}

// snakeCase turns a gRPC code name such as InvalidArgument into invalid_argument.
func snakeCase(name string) string {
var b strings.Builder
for i, r := range name {
if unicode.IsUpper(r) {
if i > 0 {
b.WriteByte('_')
}
r = unicode.ToLower(r)
}
b.WriteRune(r)
}

return b.String()
}
41 changes: 41 additions & 0 deletions app/cc/email_error_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package cc

import (
"context"
"errors"
"testing"

"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

func TestEmailGrpcError(t *testing.T) {
cases := []struct {
err error
id string
code int
}{
{status.Error(codes.ResourceExhausted, "cc.email_attempt.slot_exhausted"), "cc.email_attempt.slot_exhausted", 429},
{status.Error(codes.FailedPrecondition, "cc.email_attempt.agent_ineligible"), "cc.email_attempt.agent_ineligible", 400},
{status.Error(codes.Aborted, "cc.email_attempt.version_conflict"), "cc.email_attempt.version_conflict", 409},
{status.Error(codes.AlreadyExists, "cc.email_attempt.command_id_conflict"), "cc.email_attempt.command_id_conflict", 409},
{status.Error(codes.NotFound, "cc.email_attempt.not_found"), "cc.email_attempt.not_found", 404},
{status.Error(codes.Unavailable, "cc.email_attempt.lock_timeout"), "cc.email_attempt.lock_timeout", 503},
{status.Error(codes.InvalidArgument, "postponed_until must be positive Unix milliseconds"), "engine.email_attempt.invalid_argument", 400},
{status.Error(codes.DataLoss, "x"), "engine.email_attempt.internal", 500},
{errors.New("plain"), "engine.email_attempt.internal", 500},
}
for _, tc := range cases {
got := emailGrpcError(context.Background(), tc.err)
if got.GetId() != tc.id || got.GetStatusCode() != tc.code {
t.Errorf("%v: got %s %d, want %s %d", tc.err, got.GetId(), got.GetStatusCode(), tc.id, tc.code)
}
}

ctx, cancel := context.WithCancel(context.Background())
cancel()
if got := emailGrpcError(ctx, status.Error(codes.Canceled, "context canceled")); got.GetStatusCode() != 499 ||
got.GetId() != "engine.email_attempt.canceled" {
t.Errorf("canceled: %s %d", got.GetId(), got.GetStatusCode())
}
}
58 changes: 58 additions & 0 deletions app/cc/member.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package cc

import (
"context"

"github.com/webitel/engine/gen/cc"
"github.com/webitel/engine/model"
"github.com/webitel/engine/pkg/wbt"
)

Expand Down Expand Up @@ -134,3 +136,59 @@ func (api *memberApi) SaveFormFields(domainId, attemptId int64, fields map[strin

return err
}

func (api *memberApi) EmailAttemptTake(ctx context.Context, in *cc.EmailAttemptTakeRequest) (*cc.EmailAttemptResponse, model.AppError) {
out, err := api.Api.EmailAttemptTake(ctx, in)
if err != nil {
return nil, emailGrpcError(ctx, err)
}
return out, nil
}

func (api *memberApi) EmailAttemptPostpone(ctx context.Context, in *cc.EmailAttemptPostponeRequest) (*cc.EmailAttemptResponse, model.AppError) {
out, err := api.Api.EmailAttemptPostpone(ctx, in)
if err != nil {
return nil, emailGrpcError(ctx, err)
}
return out, nil
}

func (api *memberApi) EmailAttemptReturn(ctx context.Context, in *cc.EmailAttemptReturnRequest) (*cc.EmailAttemptResponse, model.AppError) {
out, err := api.Api.EmailAttemptReturn(ctx, in)
if err != nil {
return nil, emailGrpcError(ctx, err)
}
return out, nil
}

func (api *memberApi) EmailAttemptComplete(ctx context.Context, in *cc.EmailAttemptCompleteRequest) (*cc.EmailAttemptResponse, model.AppError) {
out, err := api.Api.EmailAttemptComplete(ctx, in)
if err != nil {
return nil, emailGrpcError(ctx, err)
}
return out, nil
}

func (api *memberApi) EmailAttemptResume(ctx context.Context, in *cc.ResumeAttemptRequest) (*cc.ResumeAttemptResponse, model.AppError) {
out, err := api.Api.ResumeAttempt(ctx, in)
if err != nil {
return nil, emailGrpcError(ctx, err)
}
return out, nil
}

func (api *memberApi) EmailAttemptRenew(ctx context.Context, in *cc.AttemptRenewalResultRequest) (*cc.AttemptRenewalResultResponse, model.AppError) {
out, err := api.Api.AttemptRenewalResult(ctx, in)
if err != nil {
return nil, emailGrpcError(ctx, err)
}
return out, nil
}

func (api *memberApi) EmailAttemptTransfer(ctx context.Context, in *cc.TransferRequest) (*cc.TransferResponse, model.AppError) {
out, err := api.Api.Transfer(ctx, in)
if err != nil {
return nil, emailGrpcError(ctx, err)
}
return out, nil
}
Loading
Loading