Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

Added sender IP warmup module for beta. Added access logs detection for fail2ban. Improved run_dev.go, add delay for every execution. Fixed GetServerIP() some call errors. Adjust background tasks delay time.

Jackbe4fdbf0e1f0
diff --git a/core/api/batch_mail/v1/batch_mail.go b/core/api/batch_mail/v1/batch_mail.go
index f7af1ed6..92d54a92 100644
--- a/core/api/batch_mail/v1/batch_mail.go
+++ b/core/api/batch_mail/v1/batch_mail.go
@@ -6,27 +6,28 @@ import (
)
type EmailTask struct {
- Id int `json:"id" dc:"task id"`
- TaskName string `json:"task_name" dc:"task name"`
- Addresser string `json:"addresser" dc:"addresser"`
- Subject string `json:"subject" dc:"subject"`
- FullName string `json:"full_name" dc:"full name"`
- RecipientCount int `json:"recipient_count" dc:"recipient count"`
- TaskProcess int `json:"task_process" dc:"task process"`
- Pause int `json:"pause" dc:"pause"`
- TemplateId int `json:"template_id" dc:"template id"`
- IsRecord int `json:"is_record" dc:"is record"`
- Unsubscribe int `json:"unsubscribe" dc:"unsubscribe"`
- Threads int `json:"threads" dc:"threads"`
- Etypes string `json:"etypes" dc:"etypes"`
- TrackOpen int `json:"track_open" dc:"track open"`
- TrackClick int `json:"track_click" dc:"track click"`
- StartTime int `json:"start_time" dc:"start time"`
- CreateTime int `json:"create_time" dc:"create time"`
- UpdateTime int `json:"update_time" dc:"update time"`
- Remark string `json:"remark" dc:"remark"`
- Active int `json:"active" dc:"status"`
- AddType int `json:"add_type" dc:"add type"`
+ Id int `json:"id" dc:"task id"`
+ TaskName string `json:"task_name" dc:"task name"`
+ Addresser string `json:"addresser" dc:"addresser"`
+ Subject string `json:"subject" dc:"subject"`
+ FullName string `json:"full_name" dc:"full name"`
+ RecipientCount int `json:"recipient_count" dc:"recipient count"`
+ TaskProcess int `json:"task_process" dc:"task process"`
+ Pause int `json:"pause" dc:"pause"`
+ TemplateId int `json:"template_id" dc:"template id"`
+ IsRecord int `json:"is_record" dc:"is record"`
+ Unsubscribe int `json:"unsubscribe" dc:"unsubscribe"`
+ Threads int `json:"threads" dc:"threads"`
+ Etypes string `json:"etypes" dc:"etypes"`
+ TrackOpen int `json:"track_open" dc:"track open"`
+ TrackClick int `json:"track_click" dc:"track click"`
+ StartTime int `json:"start_time" dc:"start time"`
+ CreateTime int `json:"create_time" dc:"create time"`
+ UpdateTime int `json:"update_time" dc:"update time"`
+ Remark string `json:"remark" dc:"remark"`
+ Active int `json:"active" dc:"status"`
+ AddType int `json:"add_type" dc:"add type"`
+ EstimatedTimeWithWarmup int64 `json:"estimated_time_with_warmup" dc:"estimated time for warmup (if applicable)"`
}
type GroupInfo struct {
@@ -118,6 +119,7 @@ type CreateTaskReq struct {
TrackOpen int `json:"track_open" v:"in:0,1" dc:"track open" default:"1"`
TrackClick int `json:"track_click" v:"in:0,1" dc:"track click" default:"1"`
StartTime int `json:"start_time" v:"required" dc:"start time"`
+ Warmup int `json:"warmup" v:"in:0,1" dc:"warmup" default:"0"`
Remark string `json:"remark" dc:"remark"`
}
diff --git a/core/internal/consts/mail_providers.go b/core/internal/consts/mail_providers.go
new file mode 100644
index 00000000..74051686
--- /dev/null
+++ b/core/internal/consts/mail_providers.go
@@ -0,0 +1,12 @@
+package consts
+
+const (
+ MailProviderGroupGmail = "google"
+ MailProviderGroupOutlook = "outlook"
+ MailProviderGroupYahoo = "yahoo"
+ MailProviderGroupApple = "apple"
+ MailProviderGroupProton = "proton"
+ MailProviderGroupZoho = "zoho"
+ MailProviderGroupAmazon = "amazon"
+ MailProviderGroupOther = "other"
+)
diff --git a/core/internal/controller/batch_mail/batch_mail_v1_create_task.go b/core/internal/controller/batch_mail/batch_mail_v1_create_task.go
index 7759af13..104bf4c7 100644
--- a/core/internal/controller/batch_mail/batch_mail_v1_create_task.go
+++ b/core/internal/controller/batch_mail/batch_mail_v1_create_task.go
@@ -28,7 +28,7 @@ func (c *ControllerV1) CreateTask(ctx context.Context, req *v1.CreateTaskReq) (r
addType := 0
// create task and import recipients
- _, err = batch_mail.CreateTaskWithRecipients(ctx, req, addType)
+ res.Data.Id, err = batch_mail.CreateTaskWithRecipients(ctx, req, addType)
if err != nil {
res.SetError(err)
return
diff --git a/core/internal/controller/dockerapi/dockerapi_v1_list_container.go b/core/internal/controller/dockerapi/dockerapi_v1_list_container.go
index 8ddaa127..bd6582b3 100644
--- a/core/internal/controller/dockerapi/dockerapi_v1_list_container.go
+++ b/core/internal/controller/dockerapi/dockerapi_v1_list_container.go
@@ -1,12 +1,10 @@
package dockerapi
import (
+ "billionmail-core/api/dockerapi/v1"
"billionmail-core/internal/service/public"
"context"
- "github.com/gogf/gf/v2/errors/gcode"
- "github.com/gogf/gf/v2/errors/gerror"
-
- "billionmail-core/api/dockerapi/v1"
+ "fmt"
)
func (c *ControllerV1) ListContainer(ctx context.Context, req *v1.ListContainerReq) (res *v1.ListContainerRes, err error) {
@@ -15,7 +13,7 @@ func (c *ControllerV1) ListContainer(ctx context.Context, req *v1.ListContainerR
res.Data, err = public.DockerApiFromCtx(ctx).ListContainers(ctx)
if err != nil {
- return nil, gerror.NewCode(gcode.CodeNotFound, "获取容器列表失败")
+ return nil, fmt.Errorf("failed to list containers: %w", err)
}
res.SetSuccess("Success")
diff --git a/core/internal/controller/mail_boxes/mail_boxes_v1_get_mailbox.go b/core/internal/controller/mail_boxes/mail_boxes_v1_get_mailbox.go
index 5e0b6ef5..172ff7b7 100644
--- a/core/internal/controller/mail_boxes/mail_boxes_v1_get_mailbox.go
+++ b/core/internal/controller/mail_boxes/mail_boxes_v1_get_mailbox.go
@@ -29,7 +29,7 @@ func (c *ControllerV1) GetMailbox(ctx context.Context, req *v1.GetMailboxReq) (r
return nil, err
}
- // 转换为带 MxRecord 的结构体
+ // transform mailbox list to include MX records
mailboxListWithMx := make([]v1.MailboxWithMxRecord, len(mailboxList))
for i, mailbox := range mailboxList {
mailboxListWithMx[i] = v1.MailboxWithMxRecord{
diff --git a/core/internal/model/entity/sender_ip_warmup_models.go b/core/internal/model/entity/sender_ip_warmup_models.go
new file mode 100644
index 00000000..eb972ee6
--- /dev/null
+++ b/core/internal/model/entity/sender_ip_warmup_models.go
@@ -0,0 +1,34 @@
+package entity
+
+// SenderIpWarmup bm_sender_ip_warmup
+type SenderIpWarmup struct {
+ Id int64 `json:"id"`
+ SenderIp string `json:"sender_ip"`
+ Period int `json:"period"`
+ Score int `json:"score"`
+ LastEvaluateTime int64 `json:"last_evaluate_time"`
+ Progress int `json:"progress"`
+ ReWarmups int `json:"re_warmups"`
+ BeginTime int64 `json:"begin_time"`
+ EndTime int64 `json:"end_time"`
+ CreateTime int64 `json:"create_time"`
+ UpdateTime int64 `json:"update_time"`
+}
+
+// SenderIpMailProvider bm_sender_ip_mail_provider
+type SenderIpMailProvider struct {
+ Id int64 `json:"id"`
+ SenderIp string `json:"sender_ip"`
+ MailProvider string `json:"mail_provider"`
+ Score int `json:"score"`
+ LastEvaluateTime int64 `json:"last_evaluate_time"`
+ CreateTime int64 `json:"create_time"`
+ UpdateTime int64 `json:"update_time"`
+}
+
+// CampaignWarmup bm_campaign_warmup
+type CampaignWarmup struct {
+ Id int64 `json:"id"`
+ TaskId int64 `json:"task_id"`
+ WarmupId int64 `json:"warmup_id"`
+}
diff --git a/core/internal/service/batch_mail/batch_mail.go b/core/internal/service/batch_mail/batch_mail.go
index 0462a5ee..f92f5a1c 100644
--- a/core/internal/service/batch_mail/batch_mail.go
+++ b/core/internal/service/batch_mail/batch_mail.go
@@ -4,6 +4,7 @@ import (
"billionmail-core/api/batch_mail/v1"
"billionmail-core/internal/model/entity"
"billionmail-core/internal/service/public"
+ "billionmail-core/internal/service/warmup"
"context"
"fmt"
"github.com/gogf/gf/v2/database/gdb"
@@ -14,6 +15,23 @@ import (
"time"
)
+type CreateTaskArgs struct {
+ Addresser string `json:"addresser"` // Sender email address
+ Subject string `json:"subject"` // Email subject
+ FullName string `json:"full_name"` // FullName of Sender
+ TemplateId int `json:"template_id"` // Template ID
+ IsRecord int `json:"is_record"` // Landing to outbox
+ Unsubscribe int `json:"unsubscribe"` // Enable unsubscribe link
+ Threads int `json:"threads"` // Number of threads to use
+ TrackOpen int `json:"track_open"` // Track email opens
+ TrackClick int `json:"track_click"` // Track email clicks
+ Etypes string `json:"etypes"` // Email types (e.g., group IDs)
+ Remark string `json:"remark"` // Task remark
+ StartTime int `json:"start_time"` // Scheduled start time
+ Warmup int `json:"warmup"` // Warmup campaign association
+ AddType int `json:"add_type"` // Add type (0: normal)
+}
+
// ============= task related operations =============
// GetTasksWithPage get task list (pagination)
@@ -49,6 +67,29 @@ func GetTasksWithPage(ctx context.Context, page, pageSize int, keyword string, s
Order("create_time DESC").
Scan(&list)
+ if err == nil {
+ serverIP, _ := public.GetServerIP()
+
+ if serverIP != "" {
+ // Filter associated warmup campaigns
+ ids := make([]int, 0)
+ m := make(map[int]*v1.EmailTask)
+ for _, v := range list {
+ // Calculate estimated time for warmup
+ ids = append(ids, v.Id)
+ v.EstimatedTimeWithWarmup = -1 // default -1 means no warmup
+ m[v.Id] = v
+ }
+
+ var vals []gdb.Value
+ vals, _ = g.DB().Ctx(ctx).Model("bm_campaign_warmup").WhereIn("task_id", ids).Array("task_id")
+
+ for _, val := range vals {
+ m[val.Int()].EstimatedTimeWithWarmup, _ = warmup.WarmupCampaign().CalculateEstimatedTime(ctx, val.Int64(), serverIP)
+ }
+ }
+ }
+
return total, list, err
}
@@ -64,39 +105,56 @@ func DeleteTask(ctx context.Context, id int) error {
}
// CreateTask create task
-func CreateTask(ctx context.Context, addresser, subject, fullName string, templateId int,
- isRecord, unsubscribe, threads, trackOpen, trackClick int, etypes string, remark string, startTime int, add_type int) (int, error) {
+func CreateTask(ctx context.Context, args CreateTaskArgs) (int, error) {
now := time.Now().Unix()
// generate task name
taskName := "task_" + gconv.String(now)
result, err := g.DB().Model("email_tasks").Insert(g.Map{
"task_name": taskName,
- "addresser": addresser,
- "subject": subject,
- "full_name": fullName,
+ "addresser": args.Addresser,
+ "subject": args.Subject,
+ "full_name": args.FullName,
"recipient_count": 0, // initial 0, update later
"task_process": 0,
"pause": 0,
- "template_id": templateId,
- "is_record": isRecord,
- "unsubscribe": unsubscribe,
- "threads": threads,
- "etypes": etypes,
- "track_open": trackOpen,
- "track_click": trackClick,
- "start_time": startTime,
+ "template_id": args.TemplateId,
+ "is_record": args.IsRecord,
+ "unsubscribe": args.Unsubscribe,
+ "threads": args.Threads,
+ "etypes": args.Etypes,
+ "track_open": args.TrackOpen,
+ "track_click": args.TrackClick,
+ "start_time": args.StartTime,
"create_time": now,
"update_time": now,
"active": 1,
- "remark": remark,
- "add_type": add_type,
+ "remark": args.Remark,
+ "add_type": args.AddType,
})
if err != nil {
+ g.Log().Warning(ctx, "Failed to create campaign:", err.Error())
return 0, err
}
id, err := result.LastInsertId()
+
+ if err == nil && args.Warmup == 1 {
+ // link to sender ip warmup
+ serverIP, _ := public.GetServerIP()
+
+ if serverIP != "" {
+ _, err = warmup.WarmupCampaign().AssociateCampaignWithWarmup(ctx, id, serverIP)
+
+ if err != nil {
+ g.Log().Warning(ctx, "Failed to associate campaign with warmup for task ID %d: %v", id, err)
+ err = nil
+ }
+ }
+ }
+
+ g.Log().Debugf(ctx, "CreateTask: Task ID %d is created.", id)
+
return int(id), err
}
@@ -227,22 +285,22 @@ func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addTyp
err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
etype := strings.Join(gconv.SliceStr(req.GroupIds), ",")
- taskId, err = CreateTask(
- ctx,
- req.Addresser,
- req.Subject,
- req.FullName,
- req.TemplateId,
- req.IsRecord,
- req.Unsubscribe,
- req.Threads,
- req.TrackOpen,
- req.TrackClick,
- etype,
- req.Remark,
- req.StartTime,
- addType,
- )
+ taskId, err = CreateTask(ctx, CreateTaskArgs{
+ Addresser: req.Addresser,
+ Subject: req.Subject,
+ FullName: req.FullName,
+ TemplateId: req.TemplateId,
+ IsRecord: req.IsRecord,
+ Unsubscribe: req.Unsubscribe,
+ Threads: req.Threads,
+ TrackOpen: req.TrackOpen,
+ TrackClick: req.TrackClick,
+ Etypes: etype,
+ Remark: req.Remark,
+ StartTime: req.StartTime,
+ Warmup: req.Warmup,
+ AddType: addType,
+ })
if err != nil {
return gerror.New(public.LangCtx(ctx, "Failed to create task {}", err.Error()))
}
diff --git a/core/internal/service/batch_mail/task_executor.go b/core/internal/service/batch_mail/task_executor.go
index 32bfe56c..2d39deb2 100644
--- a/core/internal/service/batch_mail/task_executor.go
+++ b/core/internal/service/batch_mail/task_executor.go
@@ -6,9 +6,11 @@ import (
"billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/maillog_stat"
"billionmail-core/internal/service/public"
+ "billionmail-core/internal/service/warmup"
"context"
"errors"
"fmt"
+ "github.com/gogf/gf/util/grand"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
@@ -170,6 +172,11 @@ type SendResult struct {
func NewTaskExecutor(ctx context.Context) *TaskExecutor {
taskCtx, cancel := context.WithCancel(ctx)
+ // Set server IP in context
+ serverIP, _ := public.GetServerIP()
+
+ taskCtx = context.WithValue(taskCtx, "serverIP", serverIP)
+
executor := &TaskExecutor{
ctx: taskCtx,
cancel: cancel,
@@ -238,6 +245,14 @@ func (e *TaskExecutor) ProcessTask(ctx context.Context) error {
e.isPaused.Store(true)
}
+ // check campaign warmup association
+ warmupAssociated := false
+ if warmupStat, _ := warmup.WarmupCampaign().GetWarmupStatusForCampaign(ctx, int64(taskId)); warmupStat != nil {
+ warmupAssociated = true
+ }
+
+ e.ctx = context.WithValue(e.ctx, "warmupAssociated", warmupAssociated)
+
// configure rate controller
e.configureRateController(task)
@@ -562,6 +577,7 @@ func (e *TaskExecutor) getNextRecipientBatch(ctx context.Context, taskId, lastId
err := g.DB().Model("recipient_info").
Where("task_id", taskId).
Where("is_sent", 0).
+ Where("sent_time = 0 OR sent_time < ?", time.Now().Unix()). // not sent yet
Where("id > ?", lastId).
Order("id ASC").
Limit(batchSize).
@@ -606,6 +622,8 @@ func (e *TaskExecutor) processRecipientBatch(ctx context.Context, task *entity.E
}
}
+ updates := make(map[int]int)
+
// submit send task for each recipient
for _, recipient := range recipients {
// check again if paused or canceled
@@ -637,6 +655,18 @@ func (e *TaskExecutor) processRecipientBatch(ctx context.Context, task *entity.E
}
+ // check if recipient is allowed to send with warmup
+ if warmupAssociated, ok := e.ctx.Value("warmupAssociated").(bool); ok && warmupAssociated {
+ if allow, waits, _ := warmup.RateLimiter().Allow(ctx, e.ctx.Value("serverIP").(string), public.GetMailProviderGroup(recipient.Recipient)); !allow {
+ if waits > 0 {
+ updates[recipient.Id] = waits * 2
+ }
+ // rate limit exceeded, skip this recipient
+ g.Log().Warningf(ctx, "Rate limit exceeded for recipient %d, wait for %d seconds after retry, skipping", recipient.Id, waits)
+ continue
+ }
+ }
+
// create recipient copy to avoid closure problem
recipientBak := recipient
@@ -657,6 +687,9 @@ func (e *TaskExecutor) processRecipientBatch(ctx context.Context, task *entity.E
// send email
result := e.sendEmail(ctx, task, recipientBak, personalized)
+ // use sendEmailMock (Don't use in production)
+ // result := e.sendEmailMock(ctx, task, recipientBak, personalized)
+
// record send
e.rateController.RecordSend()
@@ -687,6 +720,25 @@ func (e *TaskExecutor) processRecipientBatch(ctx context.Context, task *entity.E
}
}
+ if len(updates) > 0 {
+ curTime := int(time.Now().Unix())
+ data := make([]map[string]interface{}, 0, len(updates))
+ i := 0
+ for id, waits := range updates {
+ data = append(data, g.Map{
+ "id": id,
+ "task_id": 0,
+ "recipient": "",
+ "message_id": "",
+ "sent_time": curTime + (waits * ((i % 10) + 1)),
+ })
+ i++
+ }
+ _, _ = g.DB().Ctx(ctx).Model("recipient_info").Data(data).OnConflict("id").OnDuplicate(g.Map{
+ "sent_time": gdb.Raw("excluded.sent_time"),
+ }).Save()
+ }
+
// all tasks submitted, start result processing and channel closure goroutine
resultsDone := make(chan struct{})
@@ -1006,6 +1058,149 @@ func (e *TaskExecutor) sendEmail(ctx context.Context, task *entity.EmailTask, re
}
}
+// sendEmailMock simulates sending an email and records it in the database.
+func (e *TaskExecutor) sendEmailMock(ctx context.Context, task *entity.EmailTask, recipient *entity.RecipientInfo, content string) *SendResult {
+ // Check if the context is canceled
+ select {
+ case <-ctx.Done():
+ return &SendResult{
+ RecipientID: recipient.Id,
+ Success: false,
+ Error: ctx.Err(),
+ }
+ default:
+ // Continue execution
+ }
+
+ // Get the rendered content and subject
+ renderedContent, renderedSubject := e.personalizeEmail(ctx, content, task, recipient)
+
+ sender, err := mail_service.NewEmailSenderWithLocal(task.Addresser)
+ if err != nil {
+ g.Log().Error(ctx, "Failed to create email sender: %v", err)
+ return &SendResult{
+ RecipientID: recipient.Id,
+ Success: false,
+ Error: fmt.Errorf("failed to create email sender: %w", err),
+ }
+ }
+ defer sender.Close()
+ // Set message ID
+ messageID := sender.GenerateMessageID()
+
+ // Track email
+ baseURL := domains.GetBaseURLBySender(task.Addresser)
+ mail_tracker := maillog_stat.NewMailTracker(renderedContent, task.Id, messageID, recipient.Recipient, baseURL)
+ mail_tracker.TrackLinks()
+ mail_tracker.AppendTrackingPixel()
+ renderedContent = mail_tracker.GetHTML()
+
+ // Create email message with rendered subject
+ message := mail_service.NewMessage(renderedSubject, renderedContent)
+ message.SetMessageID(messageID)
+
+ // Set sender display name
+ if task.FullName != "" {
+ message.SetRealName(task.FullName)
+ }
+
+ // We will create a log entry and save it, instead of sending.
+ // This simulates a successful send.
+ postfixMessageID := strings.ToUpper("TEST_" + grand.S(11))
+ nowMillis := time.Now().UnixMilli()
+
+ // 1. Create MailSender record
+ senderRecord := &maillog_stat.MailSender{
+ MailRecord: maillog_stat.MailRecord{
+ PostfixMessageID: postfixMessageID,
+ LogTimeMillis: nowMillis,
+ },
+ Sender: task.Addresser,
+ Size: int64(len(renderedContent)),
+ }
+ _, err = g.DB().Model("mailstat_senders").InsertIgnore(senderRecord)
+ if err != nil {
+ g.Log().Warningf(ctx, "sendEmailMock: failed to insert mailstat_senders: %v", err)
+ }
+
+ // 2. Create MailMessageID record
+ messageIDRecord := &maillog_stat.MailMessageID{
+ MailRecord: maillog_stat.MailRecord{
+ PostfixMessageID: postfixMessageID,
+ LogTimeMillis: nowMillis,
+ },
+ MessageID: strings.Trim(messageID, "<>"),
+ }
+ _, err = g.DB().Model("mailstat_message_ids").InsertIgnore(messageIDRecord)
+ if err != nil {
+ g.Log().Warningf(ctx, "sendEmailMock: failed to insert mailstat_message_ids: %v", err)
+ }
+
+ // 3. Create MailSendRecord record
+ sendRecord := &maillog_stat.MailSendRecord{
+ MailRecord: maillog_stat.MailRecord{
+ PostfixMessageID: postfixMessageID,
+ LogTimeMillis: nowMillis,
+ },
+ Recipient: recipient.Recipient,
+ MailProvider: public.GetMailProviderGroup(recipient.Recipient),
+ Status: "sent",
+ Delay: 0.1, // Mock value
+ Delays: "0/0/0.1/0", // Mock value
+ Dsn: "2.0.0", // Mock value for successful send
+ Relay: "mock.relay.com", // Mock value
+ Description: "250 2.0.0 OK", // Mock value
+ }
+
+ _, err = g.DB().Model("mailstat_send_mails").Data(sendRecord).Insert()
+ if err != nil {
+ g.Log().Errorf(ctx, "sendEmailMock: failed to insert mailstat_send_mails: %v", err)
+ return &SendResult{
+ RecipientID: recipient.Id,
+ Success: false,
+ Error: fmt.Errorf("sendEmailMock: failed to save record: %w", err),
+ }
+ }
+
+ // 4. Simulate email open and click
+ // Simulate a 50% open rate
+ if grand.Intn(100) < 50 {
+ openTimeMillis := nowMillis + int64(grand.Intn(3600*1000)) // Simulate opening within 1 hour of sending
+ _, err = g.DB().Model("mailstat_opened").Insert(g.Map{
+ "campaign_id": task.Id,
+ "log_time_millis": openTimeMillis,
+ "recipient": recipient.Recipient,
+ "message_id": strings.Trim(messageID, "<>"),
+ "postfix_message_id": postfixMessageID,
+ })
+ if err != nil {
+ g.Log().Warningf(ctx, "sendEmailMock: failed to insert mailstat_opened: %v", err)
+ }
+
+ // If opened, simulate a 20% click rate
+ if grand.Intn(100) < 20 {
+ clickTimeMillis := openTimeMillis + int64(grand.Intn(600*1000)) // Simulate clicking within 10 minutes of opening
+ _, err = g.DB().Model("mailstat_clicked").Insert(g.Map{
+ "campaign_id": task.Id,
+ "log_time_millis": clickTimeMillis,
+ "recipient": recipient.Recipient,
+ "message_id": strings.Trim(messageID, "<>"),
+ "postfix_message_id": postfixMessageID,
+ })
+ if err != nil {
+ g.Log().Warningf(ctx, "sendEmailMock: failed to insert mailstat_clicked: %v", err)
+ }
+ }
+ }
+
+ return &SendResult{
+ RecipientID: recipient.Id,
+ MessageID: messageID,
+ Success: true,
+ Error: nil,
+ }
+}
+
// isTaskComplete check if task is complete
func (e *TaskExecutor) isTaskComplete(ctx context.Context, taskId int) (bool, error) {
type CountResult struct {
diff --git a/core/internal/service/database_initialization/sender_ip_warmup.go b/core/internal/service/database_initialization/sender_ip_warmup.go
new file mode 100644
index 00000000..f5d3933b
--- /dev/null
+++ b/core/internal/service/database_initialization/sender_ip_warmup.go
@@ -0,0 +1,56 @@
+package database_initialization
+
+import (
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+func init() {
+ registerHandler(func() {
+ row_sql_list := []string{
+ `CREATE TABLE IF NOT EXISTS bm_sender_ip_warmup (
+ id serial primary key,
+ sender_ip text not null default '',
+ period integer not null default 45, -- warmup period in days
+ score integer not null default 40, -- 0-100
+ last_evaluate_time integer not null default 0, -- last evaluate time
+ progress integer not null default 0, -- progress of warmup 0-100
+ re_warmups integer not null default 0, -- re-warmup times
+ begin_time integer not null DEFAULT EXTRACT(EPOCH FROM NOW()), -- begin of warmup
+ end_time integer not null default 0, -- end of warmup
+ create_time integer DEFAULT EXTRACT(EPOCH FROM NOW()),
+ update_time integer DEFAULT EXTRACT(EPOCH FROM NOW())
+ )`,
+
+ `CREATE INDEX IF NOT EXISTS idx_bm_sender_ip_warmup_sender_ip ON bm_sender_ip_warmup (sender_ip)`,
+
+ `CREATE TABLE IF NOT EXISTS bm_sender_ip_mail_provider (
+ id serial primary key,
+ sender_ip text not null default '',
+ mail_provider text not null default 'other', -- mail provider name
+ score integer not null default 40, -- 0-100
+ last_evaluate_time integer not null default 0, -- last evaluate time
+ create_time integer not null default EXTRACT(EPOCH FROM NOW()),
+ update_time integer not null default EXTRACT(EPOCH FROM NOW())
+ )`,
+
+ `CREATE INDEX IF NOT EXISTS idx_bm_sender_ip_mail_provider_sender_ip ON bm_sender_ip_mail_provider (sender_ip, mail_provider)`,
+
+ `CREATE TABLE IF NOT EXISTS bm_campaign_warmup (
+ id serial primary key,
+ task_id bigint not null default 0, -- campaign task ID
+ warmup_id bigint not null default 0 -- sender IP warmup ID
+ )`,
+
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_bm_campaign_warmup_task_id_warmup_id ON bm_campaign_warmup (task_id, warmup_id)`,
+ }
+
+ for _, sql := range row_sql_list {
+ _, err := g.DB().Exec(context.Background(), sql)
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to create table:", err)
+ return
+ }
+ }
+ })
+}
diff --git a/core/internal/service/fail2ban/access_log_detection.go b/core/internal/service/fail2ban/access_log_detection.go
new file mode 100644
index 00000000..957fbc51
--- /dev/null
+++ b/core/internal/service/fail2ban/access_log_detection.go
@@ -0,0 +1,63 @@
+package fail2ban
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfsnotify"
+ "os/exec"
+ "path/filepath"
+ "time"
+)
+
+type AccessLogDetection struct {
+ logPath string
+ ch chan struct{}
+}
+
+// NewAccessLogDetection creates a new AccessLogDetection instance with the specified log path.
+func NewAccessLogDetection() *AccessLogDetection {
+ return &AccessLogDetection{
+ logPath: public.AbsPath("logs"),
+ ch: make(chan struct{}, 2),
+ }
+}
+
+// Start begins the detection process for access logs.
+func (ald *AccessLogDetection) Start() {
+ _, err := gfsnotify.Add(ald.logPath, func(event *gfsnotify.Event) {
+
+ if event.IsCreate() {
+ if event.Path == filepath.Join(ald.logPath, time.Now().Format("access-20060102.log")) {
+ g.Log().Debug(context.Background(), "MallogEventHandler: access log file created, triggering detection")
+ ald.ch <- struct{}{}
+ }
+ }
+ })
+
+ if err != nil {
+ g.Log().Error(context.Background(), "AccessLogDetection: error adding file watcher", err)
+ return
+ }
+
+ g.Log().Debug(context.Background(), "AccessLogDetection: start event")
+
+ for {
+ select {
+ case <-ald.ch:
+ g.Log().Debug(context.Background(), "AccessLogDetection: timer triggered, restarting fail2ban service")
+
+ if !public.FileExists("/restart_fail2ban.sh") {
+ g.Log().Warning(context.Background(), "AccessLogDetection: /restart_fail2ban.sh script does not exist, skipping restart")
+ continue
+ }
+
+ cmd := exec.Command("bash", "/restart_fail2ban.sh")
+ if res, err := cmd.CombinedOutput(); err != nil {
+ g.Log().Warning(context.Background(), "AccessLogDetection: error restarting fail2ban service", err, string(res))
+ } else {
+ g.Log().Debug(context.Background(), "AccessLogDetection: restarting fail2ban service", string(res))
+ }
+ }
+ }
+}
diff --git a/core/internal/service/maillog_stat/maillog_stat.go b/core/internal/service/maillog_stat/maillog_stat.go
index fa47fb47..5ab5b8d5 100644
--- a/core/internal/service/maillog_stat/maillog_stat.go
+++ b/core/internal/service/maillog_stat/maillog_stat.go
@@ -268,34 +268,7 @@ func (ms *MaillogStat) initIgnoreMailAddresses() {
// getMailProvider gets mail service provider
func (ms *MaillogStat) getMailProvider(email string) string {
- hostname := strings.Split(email, "@")[1]
-
- switch {
- case strings.Contains(hostname, "gmail.com") || strings.Contains(hostname, "googlemail.com"):
- return "google"
- case strings.Contains(hostname, "outlook.com") || strings.Contains(hostname, "hotmail.com") ||
- strings.Contains(hostname, "live.com") || strings.Contains(hostname, "msn.com") ||
- strings.HasPrefix(hostname, "outlook."):
- return "outlook"
- case strings.Contains(hostname, "yahoo.com") || strings.Contains(hostname, "ymail.com") ||
- strings.Contains(hostname, "rocketmail.com") || strings.HasPrefix(hostname, "yahoo."):
- return "yahoo"
- case strings.Contains(hostname, "icloud.com") || strings.Contains(hostname, "me.com") ||
- strings.Contains(hostname, "mac.com") || strings.Contains(hostname, "apple.com"):
- return "apple"
- case strings.Contains(hostname, "protonmail.com") || strings.Contains(hostname, "proton.me") ||
- strings.Contains(hostname, "pm.me"):
- return "proton"
- case strings.Contains(hostname, "zoho.com") || strings.Contains(hostname, "zohomail.com") ||
- strings.Contains(hostname, "zohocorp.com") || strings.Contains(hostname, "zmail.com") ||
- strings.HasPrefix(hostname, "zoho."):
- return "zoho"
- case strings.Contains(hostname, "kindle.com") || strings.Contains(hostname, "amazon.com") ||
- strings.Contains(hostname, "awsapps.com"):
- return "amazon"
- default:
- return "other"
- }
+ return public.GetMailProviderGroup(email)
}
// parseLogTimeMillis parses log time (millisecond timestamp)
@@ -849,16 +822,12 @@ func (handler *MallogEventHandler) Start() {
for {
select {
case <-handler.timer.C:
- func() {
- defer func() {
- handler.isHanding = false
- }()
- g.Log().Debug(context.Background(), "MallogEventHandler: timer event")
- handler.maillogStat.startTime = GetLastMaillogTimeMillis()
- if err = handler.maillogStat.AnalysisAndSaveToDatabase(context.Background()); err != nil {
- g.Log().Error(context.Background(), "MallogEventHandler: error analysing maillog", err)
- }
- }()
+ handler.isHanding = false
+ g.Log().Debug(context.Background(), "MallogEventHandler: timer event")
+ handler.maillogStat.startTime = GetLastMaillogTimeMillis()
+ if err = handler.maillogStat.AnalysisAndSaveToDatabase(context.Background()); err != nil {
+ g.Log().Error(context.Background(), "MallogEventHandler: error analysing maillog", err)
+ }
}
}
}
diff --git a/core/internal/service/public/common.go b/core/internal/service/public/common.go
index 37e269b2..bcaba01a 100644
--- a/core/internal/service/public/common.go
+++ b/core/internal/service/public/common.go
@@ -2082,23 +2082,60 @@ func TimeCost() func() {
}
// GetServerIP retrieves the server's public IP address.
-func GetServerIP() (string, error) {
- resp, err := http.Get("https://ifconfig.me/ip")
- if err != nil {
- // Try alternative service
- resp, err = http.Get("https://www.aapanel.com/api/common/getClientIP")
+func GetServerIP(force ...bool) (string, error) {
+ if len(force) > 0 && force[0] {
+ // Force refresh public IP
+ _, _ = Cache.Remove(Ctx, "ServerIP")
+ }
+
+ cachedServerIP, err := Cache.Get(Ctx, "ServerIP")
+
+ if err == nil && !cachedServerIP.IsEmpty() {
+ // Return cached public IP
+ return cachedServerIP.String(), nil
+ }
+
+ serverIP := ""
+
+ for i := 0; i < 2; i++ {
+ var resp *http.Response
+ resp, err = http.Get("https://ifconfig.me/ip")
+ if err != nil || i > 0 {
+ // Try alternative service
+ resp, err = http.Get("https://www.aapanel.com/api/common/getClientIP")
+ if err != nil {
+ return "", err
+ }
+ }
+
+ var ip []byte
+ ip, err = io.ReadAll(resp.Body)
if err != nil {
return "", err
}
+
+ _ = resp.Body.Close()
+
+ serverIP = strings.TrimSpace(string(ip))
+
+ // check ip format
+ if !IsIpAddr(serverIP) {
+ continue
+ }
+
+ break
}
- defer resp.Body.Close()
- ip, err := io.ReadAll(resp.Body)
- if err != nil {
+ if serverIP == "" || !IsIpAddr(serverIP) {
return "", err
}
- return strings.TrimSpace(string(ip)), nil
+ // Cache the public IP address for 2 hours
+ if err = Cache.Set(Ctx, "ServerIP", serverIP, 2*time.Hour); err != nil {
+ g.Log().Warning(context.Background(), "Failed to cache server IP:", err)
+ }
+
+ return serverIP, nil
}
// GetLocalIP retrieves the server's local IP address.
diff --git a/core/internal/service/public/mail_stat_helpers.go b/core/internal/service/public/mail_stat_helpers.go
new file mode 100644
index 00000000..678939bb
--- /dev/null
+++ b/core/internal/service/public/mail_stat_helpers.go
@@ -0,0 +1,46 @@
+package public
+
+import (
+ "billionmail-core/internal/consts"
+ "strings"
+)
+
+// GetMailProviderGroup Gets the mail provider group based on the email or host.
+func GetMailProviderGroup(emailOrHost string) string {
+ hostname := strings.ToLower(strings.TrimSpace(emailOrHost))
+ if hostname == "" {
+ return consts.MailProviderGroupOther
+ }
+
+ if strings.Contains(hostname, "@") {
+ hostname = strings.SplitN(hostname, "@", 2)[1]
+ }
+
+ switch {
+ case strings.Contains(hostname, "gmail.com") || strings.Contains(hostname, "googlemail.com") || hostname == "google.com":
+ return consts.MailProviderGroupGmail
+ case strings.Contains(hostname, "outlook.com") || strings.Contains(hostname, "hotmail.com") ||
+ strings.Contains(hostname, "live.com") || strings.Contains(hostname, "msn.com") ||
+ strings.HasPrefix(hostname, "outlook."):
+ return consts.MailProviderGroupOutlook
+ case strings.Contains(hostname, "yahoo.com") || strings.Contains(hostname, "ymail.com") ||
+ strings.Contains(hostname, "rocketmail.com") || strings.HasPrefix(hostname, "yahoo.") ||
+ strings.Contains(hostname, "aol.com") || strings.Contains(hostname, "verizonmedia.com"):
+ return consts.MailProviderGroupYahoo
+ case strings.Contains(hostname, "icloud.com") || strings.Contains(hostname, "me.com") ||
+ strings.Contains(hostname, "mac.com") || strings.Contains(hostname, "apple.com"):
+ return consts.MailProviderGroupApple
+ case strings.Contains(hostname, "protonmail.com") || strings.Contains(hostname, "proton.me") ||
+ strings.Contains(hostname, "pm.me"):
+ return consts.MailProviderGroupProton
+ case strings.Contains(hostname, "zoho.com") || strings.Contains(hostname, "zohomail.com") ||
+ strings.Contains(hostname, "zohocorp.com") || strings.Contains(hostname, "zmail.com") ||
+ strings.HasPrefix(hostname, "zoho."):
+ return consts.MailProviderGroupZoho
+ case strings.Contains(hostname, "kindle.com") || strings.Contains(hostname, "amazon.com") ||
+ strings.Contains(hostname, "awsapps.com"):
+ return consts.MailProviderGroupAmazon
+ default:
+ return consts.MailProviderGroupOther
+ }
+}
diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.go
index f86e8429..f7cce0d0 100644
--- a/core/internal/service/timers/timers.go
+++ b/core/internal/service/timers/timers.go
@@ -4,22 +4,24 @@ import (
"billionmail-core/internal/service/batch_mail"
"billionmail-core/internal/service/collect"
"billionmail-core/internal/service/domains"
+ "billionmail-core/internal/service/fail2ban"
"billionmail-core/internal/service/mail_boxes"
"billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/maillog_stat"
"billionmail-core/internal/service/relay"
+ "billionmail-core/internal/service/warmup"
"context"
"github.com/gogf/gf/os/gtimer"
"github.com/gogf/gf/v2/frame/g"
"time"
)
-// Start 启动所有定时任务 (主入口函数)
+// Start Start initializes and starts all the necessary timers for the service.
func Start(ctx context.Context) (err error) {
g.Log().Debug(ctx, "Starting timers...")
// Normalize mailboxes to lowercase
- gtimer.AddOnce(1*time.Second, func() {
+ gtimer.AddOnce(500*time.Millisecond, func() {
g.Log().Debug(ctx, "Mailboxes normalization started")
err = mail_boxes.NormalizeMailboxes()
@@ -34,7 +36,7 @@ func Start(ctx context.Context) (err error) {
// Start DNS Records checking
// Ensure the DNS records are fresh on startup
- gtimer.AddOnce(5*time.Second, func() {
+ gtimer.AddOnce(500*time.Millisecond, func() {
// repair DKIM signing config
err = domains.RepairDKIMSigningConfig(ctx)
@@ -51,18 +53,18 @@ func Start(ctx context.Context) (err error) {
})
// Start maillog analysis
- gtimer.AddOnce(5*time.Second, func() {
+ gtimer.AddOnce(time.Second, func() {
me := maillog_stat.NewMallogEventHandler("", 1*time.Second)
me.Start()
})
// Start maillog aggregation
- gtimer.AddOnce(5*time.Second, func() {
+ gtimer.AddOnce(time.Second, func() {
maillog_stat.AggregateMaillogsTask(1 * time.Minute)
})
// Start console panel baseurl update timer
- gtimer.AddOnce(5*time.Second, func() {
+ gtimer.AddOnce(100*time.Millisecond, func() {
domains.UpdateBaseURL(ctx)
})
gtimer.Add(5*time.Minute, func() {
@@ -71,11 +73,6 @@ func Start(ctx context.Context) (err error) {
g.Log().Debug(ctx, "Start timers complete")
- gtimer.AddOnce(5*time.Second, func() {
- me := maillog_stat.NewMallogEventHandler("", 1*time.Second)
- me.Start()
- })
-
// Collect mail-sent total and mail-relay total
gtimer.AddOnce(5*time.Second, func() {
collect.Collect(ctx)
@@ -115,6 +112,15 @@ func Start(ctx context.Context) (err error) {
domains.AutoRenewSSL(ctx)
})
+ // Sender IP warmup and mail provider warmup
+ gtimer.Add(time.Hour, func() {
+ warmup.SenderIpWarmup().PeriodicTask(ctx)
+ warmup.SenderIpMailProvider().PeriodicTaskForProviders(ctx)
+ })
+
+ // fail2ban access logs detection
+ gtimer.Add(800*time.Millisecond, fail2ban.NewAccessLogDetection().Start)
+
g.Log().Debug(ctx, "All timers started successfully")
return nil
}
diff --git a/core/internal/service/warmup/rate_limiter.go b/core/internal/service/warmup/rate_limiter.go
new file mode 100644
index 00000000..38636ffd
--- /dev/null
+++ b/core/internal/service/warmup/rate_limiter.go
@@ -0,0 +1,206 @@
+package warmup
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/gogf/gf/v2/encoding/gjson"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+const (
+ // cacheTTLForLimits is the cache time for sending limits.
+ // We cache for a short period to avoid hitting the database on every request,
+ // while still allowing the system to pick up changes in scores and progress relatively quickly.
+ cacheTTLForLimits = 5 * time.Minute
+
+ // counterExpireInDay is the expiration time for the daily counter.
+ // Set to 2 days.
+ counterExpireInDay = 24 * time.Hour
+)
+
+// tokenBucketLua is an atomic script for the token bucket rate limiter.
+// It refills tokens based on elapsed time and consumes one if available.
+const tokenBucketLua = `
+-- KEYS[1] - The key for the token bucket hash
+-- ARGV[1] - The capacity of the bucket
+-- ARGV[2] - The refill rate (tokens per second)
+-- ARGV[3] - The current timestamp (seconds)
+-- ARGV[4] - The number of tokens to consume
+
+local key = KEYS[1]
+local capacity = tonumber(ARGV[1])
+local rate = tonumber(ARGV[2])
+local now = tonumber(ARGV[3])
+local requested = tonumber(ARGV[4])
+
+local bucket_info = redis.call('HGETALL', key)
+local last_tokens = capacity
+local last_refill_time = now
+
+if #bucket_info > 0 then
+ for i = 1, #bucket_info, 2 do
+ if bucket_info[i] == 'tokens' then
+ last_tokens = tonumber(bucket_info[i+1])
+ elseif bucket_info[i] == 'last_refill_time' then
+ last_refill_time = tonumber(bucket_info[i+1])
+ end
+ end
+end
+
+local time_passed = now - last_refill_time
+local new_tokens = time_passed * rate
+
+local current_tokens = math.min(capacity, last_tokens + new_tokens)
+
+if current_tokens >= requested then
+ current_tokens = current_tokens - requested
+ redis.call('HSET', key, 'tokens', current_tokens, 'last_refill_time', now)
+ -- Set an expiration for safety, e.g., twice the time it takes to fill an empty bucket
+ local expiry = 86400 -- Default 24 hours
+ if rate > 0 then
+ expiry = math.ceil(capacity / rate * 2)
+ end
+ redis.call('EXPIRE', key, expiry)
+ return 1
+else
+ -- Not enough tokens, don't update anything, just return 0
+ return 0
+end
+`
+
+// RateLimiterService provides rate limiting functionality for IP warmup.
+// It uses Redis for high-performance, distributed counting and caching.
+type RateLimiterService struct {
+ providerService *SenderIpMailProviderService
+}
+
+var insRateLimiterService = RateLimiterService{
+ providerService: SenderIpMailProvider(),
+}
+
+// RateLimiter returns the singleton instance of RateLimiterService.
+func RateLimiter() *RateLimiterService {
+ return &insRateLimiterService
+}
+
+// Allow checks if sending is allowed for the given sender IP and recipient.
+// It uses a hybrid approach:
+// 1. Daily limit: using Redis's variable window counter to ensure the absolute daily quota is not exceeded.
+// 2. Hourly limit: using the token bucket algorithm to smooth the sending rate and allow short-term bursts.
+func (s *RateLimiterService) Allow(ctx context.Context, senderIp string, recipientEmail string) (allow bool, waits int, err error) {
+ // Default wait time is 300 seconds (5 minutes), if not exceeded limit, it will be 0.
+ waits = 300
+
+ // 1. Determine the mail service provider group from the recipient email.
+ mailProviderGroup := public.GetMailProviderGroup(recipientEmail)
+
+ // 2. Get the sending limits (daily and hourly) for this IP and service provider group.
+ var dailyLimit, hourlyLimit int
+ dailyLimit, hourlyLimit, err = s.getCachedLimitsForProvider(ctx, senderIp, mailProviderGroup)
+ if err != nil {
+ g.Log().Errorf(ctx, "RateLimiter: Failed to get limits for IP %s, Group %s: %v", senderIp, mailProviderGroup, err)
+ return
+ }
+
+ if dailyLimit <= 0 || hourlyLimit <= 0 {
+ g.Log().Warningf(ctx, "RateLimiter: Sending denied for IP %s, Group %s because limits are zero (Daily: %d, Hourly: %d)", senderIp, mailProviderGroup, dailyLimit, hourlyLimit)
+ return
+ }
+
+ // 3. Check the daily limit (variable window counter)
+ var dailyCount int64
+ now := time.Now()
+ dailyKey := fmt.Sprintf("warmup:vw:d:%s:%s", senderIp, mailProviderGroup)
+
+ dailyCount, err = g.Redis().Incr(ctx, dailyKey)
+ if err != nil {
+ g.Log().Errorf(ctx, "RateLimiter: Redis INCR failed for daily key %s: %v", dailyKey, err)
+ return
+ }
+ if dailyCount == 1 {
+ // New daily counter, set expiration time
+ _, _ = g.Redis().Expire(ctx, dailyKey, int64(counterExpireInDay.Seconds()))
+ }
+
+ if dailyCount > int64(dailyLimit) {
+ g.Log().Debugf(ctx, "RateLimiter: Daily limit exceeded for IP %s, Group %s. Count: %d, Limit: %d", senderIp, mailProviderGroup, dailyCount, dailyLimit)
+ // Note: We don't roll back the counter here, because the exceeded requests have indeed occurred.
+ // Keeping the counter in an exceeded state prevents subsequent requests.
+ return
+ }
+
+ // 4. Check the hourly limit (token bucket)
+ hourlyKey := fmt.Sprintf("warmup:tb:h:%s:%s", senderIp, mailProviderGroup)
+ capacity := float64(hourlyLimit)
+ rate := capacity / 3600.0 // Tokens replenished per second
+
+ res, err := g.Redis().Eval(ctx, tokenBucketLua, 1, []string{hourlyKey}, []interface{}{
+ capacity,
+ rate,
+ now.Unix(),
+ 1, // Consume 1 token
+ })
+ if err != nil {
+ g.Log().Errorf(ctx, "RateLimiter: Token bucket script failed for IP %s, Group %s: %v", senderIp, mailProviderGroup, err)
+ // Script failed, status unknown, roll back daily count and deny
+ _, _ = g.Redis().Decr(ctx, dailyKey)
+ return
+ }
+
+ allowed := res.Int() == 1
+ if !allowed {
+ g.Log().Debugf(ctx, "RateLimiter: Hourly rate limit exceeded (token bucket) for IP %s, Group %s.", senderIp, mailProviderGroup)
+ // Not enough tokens in the bucket, roll back daily count
+ _, _ = g.Redis().Decr(ctx, dailyKey)
+ // Calculate the wait time/seconds for the next available token
+ waits = int(float64(1)/rate) + 1
+ return
+ }
+
+ // 5. If all checks pass, allow sending.
+ allow = true
+ waits = 0 // No wait time, request is allowed
+
+ g.Log().Debugf(ctx, "RateLimiter: Allow send for IP %s, Group %s. Daily count: %d/%d", senderIp, mailProviderGroup, dailyCount, dailyLimit)
+ return
+}
+
+// getCachedLimitsForProvider retrieves the sending limits, utilizing cache to avoid frequent database calls.
+func (s *RateLimiterService) getCachedLimitsForProvider(ctx context.Context, senderIp, mailProviderGroup string) (dailyLimit, hourlyLimit int, err error) {
+ cacheKey := fmt.Sprintf("warmup:limits:%s:%s", senderIp, mailProviderGroup)
+
+ // First, try to get it from the cache.
+ cachedVal, err := g.Redis().Get(ctx, cacheKey)
+ if err == nil && !cachedVal.IsNil() {
+ // Cache hit
+ limitsJson := gjson.New(cachedVal.String())
+ dailyLimit = limitsJson.Get("d").Int()
+ hourlyLimit = limitsJson.Get("h").Int()
+ g.Log().Debugf(ctx, "RateLimiter: Cache HIT for limits on IP %s, Group %s. Daily: %d, Hourly: %d", senderIp, mailProviderGroup, dailyLimit, hourlyLimit)
+ return
+ }
+
+ // Cache miss, fetch from service.
+ g.Log().Debugf(ctx, "RateLimiter: Cache MISS for limits on IP %s, Group %s. Fetching from service.", senderIp, mailProviderGroup)
+ dailyLimit, hourlyLimit, err = s.providerService.GetAdjustedSendingLimitsForProvider(ctx, senderIp, mailProviderGroup)
+ if err != nil {
+ return 0, 0, err
+ }
+
+ // Store in cache for future requests.
+ limits := g.Map{
+ "d": dailyLimit,
+ "h": hourlyLimit,
+ }
+ limitsStr, _ := gjson.New(limits).ToJsonString()
+ err = g.Redis().SetEX(ctx, cacheKey, limitsStr, int64(cacheTTLForLimits.Seconds()))
+ if err != nil {
+ // Log the error, but don't fail the operation, as we have already fetched the limits.
+ g.Log().Warningf(ctx, "RateLimiter: Failed to set cache for limits on IP %s, Group %s: %v", senderIp, mailProviderGroup, err)
+ }
+
+ return
+}
diff --git a/core/internal/service/warmup/sender_ip_mail_provider.go b/core/internal/service/warmup/sender_ip_mail_provider.go
new file mode 100644
index 00000000..3257fbf0
--- /dev/null
+++ b/core/internal/service/warmup/sender_ip_mail_provider.go
@@ -0,0 +1,380 @@
+package warmup
+
+import (
+ "billionmail-core/internal/consts"
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/database/gdb"
+ "math"
+ "strings"
+ "time"
+
+ "billionmail-core/internal/model/entity"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gtime"
+)
+
+const (
+ minScoreForSendingProvider = 25 // If the score is below this value, the (IP, provider group) combination will be suspended.
+ evaluationIntervalProvider = 2 * time.Hour // The evaluation frequency for provider group scores.
+ defaultEvaluationWindowProvider = 3 * 24 * time.Hour // The data window for provider group scoring, e.g., the last 3 days.
+ minSendVolumeForProviderScoring = 15 // The minimum sending volume required to calculate a full score for a provider group.
+ initialProviderScore = 40 // The initial score for an (IP, provider group).
+)
+
+// SenderIpMailProviderService struct.
+type SenderIpMailProviderService struct {
+ ipWarmupService *SenderIpWarmupService // Depends on the overall IP warmup service.
+ dailyUpstairsService *WarmupDailyUpstairsService // Depends on the daily sending volume service.
+}
+
+var insSenderIpMailProviderService = SenderIpMailProviderService{
+ ipWarmupService: SenderIpWarmup(), // Get an instance of SenderIpWarmupService.
+ dailyUpstairsService: WarmupDailyUpstairs(), // Get an instance of WarmupDailyUpstairsService.
+}
+
+// SenderIpMailProvider returns the service instance.
+func SenderIpMailProvider() *SenderIpMailProviderService {
+ return &insSenderIpMailProviderService
+}
+
+// getMailProviderGroup returns the corresponding service provider group name based on the mail_provider field in the database (usually a domain name).
+func (s *SenderIpMailProviderService) getMailProviderGroup(dbMailProvider string) string {
+ return public.GetMailProviderGroup(dbMailProvider)
+}
+
+// InitializeOrGetProviderStatus initializes or retrieves the scoring status for a specified IP and mail provider group.
+func (s *SenderIpMailProviderService) InitializeOrGetProviderStatus(ctx context.Context, senderIp string, mailProviderGroup string) (record *entity.SenderIpMailProvider, err error) {
+ err = g.DB().Model("bm_sender_ip_mail_provider").Ctx(ctx).
+ Where("sender_ip", senderIp).
+ Where("mail_provider", mailProviderGroup).
+ Scan(&record)
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to query SenderIpMailProvider for IP %s, Group %s: %v", senderIp, mailProviderGroup, err)
+ return
+ }
+
+ if record == nil {
+ now := gtime.Now()
+ record = &entity.SenderIpMailProvider{
+ SenderIp: senderIp,
+ MailProvider: mailProviderGroup,
+ Score: initialProviderScore,
+ LastEvaluateTime: now.Timestamp(), // When first created, the evaluation time is set to the current time to avoid immediate re-evaluation.
+ CreateTime: now.Timestamp(),
+ UpdateTime: now.Timestamp(),
+ }
+ var insertId int64
+ insertId, err = g.DB().Model("bm_sender_ip_mail_provider").Ctx(ctx).Data(record).OmitEmptyData().InsertAndGetId()
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to insert SenderIpMailProvider for IP %s, Group %s: %v", senderIp, mailProviderGroup, err)
+ return
+ }
+ record.Id = insertId
+ g.Log().Infof(ctx, "Initialized SenderIpMailProvider status for IP %s, Group %s", senderIp, mailProviderGroup)
+ }
+ return
+}
+
+// EvaluateScoreForProvider evaluates and updates the score for a specified IP and mail provider group.
+func (s *SenderIpMailProviderService) EvaluateScoreForProvider(ctx context.Context, senderIp string, mailProviderGroup string) (score int, err error) {
+ providerStatus, err := s.InitializeOrGetProviderStatus(ctx, senderIp, mailProviderGroup)
+ if err != nil {
+ return 0, err
+ }
+
+ // Use the getSenderIdentitiesForIp method from SenderIpWarmupService.
+ // Note: This method needs to be exported from SenderIpWarmupService or provided as a public utility function.
+ senderIdentities, err := s.ipWarmupService.getSenderIdentitiesForIp(ctx, senderIp) // Assume it can be called
+ if err != nil {
+ g.Log().Errorf(ctx, "EvaluateScoreForProvider: Failed to get sender identities for IP %s: %v", senderIp, err)
+ // Update the evaluation time to avoid getting stuck.
+ _, _ = g.DB().Model("bm_sender_ip_mail_provider").Ctx(ctx).
+ Where("id", providerStatus.Id).
+ Data(g.Map{"last_evaluate_time": gtime.Now().Timestamp()}).Update()
+ return providerStatus.Score, err
+ }
+
+ evaluationWindowStartMillis := gtime.New(providerStatus.LastEvaluateTime).Add(-defaultEvaluationWindowProvider).TimestampMilli()
+ // If it's the first evaluation (LastEvaluateTime == CreateTime), calculate from CreateTime, or from a reasonable earliest time.
+ if providerStatus.LastEvaluateTime == providerStatus.CreateTime {
+ evaluationWindowStartMillis = gtime.New(providerStatus.CreateTime).Add(-defaultEvaluationWindowProvider).TimestampMilli()
+ // Prevent the window from being too early, ensure it starts at least from the creation time.
+ if evaluationWindowStartMillis < gtime.New(providerStatus.CreateTime).Add(-2*defaultEvaluationWindowProvider).TimestampMilli() {
+ evaluationWindowStartMillis = gtime.New(providerStatus.CreateTime).TimestampMilli()
+ }
+ }
+ if gtime.Now().TimestampMilli()-evaluationWindowStartMillis > defaultEvaluationWindowProvider.Milliseconds()*2 { // Prevent the window from being too large.
+ evaluationWindowStartMillis = gtime.Now().Add(-defaultEvaluationWindowProvider).TimestampMilli()
+ }
+
+ relevantPmids := make([]string, 0)
+ if len(senderIdentities) > 0 {
+ var vals []gdb.Value
+ // Assume here that senderIdentities are domains or patterns that can be used for LIKE matching.
+ likes := make([]string, len(senderIdentities))
+ params := make([]interface{}, len(senderIdentities)+1)
+ for i, identity := range senderIdentities {
+ // Adjust according to the format of identity. If it's a full email address, use sender = ?; if it's a domain, use sender LIKE '%@domain'.
+ if strings.Contains(identity, "@") {
+ likes[i] = "s.sender = ?"
+ params[i] = identity
+ } else {
+ likes[i] = "s.sender LIKE ?"
+ params[i] = "%@" + identity
+ }
+ }
+ params[len(senderIdentities)] = evaluationWindowStartMillis
+ vals, err = g.DB().Ctx(ctx).Model("mailstat_senders s").
+ InnerJoin("mailstat_send_mails sm", "s.postfix_message_id=sm.postfix_message_id").
+ Fields("DISTINCT s.postfix_message_id").
+ Where(strings.Join(likes, " OR "), params[:len(senderIdentities)]...).
+ Where("s.log_time_millis >= ?", evaluationWindowStartMillis).
+ Where("sm.mail_provider", mailProviderGroup).
+ Array()
+ if err != nil {
+ g.Log().Errorf(ctx, "EvaluateScoreForProvider: Failed to get postfix_message_ids for IP %s (identities: %v): %v", senderIp, senderIdentities, err)
+ }
+ for _, v := range vals {
+ if pmid := v.String(); pmid != "" {
+ relevantPmids = append(relevantPmids, pmid)
+ }
+ }
+ }
+
+ totalSent := 0
+ successfulSends := 0
+ hardBounces := 0
+ softBounces := 0
+ deferredSends := 0
+ openedCount := 0
+ clickedCount := 0
+ // complaintCount := 0 // TODO: Complaint rate
+
+ if len(relevantPmids) > 0 {
+ // 1. Get sending statistics (mailstat_send_mails)
+ type SendMailStatItemWithProvider struct {
+ Status string `json:"status"`
+ Dsn string `json:"dsn"`
+ Count int `json:"count"`
+ }
+ var sendMailStats []SendMailStatItemWithProvider
+ err = g.DB().Ctx(ctx).Model("mailstat_send_mails").
+ Fields("status", "dsn", "COUNT(*) as count").
+ WhereIn("postfix_message_id", relevantPmids).
+ Where("log_time_millis >= ?", evaluationWindowStartMillis).
+ Group("status", "dsn").
+ Scan(&sendMailStats)
+
+ if err != nil {
+ g.Log().Errorf(ctx, "EvaluateScoreForProvider: Failed to get send mail stats for IP %s, Group %s: %v", senderIp, mailProviderGroup, err)
+ } else {
+ for _, stat := range sendMailStats {
+ totalSent += stat.Count
+ switch strings.ToLower(stat.Status) {
+ case "sent":
+ successfulSends += stat.Count
+ case "bounced":
+ if len(stat.Dsn) > 0 {
+ switch stat.Dsn[0] {
+ case '5':
+ hardBounces += stat.Count
+ case '4':
+ softBounces += stat.Count
+ default:
+ softBounces += stat.Count
+ }
+ } else {
+ softBounces += stat.Count
+ }
+ case "deferred":
+ deferredSends += stat.Count
+ }
+ }
+ }
+
+ // 2. Get open and click statistics (needs to be grouped by recipient domain)
+ // Get openedCount and clickedCount (requires user participation data)
+ openedCount, _ = g.DB().Model("mailstat_opened").
+ Ctx(ctx).
+ WhereIn("postfix_message_id", relevantPmids).
+ Where("log_time_millis >= ?", evaluationWindowStartMillis).
+ Fields("DISTINCT postfix_message_id").
+ Count()
+ clickedCount, _ = g.DB().Model("mailstat_clicked").
+ Ctx(ctx).
+ WhereIn("postfix_message_id", relevantPmids).
+ Where("log_time_millis >= ?", evaluationWindowStartMillis).
+ Fields("DISTINCT postfix_message_id").
+ Count()
+ }
+
+ currentScore := float64(providerStatus.Score)
+ if totalSent == 0 && len(relevantPmids) == 0 && len(senderIdentities) == 0 && mailProviderGroup == consts.MailProviderGroupOther {
+ // For the "Other" category, if there are no specific identities or traffic, the score may remain unchanged or decrease slowly.
+ // currentScore -= 0.1
+ g.Log().Infof(ctx, "EvaluateIpScore: IP %s Group %s has no configured sender identities. Score remains %d.", senderIp, providerStatus.MailProvider, providerStatus.Score)
+ } else if totalSent < minSendVolumeForProviderScoring && totalSent > 0 {
+ switch {
+ case hardBounces > 0:
+ currentScore -= 20 // Hard bounce penalty
+ case softBounces > 0:
+ currentScore -= 10 // Soft bounce penalty
+ case successfulSends > 0:
+ currentScore += 3 // Reward for successful sending
+ default:
+ currentScore -= 8 // Penalty for no sending records
+ }
+ } else if totalSent >= minSendVolumeForProviderScoring {
+ successRate := float64(successfulSends) / float64(totalSent)
+ hardBounceRate := float64(hardBounces) / float64(totalSent)
+ softBounceRate := float64(softBounces) / float64(totalSent)
+ deferredRate := float64(deferredSends) / float64(totalSent) // deferredSends comes from overall statistics and needs adjustment
+
+ currentScore += (successRate - 0.85) * 40 // 85% success rate benchmark, affects 40 points
+ currentScore -= hardBounceRate * 150 // Higher penalty coefficient for hard bounces
+ currentScore -= softBounceRate * 70
+ currentScore -= deferredRate * 25 // Latency also affects provider score
+
+ if successfulSends > 0 {
+ openRate := float64(openedCount) / float64(successfulSends)
+ currentScore += openRate * 25 // 12% open rate benchmark
+ if openedCount > 0 {
+ clickRate := float64(clickedCount) / float64(openedCount)
+ currentScore += clickRate * 20 // 2.5% click rate benchmark
+ }
+ }
+ // TODO: complaintRate (complaintCount / successfulSends)
+ } else { // totalSent == 0 for this provider group
+ var warmupStatus *entity.SenderIpWarmup
+ warmupStatus, err = s.ipWarmupService.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if err == nil && warmupStatus != nil && warmupStatus.Progress > 65 { // Warmup progress exceeds 65%
+ switch {
+ case providerStatus.Score < 50:
+ currentScore -= 1.5 // When the score is below 50, the penalty is heavier
+ case providerStatus.Score > 70:
+ currentScore -= 0.5 // When the score is above 70, the penalty is lighter
+ }
+ }
+ }
+
+ finalScore := int(math.Max(0, math.Min(100, currentScore)))
+ _, err = g.DB().Model("bm_sender_ip_mail_provider").Ctx(ctx).
+ Where("id", providerStatus.Id).
+ Data(g.Map{
+ "score": finalScore,
+ "last_evaluate_time": gtime.Now().Timestamp(),
+ "update_time": gtime.Now().Timestamp(),
+ }).Update()
+
+ if err != nil {
+ g.Log().Errorf(ctx, "EvaluateScoreForProvider: Failed to update score for IP %s, Group %s: %v", senderIp, mailProviderGroup, err)
+ return providerStatus.Score, err
+ }
+ g.Log().Debugf(ctx, "Evaluated score for IP %s, Group %s: %d (Sent: %d, Success: %d, HB: %d, SB: %d, Open: %d, Click: %d)", senderIp, mailProviderGroup, finalScore, totalSent, successfulSends, hardBounces, softBounces, openedCount, clickedCount)
+ return finalScore, nil
+}
+
+// GetSendingRateFactorForProvider calculates the sending rate health factor based on the score of a specific provider group.
+// This factor (0.0 - 1.0) reflects the reputation health of the IP with that provider.
+func (s *SenderIpMailProviderService) GetSendingRateFactorForProvider(ctx context.Context, senderIp string, mailProviderGroup string) (rateFactor float64, err error) {
+ providerStatus, err := s.InitializeOrGetProviderStatus(ctx, senderIp, mailProviderGroup)
+ if err != nil {
+ g.Log().Warningf(ctx, "GetSendingRateFactorForProvider: IP %s, Group %s status unknown: %v. Returning low factor.", senderIp, mailProviderGroup, err)
+ return 0.05, err // Unable to get provider group status, return a very low factor.
+ }
+
+ minScore := float64(minScoreForSendingProvider)
+ score := float64(providerStatus.Score)
+
+ if score < minScore {
+ g.Log().Debugf(ctx, "GetSendingRateFactorForProvider: IP %s, Group %s PAUSED (Score %d < %d)", senderIp, mailProviderGroup, providerStatus.Score, int(minScore))
+ return 0.0, nil // Score is too low, pause sending to this provider group.
+ }
+
+ // Linearly map the score from minScore-100 to a rate factor of 0.1-1.0.
+ // Even at the lowest allowed score, a 10% rate is maintained.
+ factor := 0.1 + (score-minScore)/(100.0-minScore)*0.9
+ rateFactor = math.Max(0, math.Min(1, factor)) // Ensure the factor is between 0 and 1.
+
+ g.Log().Debugf(ctx, "GetSendingRateFactorForProvider: IP %s, Group %s (Prov Score %d) -> Rate Factor: %.3f", senderIp, mailProviderGroup, providerStatus.Score, rateFactor)
+ return rateFactor, nil
+}
+
+// GetAdjustedSendingLimitsForProvider calculates the final sending limits for a specific IP and mail provider group.
+// It combines the daily base sending volume of the IP warmup with the reputation health factor of the specific provider.
+func (s *SenderIpMailProviderService) GetAdjustedSendingLimitsForProvider(ctx context.Context, senderIp string, mailProviderGroup string) (adjustedDailyLimit int, adjustedHourlyLimit int, err error) {
+ // 1. Get the base sending volume from the daily increment service.
+ baseDailyLimit, baseHourlyLimit, err := s.dailyUpstairsService.GetSendingLimits(ctx, senderIp)
+ if err != nil {
+ g.Log().Errorf(ctx, "GetAdjustedSendingLimitsForProvider: Failed to get base limits for IP %s: %v", senderIp, err)
+ return 0, 0, err
+ }
+
+ // 2. Get the reputation health factor for the specific mail provider group.
+ rateFactor, err := s.GetSendingRateFactorForProvider(ctx, senderIp, mailProviderGroup)
+ if err != nil {
+ g.Log().Errorf(ctx, "GetAdjustedSendingLimitsForProvider: Failed to get rate factor for IP %s, Group %s: %v", senderIp, mailProviderGroup, err)
+ // Even if fetching the factor fails, a very low value based on the base volume can be returned instead of completely blocking.
+ return int(float64(baseDailyLimit) * 0.05), int(float64(baseHourlyLimit) * 0.05), err
+ }
+
+ // 3. Apply the factor to the base volume to calculate the final adjusted limits.
+ // Use Ceil to ensure that even a small factor multiplied by the base volume results in at least 1 (if the result is greater than 0).
+ adjustedDailyLimit = int(math.Ceil(float64(baseDailyLimit) * rateFactor))
+ adjustedHourlyLimit = int(math.Ceil(float64(baseHourlyLimit) * rateFactor))
+
+ g.Log().Infof(ctx, "Adjusted Limits for IP %s, Group %s: Daily=%d, Hourly=%d (Base: D=%d, H=%d; Factor: %.2f)", senderIp, mailProviderGroup, adjustedDailyLimit, adjustedHourlyLimit, baseDailyLimit, baseHourlyLimit, rateFactor)
+
+ return adjustedDailyLimit, adjustedHourlyLimit, nil
+}
+
+// PeriodicTaskForProviders is a background periodic task that updates the scores of all IPs for each provider group.
+func (s *SenderIpMailProviderService) PeriodicTaskForProviders(ctx context.Context) {
+ g.Log().Info(ctx, "Sender IP Mail Provider Periodic Task: Starting...")
+ var allIpWarmupRecords []*entity.SenderIpWarmup
+ // Get all IPs that are warming up or have been warmed up.
+ err := g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Scan(&allIpWarmupRecords)
+ if err != nil {
+ g.Log().Errorf(ctx, "PeriodicTaskForProviders: Failed to get all IPs from bm_sender_ip_warmup: %v", err)
+ return
+ }
+ if len(allIpWarmupRecords) == 0 {
+ g.Log().Info(ctx, "PeriodicTaskForProviders: No sender IPs found in warmup table.")
+ return
+ }
+
+ providerGroups := []string{
+ consts.MailProviderGroupGmail,
+ consts.MailProviderGroupYahoo,
+ consts.MailProviderGroupOutlook,
+ consts.MailProviderGroupApple,
+ consts.MailProviderGroupProton,
+ consts.MailProviderGroupZoho,
+ consts.MailProviderGroupAmazon,
+ consts.MailProviderGroupOther,
+ }
+
+ for _, ipRecord := range allIpWarmupRecords {
+ senderIp := ipRecord.SenderIp
+ for _, groupName := range providerGroups {
+ providerStatus, err := s.InitializeOrGetProviderStatus(ctx, senderIp, groupName)
+ if err != nil {
+ // The error has been logged in InitializeOrGetProviderStatus, continue to the next one here.
+ continue
+ }
+
+ // Check if it's time for evaluation.
+ if gtime.Now().After(gtime.New(providerStatus.LastEvaluateTime).Add(evaluationIntervalProvider)) {
+ g.Log().Debugf(ctx, "PeriodicTaskForProviders: Evaluating score for IP %s, Group %s", senderIp, groupName)
+ _, evalErr := s.EvaluateScoreForProvider(ctx, senderIp, groupName)
+ if evalErr != nil {
+ g.Log().Errorf(ctx, "PeriodicTaskForProviders: Failed to evaluate score for IP %s, Group %s: %v", senderIp, groupName, evalErr)
+ }
+ } else {
+ g.Log().Debugf(ctx, "PeriodicTaskForProviders: Skipping score evaluation for IP %s, Group %s (Last eval: %s)", senderIp, groupName, gtime.New(providerStatus.LastEvaluateTime))
+ }
+ }
+ }
+ g.Log().Info(ctx, "Sender IP Mail Provider Periodic Task: Finished.")
+}
diff --git a/core/internal/service/warmup/sender_ip_warmup.go b/core/internal/service/warmup/sender_ip_warmup.go
new file mode 100644
index 00000000..0f7b138b
--- /dev/null
+++ b/core/internal/service/warmup/sender_ip_warmup.go
@@ -0,0 +1,517 @@
+package warmup
+
+import (
+ "context"
+ "fmt"
+ "github.com/gogf/gf/v2/database/gdb"
+ "math"
+ "strings"
+ "time"
+
+ "billionmail-core/internal/model/entity"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gtime"
+ "github.com/gogf/gf/v2/util/gconv"
+)
+
+const (
+ defaultWarmupPeriodDays = 45
+ minScoreForSending = 20 // IPs with a score below this will have their sending paused or sent at a very low rate
+ evaluationInterval = 1 * time.Hour // The frequency of evaluating scores and progress (example)
+ reWarmupCheckInterval = 24 * time.Hour // The frequency of checking if re-warmup is needed (example)
+ defaultEvaluationWindow = 7 * 24 * time.Hour // The time window for evaluation data, e.g., the last 7 days
+ minSendVolumeForFullScoring = 20 // The minimum sending volume required for a full score calculation
+)
+
+type SenderIpWarmupService struct{}
+
+var insSenderIpWarmupService = SenderIpWarmupService{}
+
+func SenderIpWarmup() *SenderIpWarmupService {
+ return &insSenderIpWarmupService
+}
+
+// getSenderIdentitiesForIp gets the associated sender identities (e.g., email addresses or domains) for a given sender IP.
+func (s *SenderIpWarmupService) getSenderIdentitiesForIp(ctx context.Context, senderIp string) (domains []string, err error) {
+ // Get the sender identities associated with this IP.
+ var vals []gdb.Value
+ vals, err = g.DB().Ctx(ctx).Model("domain").Where("active = 1").Fields("domain").Array("domain")
+
+ if err != nil {
+ err = fmt.Errorf("getSenderIdentitiesForIp err: %v", err)
+ return
+ }
+
+ for _, v := range vals {
+ domains = append(domains, v.String())
+ }
+
+ g.Log().Debug(ctx, "Domains for IP", senderIp, domains)
+
+ return // return empty, let the scoring logic handle the absence of data
+}
+
+// InitializeOrGetWarmupStatus initializes or retrieves the warmup status of an IP.
+func (s *SenderIpWarmupService) InitializeOrGetWarmupStatus(ctx context.Context, senderIp string) (record *entity.SenderIpWarmup, err error) {
+ err = g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Where("sender_ip", senderIp).Scan(&record)
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to query SenderIpWarmup for IP %s: %v", senderIp, err)
+ return
+ }
+ if record == nil {
+ now := gtime.Now()
+ record = &entity.SenderIpWarmup{
+ SenderIp: senderIp,
+ Period: defaultWarmupPeriodDays,
+ Score: 40, // Initial score for a new IP (e.g., 40)
+ LastEvaluateTime: now.Timestamp(),
+ Progress: 0,
+ ReWarmups: 0,
+ BeginTime: now.Timestamp(), // Warmup start time
+ EndTime: now.AddDate(0, 0, defaultWarmupPeriodDays).Timestamp(),
+ CreateTime: now.Timestamp(),
+ UpdateTime: now.Timestamp(),
+ }
+ record.Id, err = g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Data(record).OmitEmptyData().InsertAndGetId()
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to insert SenderIpWarmup for IP %s: %v", senderIp, err)
+ return
+ }
+ g.Log().Infof(ctx, "Initialized warmup status for new IP: %s", senderIp)
+ }
+ return
+}
+
+// EvaluateIpScore evaluates and updates the score of an IP.
+func (s *SenderIpWarmupService) EvaluateIpScore(ctx context.Context, senderIp string) (score int, err error) {
+ var warmupStatus *entity.SenderIpWarmup
+ warmupStatus, err = s.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if err != nil {
+ return
+ }
+
+ evaluationWindowStartMillis := gtime.New(warmupStatus.LastEvaluateTime).Add(-defaultEvaluationWindow).TimestampMilli()
+ if warmupStatus.CreateTime == warmupStatus.LastEvaluateTime || gtime.New(warmupStatus.LastEvaluateTime).Before(gtime.New(warmupStatus.BeginTime)) { // After the first evaluation or a reset
+ evaluationWindowStartMillis = gtime.New(warmupStatus.BeginTime).TimestampMilli()
+ }
+ if gtime.Now().TimestampMilli()-evaluationWindowStartMillis > defaultEvaluationWindow.Milliseconds()*2 { // Prevent the window from being too large
+ evaluationWindowStartMillis = gtime.Now().Add(-defaultEvaluationWindow).TimestampMilli()
+ }
+
+ senderIdentities, err := s.getSenderIdentitiesForIp(ctx, senderIp)
+ if err != nil {
+ g.Log().Errorf(ctx, "EvaluateIpScore: Failed to get sender identities for IP %s: %v", senderIp, err)
+ // Even if identities cannot be fetched, try to update the evaluation time to avoid getting stuck
+ _, _ = g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Data(g.Map{
+ "last_evaluate_time": gtime.Now().Timestamp(),
+ }).Update()
+ return warmupStatus.Score, err
+ }
+
+ relevantPmids := make([]string, 0)
+ if len(senderIdentities) > 0 {
+ var vals []gdb.Value
+ // Note: This query assumes that mailstat_senders.sender stores email addresses.
+ // If it's a domain, the query condition needs to be adjusted to LIKE '%@domain.com'.
+ likes := make([]string, len(senderIdentities))
+ params := make([]interface{}, len(senderIdentities))
+ for i, identity := range senderIdentities {
+ // Adjust according to the format of identity. If it's a full email address, use sender = ?; if it's a domain, use sender LIKE '%@domain'.
+ if strings.Contains(identity, "@") {
+ likes[i] = "sender = ?"
+ params[i] = identity
+ } else {
+ likes[i] = "sender LIKE ?"
+ params[i] = "%@" + identity
+ }
+ }
+ vals, err = g.DB().Ctx(ctx).Model("mailstat_senders").
+ Fields("DISTINCT postfix_message_id").
+ Where(strings.Join(likes, " OR "), params...).
+ Where("log_time_millis >= ?", evaluationWindowStartMillis).
+ Array()
+ if err != nil {
+ g.Log().Errorf(ctx, "EvaluateIpScore: Failed to get postfix_message_ids for IP %s (identities: %v): %v", senderIp, senderIdentities, err)
+ }
+ for _, v := range vals {
+ if pmid := v.String(); pmid != "" {
+ relevantPmids = append(relevantPmids, pmid)
+ }
+ }
+ }
+
+ totalSent := 0
+ successfulSends := 0
+ hardBounces := 0
+ softBounces := 0
+ deferredSends := 0 // status='deferred' from mailstat_send_mails
+ openedCount := 0 // Needs to be obtained from mailstat_opened
+ clickedCount := 0 // Needs to be obtained from mailstat_clicked
+
+ if len(relevantPmids) > 0 {
+ // 1. Get sending statistics (mailstat_send_mails)
+ type SendMailStatItem struct {
+ Status string `json:"status"`
+ Dsn string `json:"dsn"`
+ Count int `json:"count"`
+ }
+ var sendMailStats []SendMailStatItem
+ err = g.DB().Model("mailstat_send_mails").
+ Ctx(ctx).
+ WhereIn("postfix_message_id", relevantPmids).
+ Where("log_time_millis >= ?", evaluationWindowStartMillis).
+ Group("status, dsn").
+ Fields("status, dsn, COUNT(*) AS count").
+ Scan(&sendMailStats)
+ if err != nil {
+ g.Log().Errorf(ctx, "EvaluateIpScore: Failed to get send mail stats for IP %s (pmids: %d): %v", senderIp, len(relevantPmids), err)
+ } else {
+ for _, stat := range sendMailStats {
+ totalSent += stat.Count
+ switch strings.ToLower(stat.Status) {
+ case "sent":
+ successfulSends += stat.Count
+ case "bounced":
+ if len(stat.Dsn) > 0 {
+ switch stat.Dsn[0] {
+ case '5':
+ hardBounces += stat.Count
+ case '4':
+ softBounces += stat.Count
+ default:
+ softBounces += stat.Count // Others are classified as soft bounces
+ }
+ } else {
+ softBounces += stat.Count // Bounces without a DSN are treated as soft bounces
+ }
+ case "deferred":
+ deferredSends += stat.Count
+ }
+ }
+ }
+ // Get openedCount and clickedCount (requires user interaction data)
+ openedCount, _ = g.DB().Model("mailstat_opened").
+ Ctx(ctx).
+ WhereIn("postfix_message_id", relevantPmids).
+ Where("log_time_millis >= ?", evaluationWindowStartMillis).
+ Fields("DISTINCT postfix_message_id").
+ Count()
+ clickedCount, _ = g.DB().Model("mailstat_clicked").
+ Ctx(ctx).
+ WhereIn("postfix_message_id", relevantPmids).
+ Where("log_time_millis >= ?", evaluationWindowStartMillis).
+ Fields("DISTINCT postfix_message_id").
+ Count()
+ }
+
+ currentScore := float64(warmupStatus.Score) // Adjust starting from the current score
+
+ if totalSent == 0 && len(relevantPmids) == 0 && len(senderIdentities) == 0 {
+ // If the IP is not configured with any sender identities, do not adjust the score, only update the evaluation time
+ g.Log().Infof(ctx, "EvaluateIpScore: IP %s has no configured sender identities. Score remains %d.", senderIp, warmupStatus.Score)
+ } else if totalSent < minSendVolumeForFullScoring && totalSent > 0 { // Low sending volume
+ if hardBounces > 0 {
+ currentScore -= 15 // Low volume but with hard bounces, heavy penalty
+ } else if softBounces > 0 {
+ currentScore -= 7 // Low volume with soft bounces
+ } else if successfulSends > 0 {
+ currentScore += 2 // Low volume but with successes
+ } else { // Low volume and no successes (could be all deferred or other issues)
+ currentScore -= 5
+ }
+ } else if totalSent >= minSendVolumeForFullScoring { // Sufficient sending volume for a more comprehensive scoring
+ successRate := float64(successfulSends) / float64(totalSent)
+ hardBounceRate := float64(hardBounces) / float64(totalSent)
+ softBounceRate := float64(softBounces) / float64(totalSent)
+ deferredRate := float64(deferredSends) / float64(totalSent)
+
+ // Adjust based on success rate
+ currentScore += (successRate - 0.8) * 30 // 80% success rate is the baseline, fluctuation affects 30 points
+
+ // Adjust based on bounce rate
+ currentScore -= hardBounceRate * 100 // Penalty coefficient for hard bounces is 100
+ currentScore -= softBounceRate * 50 // Penalty coefficient for soft bounces is 50
+ currentScore -= deferredRate * 20 // Penalty coefficient for deferred is 20
+
+ // Adjust based on open and click rates (requires openedCount, clickedCount data)
+ if successfulSends > 0 {
+ openRate := float64(openedCount) / float64(successfulSends)
+ currentScore += openRate * 20 // 10% open rate baseline, affects 20 points (no penalty mechanism for now)
+ if openedCount > 0 {
+ clickRate := float64(clickedCount) / float64(openedCount)
+ currentScore += clickRate * 15 // 2% click rate (based on opens) baseline, affects 15 points (no penalty mechanism for now)
+ }
+ }
+ } else { // totalSent == 0 (but there are relevant pmids or identities, indicating no sending within the window)
+ if warmupStatus.Progress > 65 { // High progress but no sending
+ if warmupStatus.Score < 50 {
+ currentScore -= 1 // If the score is already not high and there is continuous no sending, decrease slowly
+ } else if warmupStatus.Score > 70 {
+ currentScore -= 0.2 // If the score is high but there is continuous no sending, decrease very slowly
+ }
+ }
+ }
+
+ finalScore := int(math.Max(0, math.Min(100, currentScore)))
+
+ _, err = g.DB().
+ Model("bm_sender_ip_warmup").
+ Ctx(ctx).
+ Where("id", warmupStatus.Id).
+ Data(g.Map{
+ "last_evaluate_time": gtime.Now().Timestamp(),
+ "score": finalScore,
+ "update_time": gtime.Now().Timestamp(),
+ }).
+ Update()
+
+ if err != nil {
+ g.Log().Errorf(ctx, "EvaluateIpScore: Failed to update score for IP %s: %v", senderIp, err)
+ return warmupStatus.Score, err // Return the old score and the error
+ }
+ g.Log().Debugf(ctx, "Evaluated score for IP %s: %d (TotalSent: %d, HardBounce: %d, SoftBounce: %d, Deferred: %d)", senderIp, finalScore, totalSent, hardBounces, softBounces, deferredSends)
+ return finalScore, nil
+}
+
+// UpdateWarmupPeriod dynamically adjusts the total warmup period.
+func (s *SenderIpWarmupService) UpdateWarmupPeriod(ctx context.Context, senderIp string) error {
+ record, err := s.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if err != nil {
+ return err
+ }
+
+ newPeriod := defaultWarmupPeriodDays
+ if record.Score < 40 { // Low score
+ newPeriod = defaultWarmupPeriodDays + 15 + (record.ReWarmups * 5) // Extend, and increase based on the number of re-warmups
+ } else if record.Score > 80 && record.Progress > 50 { // Good performance and more than halfway through
+ newPeriod = record.Period - 10
+ if newPeriod < 21 {
+ newPeriod = 21
+ } // Minimum warmup period of 21 days
+ }
+ // Ensure the new period is not less than a minimum value, e.g., 7 days
+ if newPeriod < 7 {
+ newPeriod = 7
+ }
+
+ if newPeriod != record.Period {
+ newEndTime := gtime.New(record.BeginTime).AddDate(0, 0, newPeriod).Timestamp()
+ _, err = g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Data(g.Map{
+ "period": newPeriod,
+ "end_time": newEndTime,
+ "update_time": gtime.Now().Timestamp(),
+ }).Where("id", record.Id).Update()
+ if err != nil {
+ g.Log().Errorf(ctx, "UpdateWarmupPeriod: Failed for IP %s: %v", senderIp, err)
+ return err
+ }
+ g.Log().Infof(ctx, "Updated warmup period for IP %s to %d days. New end time: %s", senderIp, newPeriod, gtime.New(newEndTime).String())
+ }
+ return nil
+}
+
+// UpdateWarmupProgress updates the warmup progress of an IP.
+func (s *SenderIpWarmupService) UpdateWarmupProgress(ctx context.Context, senderIp string) error {
+ record, err := s.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if err != nil {
+ return err
+ }
+
+ if record.BeginTime == 0 || record.Period <= 0 {
+ g.Log().Debugf(ctx, "UpdateWarmupProgress: IP %s has no begin time or invalid period. Progress not updated.", senderIp)
+ return nil // Not started or period is invalid
+ }
+
+ daysPassed := (gtime.Now().Timestamp() - record.BeginTime) / (24 * 60 * 60)
+ if daysPassed < 0 {
+ daysPassed = 0
+ } // Prevent BeginTime from being in the future
+
+ progress := int((float64(daysPassed) / float64(record.Period)) * 100)
+
+ // Adjust progress based on score: a low score may cause progress to stagnate or slightly regress
+ if record.Score < minScoreForSending && progress > record.Progress && record.Progress > 10 { // Extremely low score and had progress before
+ progress = record.Progress - 5 // Progress regresses
+ } else if record.Score < 40 && progress > record.Progress { // Poor score
+ progress = record.Progress + int(math.Max(0, (float64(progress-record.Progress)*0.3))) // Slow progress
+ } else if record.Score >= 70 && progress > record.Progress { // Good score
+ progress = record.Progress + int(math.Max(0, (float64(progress-record.Progress)*0.5))) // Accelerated progress
+ }
+
+ finalProgress := int(math.Max(0, math.Min(100, float64(progress))))
+
+ if finalProgress != record.Progress {
+ _, err = g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Data(g.Map{
+ "progress": finalProgress,
+ "update_time": gtime.Now().Timestamp(),
+ }).Where("id", record.Id).Update()
+ if err != nil {
+ g.Log().Errorf(ctx, "UpdateWarmupProgress: Failed for IP %s: %v", senderIp, err)
+ return err
+ }
+ g.Log().Debugf(ctx, "Updated warmup progress for IP %s to %d%% (Days passed: %d, Period: %d, Score: %d)", senderIp, finalProgress, daysPassed, record.Period, record.Score)
+ }
+ return nil
+}
+
+// CheckAndTriggerReWarmup checks if a re-warmup is necessary.
+func (s *SenderIpWarmupService) CheckAndTriggerReWarmup(ctx context.Context, senderIp string) error {
+ record, err := s.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if err != nil {
+ return err
+ }
+
+ needsReWarmup := false
+ // Condition 1: Warmup completed (100% progress), but the current score has dropped significantly (e.g., below 40)
+ if record.Progress >= 100 && record.Score < 40 {
+ needsReWarmup = true
+ g.Log().Infof(ctx, "IP %s (score: %d, progress: %d%%) may need re-warmup due to score drop.", senderIp, record.Score, record.Progress)
+ }
+
+ if needsReWarmup {
+ now := gtime.Now()
+ newPeriod := defaultWarmupPeriodDays + 15 // The re-warmup period can be slightly longer
+ _, err = g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Data(g.Map{
+ "progress": 0,
+ "re_warmups": record.ReWarmups + 1,
+ "period": newPeriod,
+ "begin_time": now.Timestamp(),
+ "end_time": now.AddDate(0, 0, newPeriod).Timestamp(),
+ "last_evaluate_time": now.Timestamp(),
+ "update_time": now.Timestamp(),
+ // "score": 30, // Optional: Reset the score to a lower initial value upon re-warmup
+ }).Where("id", record.Id).Update()
+ if err != nil {
+ g.Log().Errorf(ctx, "CheckAndTriggerReWarmup: Failed to reset IP %s for re-warmup: %v", senderIp, err)
+ return err
+ }
+ g.Log().Infof(ctx, "IP %s has been reset for re-warmup. New period: %d days.", senderIp, newPeriod)
+ }
+ return nil
+}
+
+// GetSendingRateFactor returns a sending rate adjustment factor (0.0 - 1.0) based on the score.
+func (s *SenderIpWarmupService) GetSendingRateFactor(ctx context.Context, senderIp string) (factor float64, err error) {
+ record, err := s.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if err != nil || record == nil {
+ g.Log().Warningf(ctx, "GetSendingRateFactor: IP %s status unknown or error (%v), defaulting to very cautious rate.", senderIp, err)
+ return 0.05, err // Status unknown, very low rate
+ }
+
+ // Warmup not complete, and score is very low, or warmup has just begun
+ if record.Progress < 100 {
+ if record.Score < minScoreForSending {
+ return 0.0, nil // Pause sending
+ }
+ // In the early stages of warmup, the rate should be very low and gradually increase with progress and score
+ // This is a simplified step-wise increase example
+ baseProgressFactor := float64(record.Progress) / 100.0
+ scoreFactor := (float64(record.Score) - float64(minScoreForSending)) / (100.0 - float64(minScoreForSending))
+ if scoreFactor < 0 {
+ scoreFactor = 0
+ }
+
+ // Example: a smoother warmup rate = (base progress rate * 0.3) + (score performance rate * 0.7)
+ // The rate should not exceed the upper limit corresponding to the current progress
+ rate := baseProgressFactor*0.3 + scoreFactor*0.7
+
+ if rate < 0.01 && record.Progress < 10 {
+ rate = 0.01
+ } // Minimum startup rate
+ if rate > baseProgressFactor {
+ rate = baseProgressFactor
+ } // The rate does not exceed the limit allowed by the current progress
+ if rate > 1.0 {
+ rate = 1.0
+ }
+ if rate < 0 {
+ rate = 0
+ }
+ g.Log().Debugf(ctx, "GetSendingRateFactor: IP %s (Progress: %d%%, Score: %d) -> In Warmup, Rate Factor: %.2f", senderIp, record.Progress, record.Score, rate)
+ return rate, nil
+ }
+
+ // Rate adjustment after warmup is complete
+ if record.Score < minScoreForSending {
+ g.Log().Debugf(ctx, "GetSendingRateFactor: IP %s (Progress: %d%%, Score: %d) -> Paused (Score too low)", senderIp, record.Progress, record.Score)
+ return 0.0, nil // Pause sending
+ }
+
+ if record.Score >= 85 {
+ factor = 1.0
+ return
+ } else if record.Score >= 70 {
+ factor = 0.8
+ return
+ } else if record.Score >= 50 {
+ factor = 0.5
+ return
+ } else if record.Score >= minScoreForSending {
+ factor = 0.2
+ return
+ }
+
+ g.Log().Debugf(ctx, "GetSendingRateFactor: IP %s (Progress: %d%%, Score: %d) -> Default Rate Factor: 0.1 (Should be covered by brackets)", senderIp, record.Progress, record.Score)
+ return 0.1, nil // Default to a lower rate, should be covered by the conditions above
+}
+
+// PeriodicTask is a background periodic task to update the warmup status of all relevant IPs.
+func (s *SenderIpWarmupService) PeriodicTask(ctx context.Context) {
+ g.Log().Info(ctx, "Sender IP Warmup Periodic Task: Starting...")
+ var activeIPs []*entity.SenderIpWarmup
+ err := g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Scan(&activeIPs) // Get all recorded IPs
+ if err != nil {
+ g.Log().Errorf(ctx, "PeriodicTask: Failed to get active IPs from SenderIpWarmup: %v", err)
+ return
+ }
+ if len(activeIPs) == 0 {
+ g.Log().Info(ctx, "PeriodicTask: No sender IPs found in warmup table.")
+ return
+ }
+
+ for _, ipRecord := range activeIPs {
+ senderIp := ipRecord.SenderIp
+ g.Log().Debugf(ctx, "PeriodicTask: Processing IP %s", senderIp)
+
+ // 1. Evaluate score (most frequent)
+ if gtime.Now().After(gtime.New(ipRecord.LastEvaluateTime).Add(evaluationInterval)) {
+ _, err := s.EvaluateIpScore(ctx, senderIp)
+ if err != nil {
+ g.Log().Errorf(ctx, "PeriodicTask: Failed to evaluate score for IP %s: %v", senderIp, err)
+ }
+ } else {
+ g.Log().Debugf(ctx, "PeriodicTask: Skipping score evaluation for IP %s, last evaluated at %s", senderIp, gtime.New(ipRecord.LastEvaluateTime))
+ }
+
+ // Re-fetch the record as the score may have been updated
+ currentIpStatus, getErr := s.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if getErr != nil {
+ g.Log().Errorf(ctx, "PeriodicTask: Failed to get updated status for IP %s after eval: %v", senderIp, getErr)
+ continue
+ }
+
+ // 2. Update warmup period (can be less frequent)
+ // Simple handling: try to update the warmup period and progress after each score evaluation
+ err = s.UpdateWarmupPeriod(ctx, senderIp)
+ if err != nil {
+ g.Log().Errorf(ctx, "PeriodicTask: Failed to update warmup period for IP %s: %v", senderIp, err)
+ }
+
+ // 3. Update progress (can be less frequent)
+ err = s.UpdateWarmupProgress(ctx, senderIp)
+ if err != nil {
+ g.Log().Errorf(ctx, "PeriodicTask: Failed to update warmup progress for IP %s: %v", senderIp, err)
+ }
+
+ // 4. Check if re-warmup is needed (can be less frequent, e.g., once a day)
+ // For simplicity, check every time; the frequency can be adjusted in practice
+ // Ensure that the score and progress are up-to-date before checking
+ if currentIpStatus.Progress >= 100 || (gtime.Now().Unix()-currentIpStatus.UpdateTime > gconv.Int64(reWarmupCheckInterval.Seconds()/2)) { // Progress is 100% or it has been a while since the last update
+ err = s.CheckAndTriggerReWarmup(ctx, senderIp)
+ if err != nil {
+ g.Log().Errorf(ctx, "PeriodicTask: Failed to check re-warmup for IP %s: %v", senderIp, err)
+ }
+ }
+ }
+ g.Log().Info(ctx, "Sender IP Warmup Periodic Task: Finished.")
+}
diff --git a/core/internal/service/warmup/warmup_daily_upstairs.go b/core/internal/service/warmup/warmup_daily_upstairs.go
new file mode 100644
index 00000000..6c52eb31
--- /dev/null
+++ b/core/internal/service/warmup/warmup_daily_upstairs.go
@@ -0,0 +1,89 @@
+package warmup
+
+import (
+ "context"
+ "math"
+
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gtime"
+)
+
+const (
+ // dailyIncreaseFactor is the factor used for sending volume growth after the initial plan.
+ // 1.3 means a 30% increase per day.
+ dailyIncreaseFactor = 1.3
+)
+
+// WarmupStep defines the sending limits for a specific day in the warmup schedule.
+type WarmupStep struct {
+ DailyLimit int
+ HourlyLimit int
+}
+
+// warmupSchedule provides predefined sending volumes for the first few days of warmup.
+// This is the base volume for each mail provider group.
+var warmupSchedule = []WarmupStep{
+ {DailyLimit: 1000, HourlyLimit: 100}, // Day 1
+ {DailyLimit: 1500, HourlyLimit: 150}, // Day 2
+ {DailyLimit: 2000, HourlyLimit: 200}, // Day 3
+ {DailyLimit: 3000, HourlyLimit: 300}, // Day 4
+ {DailyLimit: 5000, HourlyLimit: 500}, // Day 5
+ {DailyLimit: 7000, HourlyLimit: 700}, // Day 6
+ {DailyLimit: 10000, HourlyLimit: 1000}, // Day 7
+}
+
+// WarmupDailyUpstairsService manages the daily sending volume during the IP warmup period.
+type WarmupDailyUpstairsService struct {
+ ipWarmupService *SenderIpWarmupService
+}
+
+var insWarmupDailyUpstairsService = WarmupDailyUpstairsService{
+ ipWarmupService: SenderIpWarmup(),
+}
+
+// WarmupDailyUpstairs returns the singleton instance of the service.
+func WarmupDailyUpstairs() *WarmupDailyUpstairsService {
+ return &insWarmupDailyUpstairsService
+}
+
+// GetSendingLimits calculates the base daily and hourly sending limits for a given IP.
+// These limits are based on the number of days the IP has been in the warmup process.
+// These are the base limits for each mail provider group and should be further adjusted by a provider-specific scoring factor.
+func (s *WarmupDailyUpstairsService) GetSendingLimits(ctx context.Context, senderIp string) (dailyLimit int, hourlyLimit int, err error) {
+ ipWarmupStatus, err := s.ipWarmupService.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if err != nil {
+ g.Log().Errorf(ctx, "GetSendingLimits: Failed to get warmup status for IP %s: %v", senderIp, err)
+ return 0, 0, err
+ }
+
+ if ipWarmupStatus.BeginTime == 0 {
+ g.Log().Debugf(ctx, "GetSendingLimits: IP %s warmup has not started. Limits are 0.", senderIp)
+ return 0, 0, nil // Warmup has not started
+ }
+
+ // Calculate the current day of the warmup process (1-based index).
+ daysSinceWarmupStart := (gtime.Now().Timestamp()-ipWarmupStatus.BeginTime)/(24*60*60) + 1
+ if daysSinceWarmupStart <= 0 {
+ daysSinceWarmupStart = 1 // If it has started, it is at least day 1.
+ }
+
+ scheduleLen := len(warmupSchedule)
+
+ if daysSinceWarmupStart <= int64(scheduleLen) {
+ // Within the predefined schedule
+ step := warmupSchedule[daysSinceWarmupStart-1]
+ dailyLimit = step.DailyLimit
+ hourlyLimit = step.HourlyLimit
+ g.Log().Debugf(ctx, "GetSendingLimits: IP %s is on day %d of warmup. Using predefined limits: Daily=%d, Hourly=%d", senderIp, daysSinceWarmupStart, dailyLimit, hourlyLimit)
+ } else {
+ // After the predefined schedule, apply the growth factor
+ lastStep := warmupSchedule[scheduleLen-1]
+ daysAfterSchedule := daysSinceWarmupStart - int64(scheduleLen)
+
+ dailyLimit = int(float64(lastStep.DailyLimit) * math.Pow(dailyIncreaseFactor, float64(daysAfterSchedule)))
+ hourlyLimit = int(float64(lastStep.HourlyLimit) * math.Pow(dailyIncreaseFactor, float64(daysAfterSchedule)))
+ g.Log().Debugf(ctx, "GetSendingLimits: IP %s is on day %d of warmup. Calculating limits with growth factor: Daily=%d, Hourly=%d", senderIp, daysSinceWarmupStart, dailyLimit, hourlyLimit)
+ }
+
+ return dailyLimit, hourlyLimit, nil
+}
diff --git a/core/internal/service/warmup/warmup_with_campaigns.go b/core/internal/service/warmup/warmup_with_campaigns.go
new file mode 100644
index 00000000..3a209ab8
--- /dev/null
+++ b/core/internal/service/warmup/warmup_with_campaigns.go
@@ -0,0 +1,168 @@
+package warmup
+
+import (
+ "billionmail-core/internal/consts"
+ "billionmail-core/internal/model/entity"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/v2/frame/g"
+ "math"
+)
+
+// CampaignWarmupAssociation extends CampaignWarmup with prediction data.
+type CampaignWarmupAssociation struct {
+ entity.CampaignWarmup
+ EstimatedSeconds int64 `json:"estimated_seconds"`
+}
+
+// WarmupCampaignService manages the association between warmup processes and marketing campaigns.
+type WarmupCampaignService struct {
+ ipWarmupService *SenderIpWarmupService
+ providerService *SenderIpMailProviderService
+}
+
+var insWarmupCampaignService = WarmupCampaignService{
+ ipWarmupService: SenderIpWarmup(),
+ providerService: SenderIpMailProvider(),
+}
+
+// WarmupCampaign returns the singleton instance of the service.
+func WarmupCampaign() *WarmupCampaignService {
+ return &insWarmupCampaignService
+}
+
+// AssociateCampaignWithWarmup associates a marketing task with an IP warmup process.
+// If a warmup process for the given IP does not exist, it will be created.
+func (s *WarmupCampaignService) AssociateCampaignWithWarmup(ctx context.Context, taskId int64, senderIp string) (*CampaignWarmupAssociation, error) {
+ // 1. Get or create the warmup status for the IP to get its ID.
+ warmupStatus, err := s.ipWarmupService.InitializeOrGetWarmupStatus(ctx, senderIp)
+ if err != nil {
+ g.Log().Errorf(ctx, "AssociateCampaignWithWarmup: failed to get warmup status for IP %s: %v", senderIp, err)
+ return nil, err
+ }
+ warmupId := warmupStatus.Id
+
+ // Calculate the estimated sending time
+ estimatedSeconds, err := s.CalculateEstimatedTime(ctx, taskId, senderIp)
+ if err != nil {
+ // Log the error but don't fail the entire association
+ g.Log().Warningf(ctx, "AssociateCampaignWithWarmup: failed to calculate estimated time for task %d: %v", taskId, err)
+ }
+
+ // 2. Check if an association for this task already exists.
+ var existingLink *entity.CampaignWarmup
+ err = g.DB().Model("bm_campaign_warmup").Ctx(ctx).Where("task_id", taskId).Scan(&existingLink)
+ if err != nil {
+ g.Log().Errorf(ctx, "AssociateCampaignWithWarmup: failed to check for existing link for task ID %d: %v", taskId, err)
+ return nil, err
+ }
+
+ if existingLink != nil {
+ if existingLink.WarmupId == warmupId {
+ g.Log().Debugf(ctx, "AssociateCampaignWithWarmup: Task ID %d is already associated with warmup ID %d.", taskId, warmupId)
+ return &CampaignWarmupAssociation{
+ CampaignWarmup: *existingLink,
+ EstimatedSeconds: estimatedSeconds,
+ }, nil
+ }
+ // If the task is associated with a different warmup, update it.
+ existingLink.WarmupId = warmupId
+ _, err = g.DB().Model("bm_campaign_warmup").Ctx(ctx).Where("id", existingLink.Id).Data(g.Map{
+ "warmup_id": warmupId,
+ }).Update()
+ if err != nil {
+ g.Log().Errorf(ctx, "AssociateCampaignWithWarmup: failed to update association for task ID %d to warmup ID %d: %v", taskId, warmupId, err)
+ return nil, err
+ }
+ g.Log().Infof(ctx, "AssociateCampaignWithWarmup: Updated association for task ID %d to new warmup ID %d.", taskId, warmupId)
+ return &CampaignWarmupAssociation{
+ CampaignWarmup: *existingLink,
+ EstimatedSeconds: estimatedSeconds,
+ }, nil
+ }
+
+ // 3. Create a new association.
+ newLink := &entity.CampaignWarmup{
+ TaskId: taskId,
+ WarmupId: warmupId,
+ }
+
+ newLink.Id, err = g.DB().Model("bm_campaign_warmup").Ctx(ctx).Data(newLink).OmitEmptyData().InsertAndGetId()
+ if err != nil {
+ g.Log().Errorf(ctx, "AssociateCampaignWithWarmup: failed to create association for task ID %d and warmup ID %d: %v", taskId, warmupId, err)
+ return nil, err
+ }
+
+ result := &CampaignWarmupAssociation{
+ CampaignWarmup: *newLink,
+ EstimatedSeconds: estimatedSeconds,
+ }
+
+ g.Log().Infof(ctx, "Successfully associated task ID %d with warmup ID %d (IP: %s). Estimated time: %d seconds.", taskId, warmupId, senderIp, estimatedSeconds)
+ return result, nil
+}
+
+// CalculateEstimatedTime calculates the estimated sending time in seconds for a given task and IP.
+func (s *WarmupCampaignService) CalculateEstimatedTime(ctx context.Context, taskId int64, senderIp string) (int64, error) {
+ // Get the total number of unsent recipients
+ unsentCount, err := g.DB().Model("recipient_info").Ctx(ctx).Where("task_id", taskId).Where("is_sent", 0).Count()
+ if err != nil {
+ return -1, fmt.Errorf("failed to get recipient count: %w", err)
+ }
+
+ if unsentCount == 0 {
+ return 0, nil
+ }
+
+ // Calculate the total hourly sending rate
+ totalHourlyRate := 0
+ providerGroups := []string{
+ consts.MailProviderGroupGmail,
+ consts.MailProviderGroupYahoo,
+ consts.MailProviderGroupOutlook,
+ consts.MailProviderGroupApple,
+ consts.MailProviderGroupProton,
+ consts.MailProviderGroupZoho,
+ consts.MailProviderGroupAmazon,
+ consts.MailProviderGroupOther,
+ }
+
+ for _, group := range providerGroups {
+ dailyLimit, hourlyLimit, err := s.providerService.GetAdjustedSendingLimitsForProvider(ctx, senderIp, group)
+ if err == nil {
+ totalHourlyRate += int(math.Min(float64(hourlyLimit), float64(dailyLimit)/24.0))
+ } else {
+ g.Log().Warningf(ctx, "calculateEstimatedTime: unable to get limits for group %s, IP %s: %v", group, senderIp, err)
+ }
+ }
+
+ if totalHourlyRate == 0 {
+ return -1, nil // -1 indicates infinite time
+ }
+
+ estimatedSeconds := int64((float64(unsentCount) / float64(totalHourlyRate)) * 3600.0)
+ return estimatedSeconds, nil
+}
+
+// GetWarmupStatusForCampaign retrieves the warmup status for a given marketing task.
+func (s *WarmupCampaignService) GetWarmupStatusForCampaign(ctx context.Context, taskId int64) (*entity.SenderIpWarmup, error) {
+ var link *entity.CampaignWarmup
+ err := g.DB().Model("bm_campaign_warmup").Ctx(ctx).Where("task_id", taskId).Scan(&link)
+ if err != nil {
+ g.Log().Errorf(ctx, "GetWarmupStatusForCampaign: failed to find association for task ID %d: %v", taskId, err)
+ return nil, err
+ }
+ if link == nil {
+ g.Log().Debugf(ctx, "GetWarmupStatusForCampaign: no warmup association found for task ID %d.", taskId)
+ return nil, nil // Or return a specific error like gerror.New("not found")
+ }
+
+ var warmupStatus *entity.SenderIpWarmup
+ err = g.DB().Model("bm_sender_ip_warmup").Ctx(ctx).Where("id", link.WarmupId).Scan(&warmupStatus)
+ if err != nil {
+ g.Log().Errorf(ctx, "GetWarmupStatusForCampaign: failed to get warmup status for warmup ID %d (task ID %d): %v", link.WarmupId, taskId, err)
+ return nil, err
+ }
+
+ return warmupStatus, nil
+}
diff --git a/core/run_dev.go b/core/run_dev.go
index 1934d0f3..ceb04c9a 100644
--- a/core/run_dev.go
+++ b/core/run_dev.go
@@ -31,6 +31,8 @@ type FileWatcher struct {
debounceMap map[string]int64 // Debounce map, recording last modification time of each file
debounceMs int64 // Debounce time interval (milliseconds)
logger *log.Logger // Logger
+ delay time.Duration // Delay before executing the script
+ timer *time.Timer // Timer for debouncing
}
// NewFileWatcher creates a new file watcher
@@ -48,6 +50,8 @@ func NewFileWatcher(rootPath string, scriptPath string, extensions []string) (*F
debounceMap: make(map[string]int64),
debounceMs: 500, // Default debounce time: 500 milliseconds
logger: log.New(os.Stdout, "[FileWatcher] ", log.LstdFlags),
+ delay: time.Second,
+ timer: time.NewTimer(time.Second),
}, nil
}
@@ -133,6 +137,8 @@ func (fw *FileWatcher) watchLoop(ctx context.Context) {
continue
}
+ fw.timer.Reset(fw.delay)
+
// Execute script
fw.logger.Printf("Detected file change: %s", event.Name)
go fw.executeScript(ctx)
@@ -178,6 +184,8 @@ func (fw *FileWatcher) shouldDebounce(filename string) bool {
// executeScript executes the script
func (fw *FileWatcher) executeScript(ctx context.Context) {
+ <-fw.timer.C
+
fw.mu.Lock()
if fw.isExecuting {
fw.mu.Unlock()
@@ -304,7 +312,7 @@ func main() {
}
// Create file watcher
- watcher, err := NewFileWatcher(AbsPath(rootPath), AbsPath(scriptPath), []string{".go"})
+ watcher, err := NewFileWatcher(AbsPath(rootPath), AbsPath(scriptPath), []string{".go", ".html"})
if err != nil {
logger.Fatalf("Failed to create file watcher: %v", err)
}