Thuta Learning
Go
AdvancedProgrammingအခြေခံ

Context, Timeouts & Cancellation

Goသင်ခန်းစာ 2240 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • context.Background() ကနေ WithCancel, WithTimeout နဲ့ child context တွေ ဆင့်ပွားပြီး parent/child ဆက်နွယ်မှုကို ရှင်းပြနိုင်ဖို့
  • ctx.Done() ကို select ထဲမှာ စောင့်ပြီး ctx.Err() က Canceled ဒါမှမဟုတ် DeadlineExceeded ပြန်ပေးတာကို ခွဲခြားနိုင်ဖို့
  • Context ဖန်တီးတိုင်း defer cancel() ကို ဘာကြောင့် ချက်ချင်း ရေးရလဲ ရှင်းပြနိုင်ဖို့
  • WithCancelCause နဲ့ ရပ်ရတဲ့ အကြောင်းရင်းကို မှတ်ပြီး context.Cause နဲ့ ပြန်ဖတ်နိုင်ဖို့
  • Context ကို ပထမ parameter အဖြစ် လက်ဆင့်ကမ်းပြီး cancellation ကို တကယ် စစ်တဲ့ code ရေးနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Context ကို ရိုးရိုးလေး ပြောရရင်

context.Context ဆိုတာ အလုပ်တစ်ခုကို 'ရပ်တော့' လို့ ပြောနိုင်တဲ့ အချက်ပြ ကြိုးတစ်ချောင်းပါ။ Request တစ်ခု ဝင်လာတဲ့အခါ context တစ်ခု ဖန်တီးပြီး အဲဒီ request အတွက် ခေါ်တဲ့ function တိုင်းကို လက်ဆင့်ကမ်း ပေးပါတယ်။ User က page ကို ပိတ်လိုက်တာ ဒါမှမဟုတ် သတ်မှတ်ထားတဲ့ အချိန် ကုန်သွားတာနဲ့ ကြိုးကို ဆွဲလိုက်ပြီး ကြိုးနဲ့ ချိတ်ထားတဲ့ အလုပ်အားလုံးက ရပ်ရမယ်ဆိုတာ သိသွားပါတယ်။

Taxi ငှားတာနဲ့ နှိုင်းယှဉ်ကြည့်ပါ။ 'လေဆိပ်ကို ၃၀ မိနစ်အတွင်း ရောက်ရမယ်၊ မရောက်နိုင်ရင် ကျွန်တော် ဆင်းမယ်' လို့ ပြောထားတာက deadline ပါ။ ခရီးသည်က လမ်းခုလတ်မှာ 'ရပ်ပါ' လို့ ပြောတာက cancel ပါ။ ဒါပေမဲ့ driver က နားထောင်မှပဲ ကားရပ်ပါတယ် — context ကလည်း အလုပ်ကို အတင်း မရပ်ပေးပါဘူး၊ code ကိုယ်တိုင်က signal ကို စစ်ပြီး ရပ်ရပါတယ်။

Problem → Why → Solution

ပြဿနာ: ဘယ်သူမှ မစောင့်တော့တဲ့ အလုပ်

Report page တစ်ခုက database query တစ်ခုကို run ပြီး အဲဒီ query က စက္ကန့် ၃၀ လောက် ကြာပါတယ်။ User က ၅ စက္ကန့်အကြာမှာ စောင့်ရတာ ငြီးငွေ့လို့ tab ကို ပိတ်ပြီး refresh ကို ဆယ်ခါလောက် နှိပ်ပါတယ်။ Server ဘက်မှာတော့ ဘယ်သူမှ မဖတ်တော့တဲ့ query ဆယ်ခုက database connection တွေကို ဆက်ကိုင်ထားပြီး တခြား user တွေရဲ့ request တွေ နှေးလာပါတယ်။

report.go
func reportHandler(w http.ResponseWriter, r *http.Request) {
	// r.Context() is ignored: the query keeps running even after
	// the client has disconnected
	rows, err := db.Query("SELECT customer, SUM(total) FROM orders GROUP BY 1")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	// ...
}

ဘာကြောင့် context လိုတာလဲ

Goroutine တစ်ခုကို အပြင်ကနေ အတင်း သတ်လို့ မရပါဘူး၊ အဲဒါ ကိုယ်တိုင် ရပ်မှ ရပ်ပါတယ်။ ဒါကြောင့် 'ရပ်ရမယ့် အချိန်ရောက်ပြီ' ဆိုတဲ့ သတင်းကို call chain တစ်လျှောက် ပို့ပေးမယ့် စံနည်းလမ်း တစ်ခု လိုပါတယ်။ net/http က client ချိတ်ဆက်မှု ပြတ်တာနဲ့ r.Context() ကို cancel လုပ်ပေးပြီး database/sql ရဲ့ QueryContext က အဲဒီ signal ကို နားထောင်ပါတယ်။ Context ကို လက်ဆင့်ကမ်းမှပဲ နှစ်ဖက် ချိတ်ဆက်မိပါတယ်။

Core concept: context tree, Done, Err နဲ့ Cause

Context တွေက tree တစ်ပင် ဖွဲ့ပါတယ်။ အမြစ်က context.Background() ဖြစ်ပြီး WithCancel(parent), WithTimeout(parent, d), WithDeadline(parent, t) တို့က parent ကနေ child context အသစ်နဲ့ cancel function တစ်ခုကို ပြန်ပေးပါတယ်။ Parent ကို cancel လုပ်ရင် သူ့အောက်က descendant အားလုံး cancel ဖြစ်ပါတယ်၊ child ကို cancel လုပ်တာကတော့ parent ကို ဘာမှ မထိခိုက်ပါဘူး။ ဒါကြောင့် request တစ်ခုလုံးရဲ့ context အောက်မှာ database call တစ်ခုအတွက် ပိုတိုတဲ့ timeout ကို လုံခြုံစွာ ထပ်ထည့်လို့ ရပါတယ်။

ctx.Done() က context ပြီးဆုံးတဲ့အခါ close ဖြစ်မယ့် channel ကို ပြန်ပေးတဲ့အတွက် select ထဲမှာ တခြား channel တွေနဲ့ အတူ စောင့်လို့ ရပါတယ်။ ctx.Err() က context အသက်ရှင်နေစဉ် nil ဖြစ်ပြီး cancel ပြီးရင် context.Canceled၊ deadline ကျော်ရင် context.DeadlineExceeded ကို ပြန်ပေးပါတယ်။ Context က ဘာကိုမှ ကိုယ်တိုင် မရပ်ပေးပါဘူး — cooperative cancellation ဖြစ်လို့ function က Done ကို စောင့်တာ၊ Err ကို စစ်တာ ဒါမှမဟုတ် ctx ကို လက်ခံတဲ့ API (QueryContext, NewRequestWithContext) ဆီ ဆက်ပို့တာ လုပ်မှပဲ အလုပ်ဖြစ်ပါတယ်။

ConstructorContext ဘယ်အချိန် ပြီးလဲ
WithCancel(parent)cancel() ခေါ်တဲ့အခါ ဒါမှမဟုတ် parent ပြီးတဲ့အခါ
WithTimeout(parent, d)d ကြာသွားတဲ့အခါ၊ cancel() ဒါမှမဟုတ် parent ပြီးတဲ့အခါ
WithDeadline(parent, t)နာရီက t ကို ရောက်တဲ့အခါ (ကျန်တာ WithTimeout နဲ့ တူ)
WithCancelCause(parent)cancel(err) ခေါ်တဲ့အခါ၊ err ကို context.Cause က ပြန်ပေး

Context ဖန်တီးတဲ့ line ရဲ့ နောက်မှာ defer cancel() ကို ချက်ချင်း ရေးပါ။ Cancel က timer ကို ရပ်ပြီး parent ထဲက child ရဲ့ reference ကို ဖယ်ပေးတဲ့အတွက် အလုပ် စောစော ပြီးသွားရင်တောင် ခေါ်ရပါမယ်၊ မခေါ်ရင် parent ပြီးတဲ့အထိ resource တွေ ကျန်နေပါတယ်။ go vet ရဲ့ lostcancel check က မေ့သွားတဲ့ cancel ကို သတိပေးပါတယ်။ Cancel ကို အကြိမ်ကြိမ် ခေါ်တာ ဘေးကင်းပါတယ်၊ ဒုတိယအကြိမ်ကစပြီး ဘာမှ မလုပ်ပါဘူး။

ctx.Err() က 'canceled' လို့ပဲ ပြောပြီး ဘာကြောင့်လဲ မပြောပါဘူး။ WithCancelCause(parent) က error တစ်ခု လက်ခံတဲ့ cancel function ကို ပြန်ပေးပြီး cancel(err) နဲ့ ရပ်ရတဲ့ အကြောင်းရင်းကို မှတ်ထားနိုင်ပါတယ်။ ctx.Err() က context.Canceled ဆက်ဖြစ်နေပေမဲ့ context.Cause(ctx) က အဲဒီ err ကို ပြန်ပေးပါတယ်။ Cause မှတ်မထားတဲ့ context အတွက်တော့ context.Cause က ctx.Err() နဲ့ အတူတူ ပြန်ပေးပါတယ်။

Context ကို ဆင့်ကဲ ပွားတဲ့ tree လို မြင်ကြည့်ပါ
  1. Background() ကနေ context ကို derive
  2. ချက်ချင်း defer cancel()
  3. ctx ကို ပထမ parameter အဖြစ် ပို့
  4. Worker က ctx.Done() ကို select
  5. ctx.Err() / context.Cause ကို ပြန်ပေး

Cancel signal က tree ရဲ့ အောက်ဘက်ကိုပဲ စီးပါတယ်၊ child က parent ကို ဘယ်တော့မှ မရပ်စေပါဘူး။

အထွေထွေ ပုံစံ

go
ctx, cancel := context.WithTimeout(parent, limit)
defer cancel()

func doWork(ctx context.Context, input Input) (Output, error) {
	select {
	case out := <-resultOf(input):
		return out, nil
	case <-ctx.Done():
		return Output{}, ctx.Err() // Canceled or DeadlineExceeded
	}
}

Context ကို parent ကနေ derive လုပ်ပြီး cancel ကို ချက်ချင်း defer လုပ်ပါ။ အလုပ်လုပ်တဲ့ function က ctx ကို ပထမ parameter အဖြစ် လက်ခံပြီး result ဒါမှမဟုတ် ctx.Done() ဘယ်ဟာ အရင်လာလာ စောင့်ကာ context ပြီးရင် ctx.Err() ကို ပြန်ပေးပါတယ်။

Worked example: cancel ပြီးသား context ကို စစ်ခြင်း

ဒါက context cancellation ရဲ့ အသေးဆုံး ပုံစံပါ။ WithCancel နဲ့ context ဖန်တီးပြီး select မတိုင်ခင် cancel() ကို ခေါ်လိုက်တဲ့အတွက် Done channel က ပိတ်ပြီးသား ဖြစ်နေပါတယ်။ ဒါကြောင့် select က Done case ကို ရွေးပြီး context canceled ကို print ထုတ်ပါတယ်။ cancel() line ကို ဖယ်လိုက်ရင် Done မပိတ်သေးလို့ default case က working ကို print ထုတ်ပါလိမ့်မယ် — default ပါတဲ့ select က context ကို မစောင့်ဘဲ 'ရပ်ခိုင်းထားပြီလား' လို့ မေးကြည့်တဲ့ နည်းလမ်း ဖြစ်ပါတယ်။

go
package main

import (
    "context"
    "fmt"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    cancel()
    select {
    case <-ctx.Done(): fmt.Println(ctx.Err())
    default: fmt.Println("working")
    }
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Derive a cancellable contextctx, cancel := context.WithCancel(context.Background())

    Background() က ဘယ်တော့မှ cancel မဖြစ်တဲ့ အမြစ် context ပါ။ WithCancel က အဲဒီအောက်မှာ child context နဲ့ အဲဒါကို ရပ်မယ့် cancel function ကို ပြန်ပေးပါတယ်။

  2. Cancel itcancel()

    Done channel ကို close လုပ်ပြီး Err ကို context.Canceled အဖြစ် သတ်မှတ်ပါတယ်။ ဒီ example မှာ ချက်ချင်း ခေါ်ထားပေမဲ့ လက်တွေ့ code မှာ defer cancel() လို့ ရေးပြီး တခြား goroutine ဒါမှမဟုတ် event တစ်ခုက စောစော ခေါ်လေ့ ရှိပါတယ်။

  3. Done is closed, so this case runscase <-ctx.Done(): fmt.Println(ctx.Err())

    ပိတ်ပြီးသား channel ကနေ receive က ချက်ချင်း အောင်မြင်တဲ့အတွက် ဒီ case က အဆင်သင့် ဖြစ်နေပါတယ်။ ctx.Err() ရဲ့ string form က context canceled ဖြစ်ပါတယ်။

  4. Non-blocking fallbackdefault: fmt.Println("working")

    Context မပြီးသေးရင် default က run ပြီး select က မစောင့်ပါဘူး။ Loop တစ်ခုရဲ့ iteration တိုင်းမှာ 'ဆက်လုပ်ရမလား' လို့ စစ်တဲ့အခါ ဒီပုံစံ (ဒါမှမဟုတ် if ctx.Err() != nil) ကို သုံးပါတယ်။

You should see
context canceled

WithTimeout: နှေးနေတဲ့ dependency ကို အချိန်ကန့်သတ်ခြင်း

query က result ဒါမှမဟုတ် ctx.Done() ဘယ်ဟာ အရင်လာလာ စောင့်ပါတယ်။ lookup တစ်ခါခေါ်တိုင်း 80ms timeout ပါတဲ့ context အသစ် ဖန်တီးပြီး defer cancel() နဲ့ ရှင်းပါတယ် — loop ထဲမှာ defer တိုက်ရိုက် မရေးဘဲ helper function ထဲ ထည့်ထားတာက iteration တိုင်းမှာ cancel ချက်ချင်း run စေဖို့ပါ။ 10ms query က အချိန်မီ ပြီးပြီး 200ms query ကတော့ deadline ကို ကျော်ပါတယ်။

timeout.go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

// query pretends to talk to a database that needs cost to answer.
func query(ctx context.Context, cost time.Duration) (string, error) {
	select {
	case <-time.After(cost):
		return "3 rows", nil
	case <-ctx.Done():
		return "", fmt.Errorf("query: %w", ctx.Err())
	}
}

func lookup(cost time.Duration) {
	ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
	defer cancel() // release the timer even when query finishes early

	rows, err := query(ctx, cost)
	if errors.Is(err, context.DeadlineExceeded) {
		fmt.Println(cost, "->", err)
		return
	}
	fmt.Println(cost, "->", rows)
}

func main() {
	lookup(10 * time.Millisecond)
	lookup(200 * time.Millisecond)
}

Output က 10ms -> 3 rows နဲ့ 200ms -> query: context deadline exceeded ဖြစ်ပါတယ်။ query က ctx.Err() ကို %w နဲ့ wrap လုပ်ထားလို့ err == context.DeadlineExceeded က false ဖြစ်ပေမဲ့ errors.Is ကတော့ wrap ထားတဲ့ chain ကို လိုက်ရှာပြီး true ပြန်ပေးပါတယ်။

WithCancelCause: ဘာကြောင့် ရပ်ရလဲ မှတ်ထားခြင်း

အောက်က program မှာ parent context ကို ErrTabClosed အကြောင်းရင်းနဲ့ cancel လုပ်ပါတယ်။ Child context ကလည်း parent ကနေ ဆင့်ပွားထားလို့ အလိုအလျောက် cancel ဖြစ်ပြီး နှစ်ခုလုံးရဲ့ Err က context canceled ဖြစ်ကာ Cause ကတော့ user closed the tab ဖြစ်ပါတယ်။

cause.go
package main

import (
	"context"
	"errors"
	"fmt"
)

var ErrTabClosed = errors.New("user closed the tab")

func main() {
	ctx, cancel := context.WithCancelCause(context.Background())
	child, stop := context.WithCancel(ctx) // derived from ctx
	defer stop()

	cancel(ErrTabClosed) // cancelling the parent also cancels the child

	<-child.Done()
	fmt.Println("child err:  ", child.Err())
	fmt.Println("parent err: ", ctx.Err())
	fmt.Println("cause:      ", context.Cause(ctx))
	fmt.Println("child cause:", context.Cause(child))
	fmt.Println(errors.Is(context.Cause(ctx), ErrTabClosed))
}

child ရဲ့ cause ကလည်း user closed the tab ဖြစ်တာကို သတိထားပါ — parent ကြောင့် cancel ဖြစ်တဲ့ context က parent ရဲ့ cause ကို အမွေဆက်ခံပါတယ်။ Logging မှာ ctx.Err() အစား context.Cause(ctx) ကို ရေးရင် 'canceled' ဆိုတဲ့ စကားလုံးထက် အဓိပ္ပာယ်ရှိတဲ့ အကြောင်းရင်းကို ရပါတယ်။

HTTP handler မှာ context ကို ဆက်ပို့ခြင်း

Problem section ထဲက handler ကို ပြင်ဖို့ r.Context() ကို parent အဖြစ် သုံးပြီး query အတွက် timeout ထပ်ထည့်ကာ QueryContext ဆီ ပို့ပါ။ ဒါဆိုရင် client ချိတ်ဆက်မှု ပြတ်တာ ဒါမှမဟုတ် ၂ စက္ကန့် ကျော်တာ ဘယ်ဟာ အရင်ဖြစ်ဖြစ် query ရပ်ပါတယ်။ ဒီ snippet က database တစ်ခု လိုလို့ ဒီမှာ run မထားပါဘူး။

report.go
func reportHandler(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
	defer cancel()

	rows, err := db.QueryContext(ctx, "SELECT customer, SUM(total) FROM orders GROUP BY 1")
	if errors.Is(err, context.DeadlineExceeded) {
		http.Error(w, "report took too long", http.StatusGatewayTimeout)
		return
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	// ...
}

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ context

Go server code မှာ I/O လုပ်တဲ့ function တိုင်းနီးပါးက ctx context.Context ကို ပထမ parameter အဖြစ် လက်ခံပါတယ်။ Request တစ်ခုရဲ့ context က handler ကနေ database, cache, အပြင် API call တွေအထိ တစ်ဆက်တည်း စီးဆင်းပြီး တစ်နေရာမှာ ပြတ်ရင် ကျန်တာ အားလုံး ရပ်ပါတယ်။

  • Incoming request: net/http ရဲ့ Request.Context() က client ချိတ်ဆက်မှု ပိတ်တာ ဒါမှမဟုတ် ServeHTTP return ပြန်တာနဲ့ cancel ဖြစ်ပါတယ်။
  • Outgoing call: http.NewRequestWithContext နဲ့ ဖန်တီးထားတဲ့ request က context ပြီးတာနဲ့ abort ဖြစ်ပြီး database/sql ရဲ့ QueryContext, ExecContext တို့လည်း အလားတူပါ။
  • Service အကြား: gRPC လို framework တွေက deadline ကို service တစ်ခုကနေ နောက်တစ်ခုဆီ ဆက်ပို့လို့ ကျန်တဲ့ အချိန်ထက် ပိုမစောင့်ပါဘူး။
  • Graceful shutdown: signal.NotifyContext က Ctrl+C ရောက်တာနဲ့ cancel ဖြစ်မယ့် context ကို ပေးပြီး server.Shutdown(ctx) က အဲဒီလို context နဲ့ in-flight request တွေကို အချိန်ကန့်သတ်ပြီး စောင့်ပါတယ်။

အမှားများ

Context နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

cancel ကို မခေါ်ခြင်း

ctx, _ := context.WithTimeout(...) လို cancel ကို လွှင့်ပစ်ရင် အလုပ် ပြီးသွားပေမဲ့ timer နဲ့ parent ထဲက reference က deadline ရောက်တဲ့အထိ ကျန်နေပါတယ်။ Request တစ်ခုချင်းစီမှာ ဖြစ်ရင် memory တဖြည်းဖြည်း တက်လာပါတယ်။ go vet က ဒါကို the cancel function is not used လို့ သတိပေးပါတယ်၊ ဖန်တီးတဲ့ line နောက်မှာ defer cancel() ကို ချက်ချင်း ရေးပါ။

ctx ကို လက်ခံပြီး ဘယ်တော့မှ မစစ်ခြင်း

func work(ctx context.Context) ထဲမှာ time.Sleep ပါတဲ့ loop တစ်ခုပဲ ရှိရင် timeout ကျော်သွားလည်း function က loop အဆုံးအထိ ဆက် run ပါတယ်။ Context က cooperative ဖြစ်လို့ loop iteration တိုင်းမှာ ctx.Err() ကို စစ်ပါ၊ စောင့်ရတဲ့ နေရာတွေမှာ sleep အစား select နဲ့ ctx.Done() ကို တွဲစောင့်ပါ။

Call chain အလယ်မှာ context.Background() နဲ့ ကြိုးပြတ်ခြင်း

Handler ထဲက helper function တစ်ခုက r.Context() ကို လက်မခံဘဲ context.Background() ကို ကိုယ်တိုင် ဖန်တီးရင် client ထွက်သွားလည်း အဲဒီအောက်က query တွေ ဆက် run ပါတယ်။ ctx ကို အပေါ်ကနေ လက်ဆင့်ကမ်းပါ၊ Background() ကို main, test နဲ့ request မရှိတဲ့ background job တွေမှာပဲ သုံးပါ။ ဘယ် context သုံးရမလဲ မသေချာသေးရင် context.TODO() ကို placeholder အဖြစ် သုံးပါ၊ nil ကို ဘယ်တော့မှ မပို့ပါနဲ့။

Wrap လုပ်ထားတဲ့ error ကို == နဲ့ နှိုင်းယှဉ်ခြင်း

fmt.Errorf("query: %w", ctx.Err()) လို wrap လုပ်ပြီးနောက် err == context.DeadlineExceeded က false ဖြစ်ပါတယ်။ errors.Is(err, context.DeadlineExceeded) ကို အမြဲ သုံးပါ။

Best Practices

Best practices

  • ctx context.Context ကို function ရဲ့ ပထမ parameter အဖြစ် ထားပြီး struct field ထဲ မသိမ်းပါနဲ့။
  • Context ဖန်တီးတိုင်း နောက် line မှာ defer cancel() ကို ရေးပါ။
  • context.WithValue ကို request ID လို request-scoped data အတွက်ပဲ သုံးပါ၊ optional parameter အစား မသုံးပါနဲ့။
  • Log ထဲမှာ ctx.Err() အစား context.Cause(ctx) ကို ရေးပြီး ရပ်ရတဲ့ အကြောင်းရင်းကို ပြပါ။

Mini challenge

Mini challenge: record import ကို အကြောင်းရင်းနဲ့ ရပ်ခြင်း

Record list တစ်ခုကို import လုပ်တဲ့ importAll ကို ရေးပါ။ Loop ရဲ့ အစတိုင်းမှာ context ကို စစ်ပြီး record အလွတ်တစ်ခု တွေ့ရင် ErrBadRecord ကို wrap လုပ်ထားတဲ့ cause နဲ့ context ကို cancel လုပ်ရပါမယ်။ ဒါ့အပြင် timeout context ကို လေးစားတဲ့ slowStep ကိုလည်း ရေးပါ။

  • main က WithCancelCause နဲ့ context ဖန်တီးပြီး defer cancel(nil) ရေးရမယ်
  • importAll က loop အစတိုင်းမှာ ctx.Err() ကို စစ်ပြီး import လုပ်ပြီးသား အရေအတွက်ကို ပြန်ပေးရမယ်
  • Record အလွတ်အတွက် fmt.Errorf နဲ့ %w သုံးပြီး ErrBadRecord ကို cause အဖြစ် ပေးရမယ်
  • slowStep က select နဲ့ time.After(d) ဒါမှမဟုတ် ctx.Done() ကို စောင့်ပြီး context.Cause(ctx) ကို ပြန်ပေးရမယ်
import.go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

var ErrBadRecord = errors.New("bad record")

// importAll imports records until it is done or ctx is cancelled.
func importAll(
	ctx context.Context, cancel context.CancelCauseFunc, records []string,
) int {
	// TODO: loop over records; stop if ctx.Err() != nil
	// TODO: on an empty record, cancel with a cause wrapping ErrBadRecord
	// TODO: return how many records were imported
	return 0
}

// slowStep waits for d unless ctx ends first.
func slowStep(ctx context.Context, d time.Duration) error {
	// TODO: select on time.After(d) and ctx.Done()
	return nil
}

func main() {
	// TODO: WithCancelCause + defer cancel(nil); import 4 records where the
	//       third is ""; print the count, ctx.Err() and context.Cause(ctx)
	// TODO: WithTimeout(50ms) + defer; call slowStep with 200ms and print
	//       the error and errors.Is(err, context.DeadlineExceeded)
	fmt.Println("todo")
}

ရလဒ်: imported: 2, err: context canceled, cause: record 3: bad record, bad record? true ပြီးနောက် slow step: context deadline exceeded true ကို print ထုတ်ပါမယ်။

အရိပ်အမြွက် ကြည့်ရန်

cancel(fmt.Errorf("record %d: %w", n, ErrBadRecord)) ပြီးနောက် loop ရဲ့ နောက် turn မှာ ctx.Err() က nil မဟုတ်တော့လို့ ရပ်ပါတယ်။ Timeout context အတွက် context.Cause က context.DeadlineExceeded ကို ပြန်ပေးပါတယ်။

အဖြေ ကြည့်ရန်
import.go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

var ErrBadRecord = errors.New("bad record")

// importAll processes records until it finishes, hits a bad record, or
// ctx is cancelled. It returns how many records it imported.
func importAll(
	ctx context.Context, cancel context.CancelCauseFunc, records []string,
) int {
	done := 0
	for _, r := range records {
		if err := ctx.Err(); err != nil {
			return done // stop before starting more work
		}
		if r == "" {
			cancel(fmt.Errorf("record %d: %w", done+1, ErrBadRecord))
			continue // the next loop turn sees ctx.Err() and stops
		}
		done++
	}
	return done
}

// slowStep waits for d or for ctx, whichever comes first.
func slowStep(ctx context.Context, d time.Duration) error {
	select {
	case <-time.After(d):
		return nil
	case <-ctx.Done():
		return context.Cause(ctx)
	}
}

func main() {
	ctx, cancel := context.WithCancelCause(context.Background())
	defer cancel(nil)
	n := importAll(ctx, cancel, []string{"ada", "linus", "", "grace"})
	fmt.Println("imported:", n)
	fmt.Println("err:", ctx.Err())
	fmt.Println("cause:", context.Cause(ctx))
	fmt.Println("bad record?", errors.Is(context.Cause(ctx), ErrBadRecord))

	tctx, tcancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer tcancel()
	err := slowStep(tctx, 200*time.Millisecond)
	fmt.Println("slow step:", err, errors.Is(err, context.DeadlineExceeded))
}

Quick Quiz 1 / 3

parent ကနေ child, stop := context.WithCancel(parent) ကို ဖန်တီးပြီး stop() ကို ခေါ်ပါတယ်။ parent.Err() က ဘာလဲ?

Quick Quiz 2 / 3

func work(ctx context.Context) { for i := 0; i < 10; i++ { time.Sleep(100 * time.Millisecond) } } ကို 150ms timeout ပါတဲ့ context နဲ့ ခေါ်ပါတယ်။ work က ဘယ်လောက်ကြာ run မလဲ?

Quick Quiz 3 / 3

ctx, cancel := context.WithCancelCause(bg) ပြီးနောက် cancel(ErrQuota) ကို ခေါ်ပါတယ်။ ctx.Err() နဲ့ context.Cause(ctx) က ဘာ ပြန်ပေးလဲ?

မှတ်ထားရမယ့် အချက်များ

  • Context တွေက Background() ကနေ ဆင့်ပွားတဲ့ tree ဖွဲ့ပြီး cancel က အောက်ဘက်ကိုပဲ စီးပါတယ်။
  • ctx.Done() ကို select ထဲမှာ စောင့်ပြီး ctx.Err() က Canceled ဒါမှမဟုတ် DeadlineExceeded ကို ပြန်ပေးပါတယ်၊ wrap ထားရင် errors.Is နဲ့ စစ်ပါ။
  • Context ဖန်တီးတိုင်း defer cancel() ကို ချက်ချင်း ရေးပါ၊ go vet က မေ့သွားတာကို သတိပေးပါတယ်။
  • Cancellation က cooperative ဖြစ်လို့ function တွေက ctx ကို စစ်ရမယ် ဒါမှမဟုတ် ctx လက်ခံတဲ့ API ဆီ ဆက်ပို့ရမယ်။
  • WithCancelCause နဲ့ context.Cause က 'ဘာကြောင့် ရပ်ရလဲ' ကို ctx.Err() ရဲ့ contract မပျက်ဘဲ မှတ်ထားပေးပါတယ်။

Go Concurrency Patterns: Context — Go

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Context, Timeouts & Cancellation | Thuta Learning