hmn/src/utils/utils.go

123 lines
2.6 KiB
Go
Raw Normal View History

2021-05-05 20:34:32 +00:00
package utils
import (
"context"
"errors"
"fmt"
2021-09-01 18:25:09 +00:00
"math"
"time"
"git.handmade.network/hmn/hmn/src/oops"
)
// Returns the provided value, or a default value if the input was zero.
func OrDefault[T comparable](v T, def T) T {
var zero T
if v == zero {
return def
} else {
return v
}
}
2022-05-12 03:24:05 +00:00
// Takes an (error) return and panics if there is an error.
// Helps avoid `if err != nil` in scripts. Use sparingly in real code.
func Must(err error) {
2022-05-12 03:24:05 +00:00
if err != nil {
panic(err)
}
}
// Takes a (something, error) return and panics if there is an error.
// Helps avoid `if err != nil` in scripts. Use sparingly in real code.
func Must1[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
2021-05-05 20:34:32 +00:00
func IntMin(a, b int) int {
if a < b {
return a
}
return b
}
func IntMax(a, b int) int {
if a > b {
return a
}
return b
}
func IntClamp(min, t, max int) int {
return IntMax(min, IntMin(t, max))
}
2021-08-17 18:48:54 +00:00
func Int64Max(a, b int64) int64 {
if a > b {
return a
}
return b
}
2022-06-17 22:30:18 +00:00
func DurationRoundUp(d time.Duration, interval time.Duration) time.Duration {
return (d + interval - 1).Truncate(interval)
}
2021-09-01 18:25:09 +00:00
func NumPages(numThings, thingsPerPage int) int {
return IntMax(int(math.Ceil(float64(numThings)/float64(thingsPerPage))), 1)
}
/*
Recover a panic and convert it to a returned error. Call it like so:
func MyFunc() (err error) {
defer utils.RecoverPanicAsError(&err)
}
If an error was already present, the panicked error will take precedence. Unfortunately there's
no good way to include both errors because you can't really have two chains of errors and still
play nice with the standard library's Unwrap behavior. But most of the time this shouldn't be an
issue, since the panic will probably occur before a meaningful error value was set.
*/
func RecoverPanicAsError(err *error) {
if r := recover(); r != nil {
var recoveredErr error
if rerr, ok := r.(error); ok {
recoveredErr = rerr
} else {
recoveredErr = fmt.Errorf("panic with value: %v", r)
}
*err = oops.New(recoveredErr, "panic recovered as error")
}
}
var ErrSleepInterrupted = errors.New("sleep interrupted by context cancellation")
func SleepContext(ctx context.Context, d time.Duration) error {
select {
case <-ctx.Done():
return ErrSleepInterrupted
case <-time.After(d):
return nil
}
}
Add Discord login (#106) This leverages our existing Discord OAuth implementation. Any users with a linked Discord account will be able to log in immediately. When logging in, we request the `email` scope in addition to `identity`, so existing users will be prompted one time to accept the new permissions. On subsequent logins, Discord will skip the prompt. When linking your Discord account to an existing HMN account, we continue to only request the `identity` scope, so we do not receive the user's Discord email. Both login and linking go through the same Discord OAuth callback. All flows through the callback try to achieve the same end goal: a logged-in HMN user with a linked Discord account. Linking works the same as it ever has. Login, however, is different because we do not have a session ID to use as the OAuth state. To account for this, I have added a `pending_login` table that stores a secure unique ID and the eventual destination URL. These pending logins expire after 10 minutes. When we receive the OAuth callback, we look up the pending login by the OAuth `state` and immediately delete it. The destination URL will be used to redirect the user to the right place. If we have a `discord_user` entry for the OAuth'd Discord user, we immediately log the user into the associated HMN account. This is the typical login case. If we do not have a `discord_user`, but there is exactly one HMN user with the same email address as the Discord user, we will link the two accounts and log into the HMN account. (It is possible for multiple HMN accounts to have the same email, because we don't have a uniqueness constraint there. We fail the login in this case rather than link to the wrong account.) Finally, if no associated HMN user exists, a new one will be created. It will use the Discord user's username, email, and avatar. This user will have no password, but they can set or reset a password through the usual flows. Co-authored-by: Ben Visness <bvisness@gmail.com> Reviewed-on: https://git.handmade.network/hmn/hmn/pulls/106
2023-05-06 19:38:50 +00:00
// Panics if the provided value is falsy (so, zero). This works for booleans
// but also normal values, through the magic of generics.
func Assert[T comparable](value T, msg ...any) {
var zero T
if value == zero {
finalMsg := ""
for i, arg := range msg {
if i > 0 {
finalMsg += " "
}
finalMsg += fmt.Sprintf("%v", arg)
}
panic(finalMsg)
}
}