|
| 1 | +// Package flow provides durable job kind constants and payload types |
| 2 | +// used to replace in-memory timers with restart-safe database jobs. |
| 3 | +package flow |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "encoding/json" |
| 8 | + "fmt" |
| 9 | + "log/slog" |
| 10 | + |
| 11 | + "github.com/BTreeMap/PromptPipe/internal/models" |
| 12 | + "github.com/BTreeMap/PromptPipe/internal/store" |
| 13 | +) |
| 14 | + |
| 15 | +// Job kind constants for durable jobs that replace in-memory timers. |
| 16 | +const ( |
| 17 | + JobKindStateTransition = "state_transition" |
| 18 | + JobKindFeedbackTimeout = "feedback_timeout" |
| 19 | + JobKindFeedbackFollowup = "feedback_followup" |
| 20 | + JobKindDailyPromptReminder = "daily_prompt_reminder" |
| 21 | + JobKindAutoFeedbackEnforcement = "auto_feedback_enforcement" |
| 22 | +) |
| 23 | + |
| 24 | +// StateTransitionPayload is the JSON payload for state_transition jobs. |
| 25 | +type StateTransitionPayload struct { |
| 26 | + ParticipantID string `json:"participant_id"` |
| 27 | + TargetState string `json:"target_state"` |
| 28 | + Reason string `json:"reason,omitempty"` |
| 29 | +} |
| 30 | + |
| 31 | +// FeedbackTimeoutPayload is the JSON payload for feedback_timeout jobs. |
| 32 | +type FeedbackTimeoutPayload struct { |
| 33 | + ParticipantID string `json:"participant_id"` |
| 34 | + PhoneNumber string `json:"phone_number"` |
| 35 | +} |
| 36 | + |
| 37 | +// FeedbackFollowupPayload is the JSON payload for feedback_followup jobs. |
| 38 | +type FeedbackFollowupPayload struct { |
| 39 | + ParticipantID string `json:"participant_id"` |
| 40 | + PhoneNumber string `json:"phone_number"` |
| 41 | +} |
| 42 | + |
| 43 | +// DailyPromptReminderPayload is the JSON payload for daily_prompt_reminder jobs. |
| 44 | +type DailyPromptReminderPayload struct { |
| 45 | + ParticipantID string `json:"participant_id"` |
| 46 | + To string `json:"to"` |
| 47 | + ExpectedSentAt string `json:"expected_sent_at"` |
| 48 | +} |
| 49 | + |
| 50 | +// AutoFeedbackEnforcementPayload is the JSON payload for auto_feedback_enforcement jobs. |
| 51 | +type AutoFeedbackEnforcementPayload struct { |
| 52 | + ParticipantID string `json:"participant_id"` |
| 53 | +} |
| 54 | + |
| 55 | +// RegisterJobHandlers registers all flow-related job handlers with the given JobRunner. |
| 56 | +func RegisterJobHandlers(runner *store.JobRunner, stateManager StateManager, msgService MessagingService, schedulerTool *SchedulerTool, feedbackModule *FeedbackModule, stateTransitionTool *StateTransitionTool) { |
| 57 | + runner.RegisterHandler(JobKindStateTransition, makeStateTransitionHandler(stateManager, stateTransitionTool)) |
| 58 | + runner.RegisterHandler(JobKindFeedbackTimeout, makeFeedbackTimeoutHandler(stateManager, feedbackModule)) |
| 59 | + runner.RegisterHandler(JobKindFeedbackFollowup, makeFeedbackFollowupHandler(stateManager, msgService)) |
| 60 | + runner.RegisterHandler(JobKindDailyPromptReminder, makeDailyPromptReminderHandler(schedulerTool)) |
| 61 | + runner.RegisterHandler(JobKindAutoFeedbackEnforcement, makeAutoFeedbackEnforcementHandler(schedulerTool)) |
| 62 | +} |
| 63 | + |
| 64 | +func makeStateTransitionHandler(stateManager StateManager, stt *StateTransitionTool) store.JobHandler { |
| 65 | + return func(ctx context.Context, payload string) error { |
| 66 | + var p StateTransitionPayload |
| 67 | + if err := json.Unmarshal([]byte(payload), &p); err != nil { |
| 68 | + return fmt.Errorf("invalid state_transition payload: %w", err) |
| 69 | + } |
| 70 | + slog.Info("JobHandler.state_transition: executing", "participantID", p.ParticipantID, "targetState", p.TargetState) |
| 71 | + |
| 72 | + // Idempotency: check current state - if already at target, skip |
| 73 | + currentState, err := stateManager.GetStateData(ctx, p.ParticipantID, models.FlowTypeConversation, models.DataKeyConversationState) |
| 74 | + if err != nil { |
| 75 | + return fmt.Errorf("failed to read current state: %w", err) |
| 76 | + } |
| 77 | + if currentState == p.TargetState { |
| 78 | + slog.Info("JobHandler.state_transition: already at target state, skipping", "participantID", p.ParticipantID, "targetState", p.TargetState) |
| 79 | + return nil |
| 80 | + } |
| 81 | + |
| 82 | + // Execute the transition |
| 83 | + _, err = stt.executeImmediateTransition(ctx, p.ParticipantID, models.StateType(p.TargetState), p.Reason) |
| 84 | + if err != nil { |
| 85 | + return fmt.Errorf("state transition failed: %w", err) |
| 86 | + } |
| 87 | + // Clear the stored job ID reference |
| 88 | + _ = stateManager.SetStateData(ctx, p.ParticipantID, models.FlowTypeConversation, models.DataKeyStateTransitionTimerID, "") |
| 89 | + return nil |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +func makeFeedbackTimeoutHandler(stateManager StateManager, fm *FeedbackModule) store.JobHandler { |
| 94 | + return func(ctx context.Context, payload string) error { |
| 95 | + var p FeedbackTimeoutPayload |
| 96 | + if err := json.Unmarshal([]byte(payload), &p); err != nil { |
| 97 | + return fmt.Errorf("invalid feedback_timeout payload: %w", err) |
| 98 | + } |
| 99 | + slog.Info("JobHandler.feedback_timeout: executing", "participantID", p.ParticipantID) |
| 100 | + |
| 101 | + // Idempotency: check if feedback was already received |
| 102 | + feedbackState, err := stateManager.GetStateData(ctx, p.ParticipantID, models.FlowTypeConversation, models.DataKeyFeedbackState) |
| 103 | + if err == nil && feedbackState != "waiting_initial" { |
| 104 | + slog.Info("JobHandler.feedback_timeout: feedback already received, skipping", "participantID", p.ParticipantID, "currentState", feedbackState) |
| 105 | + return nil |
| 106 | + } |
| 107 | + |
| 108 | + // Inject phone number into context for the handler |
| 109 | + ctxWithPhone := context.WithValue(ctx, phoneNumberContextKey, p.PhoneNumber) |
| 110 | + fm.handleInitialFeedbackTimeout(ctxWithPhone, p.ParticipantID) |
| 111 | + return nil |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +func makeFeedbackFollowupHandler(stateManager StateManager, msgService MessagingService) store.JobHandler { |
| 116 | + return func(ctx context.Context, payload string) error { |
| 117 | + var p FeedbackFollowupPayload |
| 118 | + if err := json.Unmarshal([]byte(payload), &p); err != nil { |
| 119 | + return fmt.Errorf("invalid feedback_followup payload: %w", err) |
| 120 | + } |
| 121 | + slog.Info("JobHandler.feedback_followup: executing", "participantID", p.ParticipantID) |
| 122 | + |
| 123 | + // Idempotency: check if feedback was already completed |
| 124 | + feedbackState, err := stateManager.GetStateData(ctx, p.ParticipantID, models.FlowTypeConversation, models.DataKeyFeedbackState) |
| 125 | + if err == nil && feedbackState == "completed" { |
| 126 | + slog.Info("JobHandler.feedback_followup: feedback already completed, skipping", "participantID", p.ParticipantID) |
| 127 | + return nil |
| 128 | + } |
| 129 | + |
| 130 | + // Send follow-up message |
| 131 | + followupMessage := "Hey! 👋 Just checking in - I sent you a habit suggestion earlier. Even if you didn't try it, I'd love to know what you think! Your feedback helps me learn what works best for you. 😊" |
| 132 | + if err := msgService.SendMessage(ctx, p.PhoneNumber, followupMessage); err != nil { |
| 133 | + return fmt.Errorf("failed to send follow-up: %w", err) |
| 134 | + } |
| 135 | + |
| 136 | + // Update state |
| 137 | + _ = stateManager.SetStateData(ctx, p.ParticipantID, models.FlowTypeConversation, models.DataKeyFeedbackState, "followup_sent") |
| 138 | + return nil |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +func makeDailyPromptReminderHandler(schedulerTool *SchedulerTool) store.JobHandler { |
| 143 | + return func(ctx context.Context, payload string) error { |
| 144 | + var p DailyPromptReminderPayload |
| 145 | + if err := json.Unmarshal([]byte(payload), &p); err != nil { |
| 146 | + return fmt.Errorf("invalid daily_prompt_reminder payload: %w", err) |
| 147 | + } |
| 148 | + slog.Info("JobHandler.daily_prompt_reminder: executing", "participantID", p.ParticipantID, "to", p.To) |
| 149 | + |
| 150 | + // Delegate to existing scheduler tool logic (which already checks pending state) |
| 151 | + schedulerTool.sendDailyPromptReminder(p.ParticipantID, p.To, p.ExpectedSentAt) |
| 152 | + return nil |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +func makeAutoFeedbackEnforcementHandler(schedulerTool *SchedulerTool) store.JobHandler { |
| 157 | + return func(ctx context.Context, payload string) error { |
| 158 | + var p AutoFeedbackEnforcementPayload |
| 159 | + if err := json.Unmarshal([]byte(payload), &p); err != nil { |
| 160 | + return fmt.Errorf("invalid auto_feedback_enforcement payload: %w", err) |
| 161 | + } |
| 162 | + slog.Info("JobHandler.auto_feedback_enforcement: executing", "participantID", p.ParticipantID) |
| 163 | + |
| 164 | + // Delegate to existing scheduler tool logic (which already checks state) |
| 165 | + schedulerTool.enforceFeedbackIfNoResponse(p.ParticipantID) |
| 166 | + return nil |
| 167 | + } |
| 168 | +} |
0 commit comments