////////////////////////////////////////////////////////////////////// // // Your video processing service has a freemium model. Everyone has 10 // sec of free processing time on your service. After that, the // service will kill your process, unless you are a paid premium user. // // Beginner Level: 10s max per request // Advanced Level: 10s max per user (accumulated) // package main import ( "sync" "time" ) const MAX_SECONDS = 10 // User defines the UserModel. Use this to check whether a User is a // Premium user or not type User struct { ID int IsPremium bool TimeUsed int64 // in seconds mu sync.Mutex } // HandleRequest runs the processes requested by users. Returns false // if process had to be killed func HandleRequest(process func(), u *User) bool { finished := make(chan bool) // unfortunately we won't be able to kill the goroutine. // So a call to process() may exceeds MAX_SECONDS duration. go func() { process() finished <- true }() select { case <-finished: return true case <-time.After(MAX_SECONDS * time.Second): if u.IsPremium { <-finished return true } u.mu.Lock() u.TimeUsed += MAX_SECONDS u.mu.Unlock() return false } } func main() { RunMockServer() }