package pushimport ()// NotificationProcessor defines the interface for push notification processors.typeNotificationProcessorinterface {// GetHandler returns the handler for a specific push notification name.GetHandler(pushNotificationName string) NotificationHandler// ProcessPendingNotifications checks for and processes any pending push notifications. // To be used when it is known that there are notifications on the socket. // It will try to read from the socket and if it is empty - it may block.ProcessPendingNotifications(ctx context.Context, handlerCtx NotificationHandlerContext, rd *proto.Reader) error// RegisterHandler registers a handler for a specific push notification name.RegisterHandler(pushNotificationName string, handler NotificationHandler, protected bool) error// UnregisterHandler removes a handler for a specific push notification name.UnregisterHandler(pushNotificationName string) error}// Processor handles push notifications with a registry of handlerstypeProcessorstruct { registry *Registry}type timeoutError interface { Timeout() bool}func isTimeoutError( error) bool {vartimeoutErrorreturnerrors.As(, &) && .Timeout()}// NewProcessor creates a new push notification processorfunc () *Processor {return &Processor{registry: NewRegistry(), }}// GetHandler returns the handler for a specific push notification namefunc ( *Processor) ( string) NotificationHandler {return .registry.GetHandler()}// RegisterHandler registers a handler for a specific push notification namefunc ( *Processor) ( string, NotificationHandler, bool) error {return .registry.RegisterHandler(, , )}// UnregisterHandler removes a handler for a specific push notification namefunc ( *Processor) ( string) error {return .registry.UnregisterHandler()}// ProcessPendingNotifications checks for and processes any pending push notifications// This method should be called by the client in WithReader before reading the reply// It will try to read from the socket and if it is empty - it may block.func ( *Processor) ( context.Context, NotificationHandlerContext, *proto.Reader) error {return .processPendingNotifications(, , , false)}// ProcessPendingNotificationsBuffered processes one pending push notification// and then continues only through frames already buffered by that read. It is// used by callers that have already established socket readiness and must not// wait for another frame after draining the current batch.func ( *Processor) (context.Context, NotificationHandlerContext, *proto.Reader,) error {return .processPendingNotifications(, , , true)}func ( *Processor) (context.Context,NotificationHandlerContext, *proto.Reader,bool,) error {if == nil {returnnil } := falsefor ! || ! || .Buffered() > 0 {// Check if there's data available to readvarbyteif {for { , := .Peek(1)if != nil {ifisTimeoutError() {returnnil }return } = [0]if != proto.RespAttr {break }// Unlike Peek, DiscardNext consumes bytes. Any error here is // fatal because the reader may be left mid-frame.if := .DiscardNext(); != nil {return } } } else {varerror , = .PeekReplyType()if != nil {// No more data available or error reading.break } }// Only process push notifications (arrays starting with >)if != proto.RespPush {break }// see if we should skip this notification , := .PeekPushNotificationName()if != nil {// A buffered probe stops cleanly when no full frame is available yet.if && isTimeoutError() {returnnil }// The frame is a CONFIRMED push (peeked above) but its name cannot be // peeked — too long, or a non-string / malformed name. Fall through to // ReadReply to CONSUME it. Do NOT break: that leaves the push at the // buffer head for the caller's reply read to eat as the command value // (cache poison / one-frame reply shift). A genuine mid-frame read error // surfaces at ReadReply below (fatal → the reply-expected drain retires // the conn); a non-string name is gracefully ignored (the type assertion // below fails, so no handler runs). } elseifwillHandleNotificationInClient() {break }// Surface a ReadReply error (unlike the boundary peek errors above, // which consumed nothing): it happens mid-frame after bytes are // consumed, so the conn is desynced and the CSC drainer must remove it. // Normal reply-read callers log-and-ignore this and let their own read fail. , := .ReadReply()if != nil {internal.Logger.Printf(, "push: error reading push notification: %v", )return } = true// Convert to slice of interfaces , := .([]interface{})if ! {break }// Handle the notification directlyiflen() > 0 {// Extract the notification type (first element)if , := [0].(string); {// Get the handler for this notification typeif := .registry.GetHandler(); != nil {// Handle the notification := .HandlePushNotification(, , )if != nil {internal.Logger.Printf(, "push: error handling push notification: %v", ) } } } } }returnnil}// VoidProcessor discards all push notifications without processing themtypeVoidProcessorstruct{}// NewVoidProcessor creates a new void push notification processorfunc () *VoidProcessor {return &VoidProcessor{}}// GetHandler returns nil for void processor since it doesn't maintain handlersfunc ( *VoidProcessor) ( string) NotificationHandler {returnnil}// RegisterHandler returns an error for void processor since it doesn't maintain handlersfunc ( *VoidProcessor) ( string, NotificationHandler, bool) error {returnErrVoidProcessorRegister()}// UnregisterHandler returns an error for void processor since it doesn't maintain handlersfunc ( *VoidProcessor) ( string) error {returnErrVoidProcessorUnregister()}// ProcessPendingNotifications for VoidProcessor does nothing since push notifications// are only available in RESP3 and this processor is used for RESP2 connections.// This avoids unnecessary buffer scanning overhead.// It does however read and discard all push notifications from the buffer to avoid// them being interpreted as a reply.// This method should be called by the client in WithReader before reading the reply// to be sure there are no buffered push notifications.// It will try to read from the socket and if it is empty - it may block.func ( *VoidProcessor) ( context.Context, NotificationHandlerContext, *proto.Reader) error {// read and discard all push notificationsif == nil {returnnil }for {// Check if there's data available to read , := .PeekReplyType()if != nil {// No more data available or error reading // if timeout, it will be handled by the callerbreak }// Only process push notifications (arrays starting with >)if != proto.RespPush {break }// see if we should skip this notification , := .PeekPushNotificationName()if != nil {// Name too long to peek: still consume the frame below so it isn't // misread as a reply.if !errors.Is(, proto.ErrPushNotificationNameTooLong) {break } } elseifwillHandleNotificationInClient() {break }// Read the push notification _, = .ReadReply()if != nil {internal.Logger.Printf(context.Background(), "push: error reading push notification: %v", )returnnil } }returnnil}// willHandleNotificationInClient checks if a notification type should be ignored by the push notification// processor and handled by other specialized systems instead (pub/sub, streams, keyspace, etc.).func willHandleNotificationInClient( string) bool {switch {// Pub/Sub notifications - handled by pub/sub systemcase"message", // Regular pub/sub message"pmessage", // Pattern pub/sub message"subscribe", // Subscription confirmation"unsubscribe", // Unsubscription confirmation"psubscribe", // Pattern subscription confirmation"punsubscribe", // Pattern unsubscription confirmation"smessage", // Sharded pub/sub message (Redis 7.0+)"ssubscribe", // Sharded subscription confirmation"sunsubscribe": // Sharded unsubscription confirmationreturntruedefault:returnfalse }}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.