Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make sure MetricsHandler doesn't crash upon multiple concurrent writes #359

Merged
merged 1 commit into from Oct 28, 2021

Conversation

tadzik
Copy link
Contributor

@tadzik tadzik commented Oct 27, 2021

With heavy traffic, concurrent usage of TrackLoginState() and similar
could result in fatal error: concurrent map read and map write,
crashing the whole process.

The effectiveness of the fix can be observed with this test, which I'm not submitting because of it being an ugly hack:

package main

import (
	"testing"
	"time"

	log "maunium.net/go/maulogger/v2"
)

func TestConcurrentMetricsUpdates(t *testing.T) {
	sut := NewMetricsHandler("0.0.0.0:9876", log.Create(), nil, nil)
	go sut.Start()

	done := false

	go func() {
		for !done {
			go sut.TrackConnectionState("foo@bar.baz", true)
			go sut.TrackConnectionState("foo@bar.baz", false)
		}
	}()

	time.Sleep(5 * time.Second)
	sut.Stop()
	done = true
}

This explodes with the aforementioned message before the patch, survives and passes after.

I had another attempt at this using channels for synchronizing all these writes, but it was a PITA to get right (processing them only after Start() while closing them after Stop() while avoiding writing to closed channels...) that I figured I'd rather keep it simple, especially since the operations themselves are so trivial that the mutex is unlikely to cause any noticable issues anyway.

With heavy traffic, concurrent usage of TrackLoginState() and similar
could result in `fatal error: concurrent map read and map write`,
crashing the whole process.
Copy link
Member

@tulir tulir left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks sensible, thanks!

@tulir tulir merged commit 13cb1e5 into mautrix:master Oct 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants