[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-0cf9e7a8-5e10-4786-be8c-08a812866dc1":3,"$fKBvWbzyZ-Cb2KaWs_ypw_UkPsON0QAmd96jc8LSh30E":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":17,"createdAt":18,"updatedAt":18,"module":19,"category":26,"packages":33},"0cf9e7a8-5e10-4786-be8c-08a812866dc1","temporal-golang-pro","用于构建使用Temporal Go SDK的耐用分布式系统。涵盖确定性的工作流规则、mTLS工作配置和高级模式。","cat_life_career","mod_other","sickn33,other","---\nname: temporal-golang-pro\ndescription: \"Use when building durable distributed systems with Temporal Go SDK. Covers deterministic workflow rules, mTLS worker configs, and advanced patterns.\"\nrisk: safe\nsource: self\ndate_added: \"2026-02-27\"\n---\n\n# Temporal Go SDK (temporal-golang-pro)\n\n## Overview\n\nExpert-level guide for building resilient, scalable, and deterministic distributed systems using the Temporal Go SDK. This skill transforms vague orchestration requirements into production-grade Go implementations, focusing on durable execution, strict determinism, and enterprise-scale worker configuration.\n\n## When to Use This Skill\n\n- **Designing Distributed Systems**: When building microservices that require durable state and reliable orchestration.\n- **Implementing Complex Workflows**: Using the Go SDK to handle long-running processes (days\u002Fmonths) or complex Saga patterns.\n- **Optimizing Performance**: When workers need fine-tuned concurrency, mTLS security, or custom interceptors.\n- **Ensuring Reliability**: Implementing idempotent activities, graceful error handling, and sophisticated retry policies.\n- **Maintenance & Evolution**: Versioning running workflows or performing zero-downtime worker updates.\n\n## Do not use this skill when\n\n- Using Temporal with other SDKs (Python, Java, TypeScript) - refer to their specific `-pro` skills.\n- The task is a simple request\u002Fresponse without durability or coordination needs.\n- High-level design without implementation (use `workflow-orchestration-patterns`).\n\n## Step-by-Step Guide\n\n1.  **Gather Context**: Proactively ask for:\n    - Target **Temporal Cluster** (Cloud vs. Self-hosted) and **Namespace**.\n    - **Task Queue** names and expected throughput.\n    - **Security requirements** (mTLS paths, authentication).\n    - **Failure modes** and desired retry\u002Ftimeout policies.\n2.  **Verify Determinism**: Before suggesting workflow code, verify against these **5 Rules**:\n    - No native Go concurrency (goroutines).\n    - No native time (`time.Now`, `time.Sleep`).\n    - No non-deterministic map iteration (must sort keys).\n    - No direct external I\u002FO or network calls.\n    - No non-deterministic random numbers.\n3.  **Implement Incrementally**: Start with shared Protobuf\u002FData classes, then Activities, then Workflows, and finally Workers.\n4.  **Leverage Resources**: If the implementation requires advanced patterns (Sagas, Interceptors, Replay Testing), explicitly refer to the implementation playbook and testing strategies.\n\n## Capabilities\n\n### Go SDK Implementation\n\n- **Worker Management**: Deep knowledge of `worker.Options`, including `MaxConcurrentActivityTaskPollers`, `WorkerStopTimeout`, and `StickyScheduleToStartTimeout`.\n- **Interceptors**: Implementing Client, Worker, and Workflow interceptors for cross-cutting concerns (logging, tracing, auth).\n- **Custom Data Converters**: Integrating Protobuf, encrypted payloads, or custom JSON marshaling.\n\n### Advanced Workflow Patterns\n\n- **Durable Concurrency**: Using `workflow.Go`, `workflow.Channel`, and `workflow.Selector` instead of native primitives.\n- **Versioning**: Implementing safe code evolution using `workflow.GetVersion` and `workflow.GetReplaySafeLogger`.\n- **Large-scale Processing**: Pattern for `ContinueAsNew` to manage history size limits (defaults: 50MB or 50K events).\n- **Child Workflows**: Managing lifecycle, cancellation, and parent-child signal propagation.\n\n### Testing & Observability\n\n- **Testsuite Mastery**: Using `WorkflowTestSuite` for unit and functional testing with deterministic time control.\n- **Mocking**: Sophisticated activity and child workflow mocking strategies.\n- **Replay Testing**: Validating code changes against production event histories.\n- **Metrics**: Configuring Prometheus\u002FOpenTelemetry exporters for worker performance tracking.\n\n## Examples\n\n### Example 1: Versioned Workflow (Deterministic)\n\n```go\n\u002F\u002F Note: imports omitted. Requires 'go.temporal.io\u002Fsdk\u002Fworkflow', 'go.temporal.io\u002Fsdk\u002Ftemporal', and 'time'.\nfunc SubscriptionWorkflow(ctx workflow.Context, userID string) error {\n    \u002F\u002F 1. Versioning for logic evolution (v1 = DefaultVersion)\n    v := workflow.GetVersion(ctx, \"billing_logic\", workflow.DefaultVersion, 2)\n\n    for i := 0; i \u003C 12; i++ {\n        ao := workflow.ActivityOptions{\n            StartToCloseTimeout: 5 * time.Minute,\n            RetryPolicy: &temporal.RetryPolicy{MaximumAttempts: 3},\n        }\n        ctx = workflow.WithActivityOptions(ctx, ao)\n\n        \u002F\u002F 2. Activity Execution (Always handle errors)\n        err := workflow.ExecuteActivity(ctx, ChargePaymentActivity, userID).Get(ctx, nil)\n        if err != nil {\n            workflow.GetLogger(ctx).Error(\"Payment failed\", \"Error\", err)\n            return err\n        }\n\n        \u002F\u002F 3. Durable Sleep (Time-skipping safe)\n        sleepDuration := 30 * 24 * time.Hour\n        if v >= 2 {\n            sleepDuration = 28 * 24 * time.Hour\n        }\n\n        if err := workflow.Sleep(ctx, sleepDuration); err != nil {\n            return err\n        }\n    }\n    return nil\n}\n```\n\n### Example 2: Full mTLS Worker Setup\n\n```go\nfunc RunSecureWorker() error {\n    \u002F\u002F 1. Load Client Certificate and Key\n    cert, err := tls.LoadX509KeyPair(\"client.pem\", \"client.key\")\n    if err != nil {\n        return fmt.Errorf(\"failed to load client keys: %w\", err)\n    }\n\n    \u002F\u002F 2. Load CA Certificate for Server verification (Proper mTLS)\n    caPem, err := os.ReadFile(\"ca.pem\")\n    if err != nil {\n        return fmt.Errorf(\"failed to read CA cert: %w\", err)\n    }\n    certPool := x509.NewCertPool()\n    if !certPool.AppendCertsFromPEM(caPem) {\n        return fmt.Errorf(\"failed to parse CA cert\")\n    }\n\n    \u002F\u002F 3. Dial Cluster with full TLS config\n    c, err := client.Dial(client.Options{\n        HostPort:  \"temporal.example.com:7233\",\n        Namespace: \"production\",\n        ConnectionOptions: client.ConnectionOptions{\n            TLS: &tls.Config{\n                Certificates: []tls.Certificate{cert},\n                RootCAs:      certPool,\n            },\n        },\n    })\n    if err != nil {\n        return fmt.Errorf(\"failed to dial temporal: %w\", err)\n    }\n    defer c.Close()\n\n    w := worker.New(c, \"payment-queue\", worker.Options{})\n    w.RegisterWorkflow(SubscriptionWorkflow)\n\n    if err := w.Run(worker.InterruptCh()); err != nil {\n        return fmt.Errorf(\"worker run failed: %w\", err)\n    }\n    return nil\n}\n```\n\n### Example 3: Selector & Signal Integration\n\n```go\nfunc ApprovalWorkflow(ctx workflow.Context) (string, error) {\n    var approved bool\n    signalCh := workflow.GetSignalChannel(ctx, \"approval-signal\")\n\n    \u002F\u002F Use Selector to wait for multiple async events\n    s := workflow.NewSelector(ctx)\n    s.AddReceive(signalCh, func(c workflow.ReceiveChannel, _ bool) {\n        c.Receive(ctx, &approved)\n    })\n\n    \u002F\u002F Add 72-hour timeout timer\n    s.AddReceive(workflow.NewTimer(ctx, 72*time.Hour).GetChannel(), func(c workflow.ReceiveChannel, _ bool) {\n        approved = false\n    })\n\n    s.Select(ctx)\n\n    if !approved {\n        return \"rejected\", nil\n    }\n    return \"approved\", nil\n}\n```\n\n## Best Practices\n\n- ✅ **Do:** Always handle errors from `ExecuteActivity` and `client.Dial`.\n- ✅ **Do:** Use `workflow.Go` and `workflow.Channel` for concurrency.\n- ✅ **Do:** Sort map keys before iteration to maintain determinism.\n- ✅ **Do:** Use `activity.RecordHeartbeat` for activities lasting > 1 minute.\n- ✅ **Do:** Test logic compatibility using `replayer.ReplayWorkflowHistoryFromJSON`.\n- ❌ **Don't:** Swallow errors with `_` or `log.Fatal` in production workers.\n- ❌ **Don't:** Perform direct Network\u002FDisk I\u002FO inside a Workflow function.\n- ❌ **Don't:** Rely on native `time.Now()` or `rand.Int()`.\n- ❌ **Don't:** Apply this to simple cron jobs that don't require durability.\n\n## Troubleshooting\n\n- **Panic: Determinism Mismatch**: Usually caused by logic changes without `workflow.GetVersion` or non-deterministic code (e.g., native maps).\n- **Error: History Size Exceeded**: History limit reached (default 50K events). Ensure `ContinueAsNew` is implemented.\n- **Worker Hang**: Check `WorkerStopTimeout` and ensure all activities handle context cancellation.\n\n## Limitations\n\n- Does not cover Temporal Cloud UI navigation or TLS certificate provisioning workflows.\n- Does not cover Temporal Java, Python, or TypeScript SDKs; refer to their dedicated `-pro` skills.\n- Assumes Temporal Server v1.20+ and Go SDK v1.25+; older SDK versions may have different APIs.\n- Does not cover experimental Temporal features (e.g., Nexus, Multi-cluster Replication).\n- Does not address global namespace configuration or multi-region failover setup.\n- Does not cover Temporal Worker versioning via the `worker-versioning` feature flag (experimental).\n\n## Resources\n\n- [Implementation Playbook](resources\u002Fimplementation-playbook.md) - Deep dive into Go SDK patterns.\n- [Testing Strategies](resources\u002Ftesting-strategies.md) - Unit, Replay, and Integration testing for Go.\n- [Temporal Go SDK Reference](https:\u002F\u002Fpkg.go.dev\u002Fgo.temporal.io\u002Fsdk)\n- [Temporal Go Samples](https:\u002F\u002Fgithub.com\u002Ftemporalio\u002Fsamples-go)\n\n## Related Skills\n\n- `grpc-golang` - Internal transport protocol and Protobuf design.\n- `golang-pro` - General Go performance tuning and advanced syntax.\n- `workflow-orchestration-patterns` - Language-agnostic orchestration strategy.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,231,"2026-05-16 13:43:31",{"id":8,"name":20,"slug":21,"icon":22,"description":23,"sort":24,"createdAt":25},"其他","other","mdi-page-next-outline","其他类型Skill",5,"2026-05-16 12:53:40",{"id":7,"name":27,"slug":28,"icon":29,"description":30,"moduleId":8,"sort":31,"skillCount":32,"createdAt":25},"职场发展","career","mdi-briefcase-outline","面试准备、简历优化、职业规划",4,575,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":18},"7e9476d9-3204-48bb-a70f-a0f0c03b6cfd","1.0.0","temporal-golang-pro.zip",9263,"uploads\u002Fskills\u002F0cf9e7a8-5e10-4786-be8c-08a812866dc1\u002Ftemporal-golang-pro.zip","aa615a6e859bfde1d9c8a1006b829a916576748ae18401d8df98a8b1bdc1a848","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":9321},{\"path\":\"resources\u002Fimplementation-playbook.md\",\"isDirectory\":false,\"size\":8520},{\"path\":\"resources\u002Ftesting-strategies.md\",\"isDirectory\":false,\"size\":4306}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]