63 lines
1.8 KiB
Go
63 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"neuralhunt/internal/data"
|
|
)
|
|
|
|
func (s *Server) dispatchHostedCreditEvents(ctx context.Context) {
|
|
if strings.TrimSpace(s.customerServiceInternalURL) == "" || strings.TrimSpace(s.internalServiceSecret) == "" {
|
|
return
|
|
}
|
|
events, err := s.store.PendingHostedCreditEvents(ctx, 25)
|
|
if err != nil {
|
|
log.Printf("hosted credit outbox: %v", err)
|
|
return
|
|
}
|
|
for _, ev := range events {
|
|
if ev.Attempts > 0 && ev.Attempts%20 == 0 {
|
|
log.Printf("hosted credit event %s still pending after %d attempts", ev.EventID, ev.Attempts)
|
|
}
|
|
if err := s.deliverHostedCreditEvent(ctx, ev); err != nil {
|
|
_ = s.store.MarkHostedCreditEventAttempt(ctx, ev.EventID, err.Error())
|
|
continue
|
|
}
|
|
_ = s.store.MarkHostedCreditEventDelivered(ctx, ev.EventID)
|
|
}
|
|
}
|
|
|
|
func (s *Server) deliverHostedCreditEvent(ctx context.Context, ev data.HostedCreditEvent) error {
|
|
body, _ := json.Marshal(map[string]any{
|
|
"event_id": ev.EventID,
|
|
"worker_client_id": ev.WorkerClientID,
|
|
"reward_client_id": ev.RewardClientID,
|
|
"task_id": ev.TaskID,
|
|
"seq": ev.Seq,
|
|
"score": ev.Score,
|
|
})
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.customerServiceInternalURL+"/internal/game/positive-tip", bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+s.internalServiceSecret)
|
|
resp, err := s.customerServiceHTTP.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
if resp.StatusCode/100 != 2 {
|
|
return fmt.Errorf("customer service HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
|
|
}
|
|
return nil
|
|
}
|