package main import ( "context" "errors" "log" "os" "reflect" "strings" "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" ) // questionTablePollerRunner is the interface expected by the poller loop. type questionTablePollerRunner interface { RunOnce(context.Context) (questiontable.DispatcherStats, error) } // questionTableConfig holds the optional Notable question-table env values. type questionTableConfig struct { BaseID string SheetID string OperatorID string FieldMapping map[string]string } // readQuestionTableConfig reads the three dedicated env vars and returns // a validated config. All three blank => disabled (no error). Any partial // configuration => stable configuration error (no values echoed). func readQuestionTableConfig() (questionTableConfig, error) { cfg := questionTableConfig{ BaseID: strings.TrimSpace(os.Getenv("DINGTALK_QUESTION_TABLE_BASE_ID")), SheetID: strings.TrimSpace(os.Getenv("DINGTALK_QUESTION_TABLE_SHEET_ID")), OperatorID: strings.TrimSpace(os.Getenv("DINGTALK_QUESTION_TABLE_OPERATOR_ID")), } allBlank := cfg.BaseID == "" && cfg.SheetID == "" && cfg.OperatorID == "" allSet := cfg.BaseID != "" && cfg.SheetID != "" && cfg.OperatorID != "" if allBlank { return questionTableConfig{}, nil } if allSet { return cfg, nil } return questionTableConfig{}, errors.New("DingTalk question table config: all three env vars must be set or all blank (DINGTALK_QUESTION_TABLE_BASE_ID, DINGTALK_QUESTION_TABLE_SHEET_ID, DINGTALK_QUESTION_TABLE_OPERATOR_ID)") } // buildQuestionTableDispatcher creates a validated question-table dispatcher // when the repo is non-nil and all required credentials are present. // The optional answer rewriter converts the stored answer into the same // outbound form used for DingTalk delivery (resource images to stable HTTPS, // document links, anchor cleanup). No HTTP request occurs at build time. // It returns (nil, nil) when the question-table feature is disabled. func buildQuestionTableDispatcher(repo questiontable.ExportRepository, clientID, clientSecret string, cfg questionTableConfig, rewriter questiontable.AnswerRewriter) (*questiontable.Dispatcher, error) { // Disabled: all blank config. if cfg.BaseID == "" && cfg.SheetID == "" && cfg.OperatorID == "" { return nil, nil } if repo == nil { return nil, errors.New("question table dispatcher: repository is required") } client, err := questiontable.NewClient(questiontable.Config{ ClientID: clientID, Secret: clientSecret, BaseID: cfg.BaseID, SheetID: cfg.SheetID, OperatorID: cfg.OperatorID, FieldMapping: cfg.FieldMapping, }, nil) if err != nil { return nil, err } return questiontable.NewDispatcher(repo, client, &questiontable.DispatcherOptions{ Rewriter: rewriter, SendTimeout: 60 * time.Second, }) } // answerRewriterAdapter adapts a blocking outbound content rewriter to the // AnswerRewriter contract (caller never gets an error, so the original answer // is always written when conversion cannot run). type answerRewriterAdapter struct { rewriter dingtalk.OutboundContentRewriter } func (a answerRewriterAdapter) Rewrite(ctx context.Context, content string) (string, error) { if a.rewriter == nil { return content, nil } return a.rewriter.Rewrite(ctx, content), nil } // runQuestionTablePoller runs the dispatcher immediately, then every interval. // Non-positive interval or nil/typed-nil runner returns without calling. // Continues after a RunOnce error. Exits promptly on context cancellation. // Logging is safe: success may log only Claimed/Exported/Failed integers; // errors log stable stage text only, never raw errors. func runQuestionTablePoller(ctx context.Context, runner questionTablePollerRunner, interval time.Duration) { if runner == nil || interval <= 0 { return } // Guard against typed nil. if isNilPoller(runner) { return } runOnce := func() { runCtx, cancel := context.WithTimeout(ctx, 30*time.Second) stats, err := runner.RunOnce(runCtx) cancel() if err != nil { log.Printf("question table dispatch failed") return } if stats.Claimed > 0 || stats.Exported > 0 || stats.Failed > 0 { log.Printf("question table dispatch: claimed=%d exported=%d failed=%d", stats.Claimed, stats.Exported, stats.Failed) } } if ctx.Err() != nil { return } runOnce() ticker := time.NewTicker(interval) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: runOnce() } } } // isNilPoller returns true when runner is a typed nil. func isNilPoller(runner questionTablePollerRunner) bool { if runner == nil { return true } // reflect-based typed-nil check for the interface. return isInterfaceNil(runner) } // isInterfaceNil returns true when v is a typed nil wrapped in an interface. func isInterfaceNil(v interface{}) bool { if v == nil { return true } rv := reflect.ValueOf(v) switch rv.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return rv.IsNil() default: return false } }