-
Notifications
You must be signed in to change notification settings - Fork 80
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
A more configurable URLNotifier #726
Open
itzloop
wants to merge
3
commits into
livekit:main
Choose a base branch
from
itzloop:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
package webhook | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"crypto/sha256" | ||
"encoding/base64" | ||
"github.com/hashicorp/go-retryablehttp" | ||
"github.com/livekit/protocol/auth" | ||
"github.com/livekit/protocol/livekit" | ||
"github.com/livekit/protocol/logger" | ||
"google.golang.org/protobuf/encoding/protojson" | ||
"sync" | ||
"time" | ||
) | ||
|
||
const ( | ||
DefaultBatchSendInterval = 100 * time.Millisecond | ||
DefaultMaxBatchSize = 10000 | ||
) | ||
|
||
type BatchURLNotifierParams struct { | ||
Logger logger.Logger | ||
URL string | ||
Interval time.Duration | ||
MaxSize int | ||
APIKey string | ||
APISecret string | ||
} | ||
|
||
type BatchURLNotifier struct { | ||
cancelFunc context.CancelFunc | ||
client *retryablehttp.Client | ||
mu sync.RWMutex | ||
params BatchURLNotifierParams | ||
batch []*livekit.WebhookEvent | ||
dropped int // it's operated inside a mutex scope so no need for atomic type | ||
} | ||
|
||
func NewBatchURLNotifier(ctx context.Context, params BatchURLNotifierParams) URLNotifier { | ||
if params.Interval == 0 { | ||
params.Interval = DefaultBatchSendInterval | ||
} | ||
if params.MaxSize == 0 { | ||
params.MaxSize = DefaultMaxBatchSize | ||
} | ||
|
||
ctx, cancel := context.WithCancel(ctx) | ||
notifier := &BatchURLNotifier{ | ||
cancelFunc: cancel, | ||
params: params, | ||
client: retryablehttp.NewClient(), | ||
} | ||
|
||
go notifier.runner(ctx) | ||
|
||
return notifier | ||
} | ||
|
||
func (b *BatchURLNotifier) runner(ctx context.Context) { | ||
ticker := time.NewTicker(b.params.Interval) | ||
for { | ||
select { | ||
case <-ticker.C: | ||
b.mu.Lock() | ||
b.sendBatch() | ||
b.mu.Unlock() | ||
case <-ctx.Done(): | ||
return | ||
} | ||
} | ||
} | ||
|
||
func (b *BatchURLNotifier) sendBatch() { | ||
if len(b.batch) == 0 { | ||
return | ||
} | ||
raw := &livekit.BatchedWebhookEvents{ | ||
Events: b.batch, | ||
NumDropped: int32(b.dropped), | ||
DequeuedAt: time.Now().Unix(), | ||
} | ||
defer func() { | ||
b.batch = nil | ||
}() | ||
b.dropped = 0 | ||
|
||
encoded, err := protojson.Marshal(raw) | ||
if err != nil { | ||
b.params.Logger.Warnw("Failed to marshal event", err) | ||
b.dropped += len(b.batch) | ||
return | ||
} | ||
|
||
// sign payload | ||
sum := sha256.Sum256(encoded) | ||
b64 := base64.StdEncoding.EncodeToString(sum[:]) | ||
at := auth.NewAccessToken(b.params.APIKey, b.params.APISecret). | ||
SetValidFor(5 * time.Minute). | ||
SetSha256(b64) | ||
token, err := at.ToJWT() | ||
if err != nil { | ||
b.params.Logger.Warnw("Failed to generate jwt token", err) | ||
b.dropped += len(b.batch) | ||
return | ||
} | ||
|
||
req, err := retryablehttp.NewRequest("POST", b.params.URL, bytes.NewReader(encoded)) | ||
if err != nil { | ||
b.params.Logger.Warnw("Failed to create http req", err) | ||
b.dropped += len(b.batch) | ||
return | ||
} | ||
|
||
req.Header.Set(authHeader, token) | ||
req.Header.Set("batched", "true") | ||
req.Header.Set("content-type", "application/webhook+json") | ||
resp, err := b.client.Do(req) | ||
if err != nil { | ||
b.params.Logger.Errorw("Failed to send request", err) | ||
b.dropped += len(b.batch) | ||
return | ||
} | ||
_ = resp.Body.Close() | ||
|
||
return | ||
} | ||
|
||
func (b *BatchURLNotifier) SetKeys(apiKey, apiSecret string) { | ||
b.mu.Lock() | ||
defer b.mu.Unlock() | ||
b.params.APIKey = apiKey | ||
b.params.APISecret = apiSecret | ||
} | ||
|
||
func (b *BatchURLNotifier) QueueNotify(event *livekit.WebhookEvent) error { | ||
b.mu.Lock() | ||
defer b.mu.Unlock() | ||
b.batch = append(b.batch, event) | ||
|
||
if len(b.batch) >= b.params.MaxSize { | ||
b.sendBatch() | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (b *BatchURLNotifier) Stop(force bool) { | ||
b.cancelFunc() | ||
if !force { | ||
b.mu.Lock() | ||
b.sendBatch() | ||
b.mu.Unlock() | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why is this field needed? what is it intended to communicate to to the end user?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is useful for identifying issues in webhook logic. I have high latency spikes for webhook events, but I don't know how much it took Livekit from when the event was queued until it's been sent.