Skip to content

Conversation

oliverpool
Copy link
Contributor

@oliverpool oliverpool commented Apr 1, 2025

I am using the opcua server in tests, with a short-lived context. I sometimes get a panic, because msg is nil.

This PR prevents this.

The diff may look large when whitespaces are not ignored, because I removed an indentation (ctx.Err() is more concise than select{<-ctx.Done;default} and more "left-aligned"). diff ignoring whitespaces

BTW: thanks for this huge package!!

@magiconair
Copy link
Member

Glad that you like it and that it is useful :)

Regarding the PR: this doesn't look right. Contexts are checked through the Done channel usually in a select statement.

Why don't you just add the if msg == nil { continue } statement here?

image

@oliverpool
Copy link
Contributor Author

Why don't you just add the if msg == nil { continue } statement here?

This is done:
image

After doing this, I simplified the for loop from:

	for {
		select {
		case <-ctx.Done():
			return
		default:
			// do something
		}
	}

to:

	for ctx.Err() == nil {
		// do something
	}

This should be correct according to https://pkg.go.dev/context#Context:

If Done is not yet closed, Err returns nil.
If Done is closed, Err returns a non-nil error explaining why:

ctx.Err() is a essentially a non-blocking way to check if a context is done.

@magiconair
Copy link
Member

You are right. Since ReadMessage() blocks we don't create a busy loop. Just a bit wary when I see patterns I haven't seen before.

@magiconair magiconair added this to the v0.7.2 milestone Apr 7, 2025
@magiconair magiconair merged commit 8c72b97 into gopcua:main Apr 7, 2025
5 checks passed
@oliverpool oliverpool deleted the prevent-panic-ctx-cancel branch April 7, 2025 10:50
@magiconair magiconair modified the milestones: v0.7.2, v0.7.3 Apr 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants