package redis

import (
	
	
	

	
	
	
)

// himportFieldset is the client-side record of a fieldset registered with
// HImportPrepare.
type himportFieldset struct {
	fields  []string
	version uint64
}

// himportRegistry remembers fieldsets registered through a client so HIMPORT
// SET can lazily prepare them on whichever pooled connection it executes.
// Versions increase monotonically and start at 1; re-registering a name under
// a new version invalidates every connection's prepared flag for it, so a
// replaced fieldset is re-prepared before its next use.
//
// Discards propagate lazily as well: a discarded name is kept as a tombstone
// and the discard-all counter as an epoch, and connections whose sessions
// still hold discarded fieldsets replay HIMPORT DISCARD/DISCARDALL before
// their next HIMPORT command (see baseClient.himportInjectedCmds).
type himportRegistry struct {
	mu          sync.RWMutex
	nextVersion uint64
	fieldsets   map[string]himportFieldset
	// tombstones holds names discarded through this client whose server-side
	// copies may survive on pooled connections that prepared them. An entry
	// is removed when the name is registered again (the new version replaces
	// the fieldset on the server, so no discard is needed) or by discardAll.
	// Known limitation: a workload discarding many uniquely-named fieldsets
	// grows this map for the client's lifetime and pays an O(tombstones)
	// snapshot per HIMPORT round trip; HImportDiscardAll resets it.
	tombstones map[string]struct{}
	// discardAllEpoch increments on every successful HImportDiscardAll.
	discardAllEpoch uint64
}

func newHImportRegistry() *himportRegistry {
	return &himportRegistry{}
}

// register stores the fieldset and returns its new version together with the
// current discard-all epoch.
func ( *himportRegistry) ( string,  []string) (,  uint64) {
	.mu.Lock()
	defer .mu.Unlock()
	if .fieldsets == nil {
		.fieldsets = make(map[string]himportFieldset)
	}
	delete(.tombstones, )
	.nextVersion++
	.fieldsets[] = himportFieldset{
		fields:  append([]string(nil), ...),
		version: .nextVersion,
	}
	return .nextVersion, .discardAllEpoch
}

func ( *himportRegistry) ( string) (himportFieldset, bool) {
	if  == nil {
		return himportFieldset{}, false
	}
	.mu.RLock()
	,  := .fieldsets[]
	.mu.RUnlock()
	return , 
}

// discard removes the fieldset and leaves a tombstone so connections whose
// sessions still hold it replay the DISCARD before their next HIMPORT
// command. It reports whether the fieldset was registered.
func ( *himportRegistry) ( string) bool {
	.mu.Lock()
	defer .mu.Unlock()
	if ,  := .fieldsets[]; ! {
		return false
	}
	delete(.fieldsets, )
	if .tombstones == nil {
		.tombstones = make(map[string]struct{})
	}
	.tombstones[] = struct{}{}
	return true
}

// discardAll drops every fieldset and tombstone and moves to a new epoch;
// connections prepared under an older epoch replay HIMPORT DISCARDALL before
// their next HIMPORT command. It returns the new epoch and the number of
// fieldsets that were registered.
func ( *himportRegistry) () ( uint64,  int) {
	.mu.Lock()
	 = len(.fieldsets)
	.fieldsets = nil
	.tombstones = nil
	.discardAllEpoch++
	 = .discardAllEpoch
	.mu.Unlock()
	return , 
}

// discardVersion withdraws a registration whose fan-out PREPARE was rejected
// by a server — but only while the entry is still at that version, so a
// concurrent re-registration is not clobbered. A tombstone is left: the
// fan-out may have succeeded on some masters before another rejected it
// (per-node ACLs, rolling upgrades), and those sessions hold the withdrawn
// fieldset; the tombstone makes their next HIMPORT command discard it
// instead of leaving a fieldset the client can no longer address.
func ( *himportRegistry) ( string,  uint64) {
	.mu.Lock()
	if ,  := .fieldsets[];  && .version ==  {
		delete(.fieldsets, )
		if .tombstones == nil {
			.tombstones = make(map[string]struct{})
		}
		.tombstones[] = struct{}{}
	}
	.mu.Unlock()
}

// refreshVersion bumps a registered fieldset to a new version, keeping its
// fields — but only while the entry is still at the given version, so a
// concurrent re-registration is not disturbed. Every connection's prepared
// flag becomes stale, forcing a re-prepare before the fieldset's next use on
// each of them. Used when a "no such fieldset" reply signals session loss
// that may have hit more connections than the one that reported it (failover,
// cross-region switch, reset storms).
func ( *himportRegistry) ( string,  uint64) {
	.mu.Lock()
	if ,  := .fieldsets[];  && .version ==  {
		.nextVersion++
		.version = .nextVersion
		.fieldsets[] = 
	}
	.mu.Unlock()
}

// idle reports whether the registry implies no injection work at all: no
// fieldsets to replay, no tombstones to discard, and no discard-all epoch a
// session could be behind.
func ( *himportRegistry) () bool {
	if  == nil {
		return true
	}
	.mu.RLock()
	 := len(.fieldsets) == 0 && len(.tombstones) == 0 && .discardAllEpoch == 0
	.mu.RUnlock()
	return 
}

// cleanupSnapshot returns the current epoch and the tombstoned names.
func ( *himportRegistry) () ( uint64,  []string) {
	.mu.RLock()
	 = .discardAllEpoch
	if len(.tombstones) > 0 {
		 = make([]string, 0, len(.tombstones))
		for  := range .tombstones {
			 = append(, )
		}
	}
	.mu.RUnlock()
	return , 
}

// himportNoSuchFieldset reports whether err is the server's "no such
// fieldset" reply, i.e. an HIMPORT SET executed on a connection whose session
// does not hold the referenced fieldset.
func himportNoSuchFieldset( error) bool {
	return isRedisError() && strings.Contains(.Error(), "no such fieldset")
}

// himportInjectedCmds returns the HIMPORT commands to write to cn ahead of a
// batch, in order:
//
//  1. HIMPORT DISCARDALL when cn's session was prepared under an older
//     discard-all epoch;
//  2. HIMPORT DISCARD for each discarded fieldset the session still holds;
//  3. HIMPORT PREPARE for each registered fieldset referenced by an HIMPORT
//     SET in the batch that the session lacks at the current version.
//
// A fieldset covered by a user-issued PREPARE earlier in the batch needs no
// injection — the server session holds it by the time the SET runs. Returns
// nil when the batch contains no HIMPORT commands: sessions holding only
// discarded fieldsets are cleaned up on their next HIMPORT use, not on
// unrelated traffic.
func ( *baseClient) ( context.Context,  *pool.Conn,  []Cmder) []Cmder {
	if .himport.idle() {
		return nil
	}
	 := false
	for ,  := range  {
		if ,  := .(himportCmder);  {
			 = true
			break
		}
	}
	if ! {
		return nil
	}

	var  []Cmder

	// Discards first: a session behind the discard-all epoch is wiped
	// entirely; otherwise individual tombstoned fieldsets it still holds are
	// discarded.
	,  := .himport.cleanupSnapshot()
	 := false
	if .HasPreparedFieldsets() && .FieldsetEpoch() !=  {
		 := NewHImportDiscardAllCmd()
		.registryEpoch = 
		 = append(, )
		 = true
	} else {
		for ,  := range  {
			if .FieldsetPreparedVersion() != 0 {
				 = append(, NewHImportDiscardCmd(, ))
			}
		}
	}

	// Prepares for registered fieldsets the batch's SETs reference.
	var  map[string]struct{}
	 := func( string) {
		if  == nil {
			 = make(map[string]struct{})
		}
		[] = struct{}{}
	}
	for ,  := range  {
		switch hc := .(type) {
		case *HImportPrepareCmd:
			(.fieldsetName)
		case *HImportSetCmd:
			if ,  := [.fieldsetName];  {
				continue
			}
			,  := .himport.lookup(.fieldsetName)
			if ! {
				continue
			}
			if ! && .FieldsetPreparedVersion(.fieldsetName) == .version {
				continue
			}
			// The session holds an older version. Discard it before the
			// re-prepare: the SET behind it is already on the wire, and if
			// the re-prepare fails the SET must answer "no such fieldset"
			// rather than silently writing the old version's field names.
			if ! && .FieldsetPreparedVersion(.fieldsetName) != 0 {
				 = append(, NewHImportDiscardCmd(, .fieldsetName))
			}
			 := NewHImportPrepareCmd(, .fieldsetName, .fields...)
			.registryVersion = .version
			.registryEpoch = 
			 = append(, )
			(.fieldsetName)
		}
	}
	return 
}

// himportReadInjectedReplies consumes the replies of injected HIMPORT
// commands. Server errors are recorded on the command and the connection is
// left readable; transport errors are returned. Successful commands apply
// their prepared-flag bookkeeping on cn.
func ( *baseClient) ( context.Context,  *pool.Conn,  *proto.Reader,  []Cmder) error {
	for ,  := range  {
		if  := .processPendingPushNotificationWithReader(, , );  != nil {
			internal.Logger.Printf(, "push: error processing pending notifications before reading reply: %v", )
		}
		 := .readReply()
		.SetErr()
		if  != nil {
			if !isRedisError() {
				return 
			}
			// A failed injected PREPARE becomes the root cause of the
			// dependent SETs' errors downstream; a failed injected discard
			// only delays cleanup until the next HIMPORT command.
			internal.Logger.Printf(, "himport: injected %s failed: %v", .Name(), )
			continue
		}
		switch hc := .(type) {
		case *HImportPrepareCmd:
			.MarkFieldsetPrepared(.fieldsetName, .registryVersion, .registryEpoch)
		case *HImportDiscardCmd:
			.UnmarkFieldsetPrepared(.fieldsetName)
		case *HImportDiscardAllCmd:
			.ClearPreparedFieldsets(.registryEpoch)
		}
	}
	return nil
}

// himportAfterCmd applies registry and prepared-flag updates after a
// user-issued HIMPORT command completed successfully on cn.
func ( *baseClient) ( *pool.Conn,  himportCmder) {
	if .himport == nil {
		return
	}
	switch cmd := .(type) {
	case *HImportPrepareCmd:
		,  := .registryVersion, .registryEpoch
		if  == 0 {
			,  = .himport.register(.fieldsetName, .fields)
		}
		// A pre-assigned version marks a fan-out copy: the fieldset was
		// registered once at the cluster/ring level; only mark the
		// executing connection.
		.MarkFieldsetPrepared(.fieldsetName, , )
	case *HImportDiscardCmd:
		 := .himport.discard(.fieldsetName)
		.UnmarkFieldsetPrepared(.fieldsetName)
		// The managed API reports the registry lifecycle: 1 when the
		// fieldset was registered on this client and is now removed. The
		// executing connection's session count stands only for fieldsets
		// the registry never knew (raw usage).
		if  {
			.SetVal(1)
		}
	case *HImportDiscardAllCmd:
		// A pre-assigned epoch marks a fan-out copy: the registry was
		// already wiped at the cluster/ring level; only move the executing
		// connection to that epoch.
		if .registryEpoch != 0 {
			.ClearPreparedFieldsets(.registryEpoch)
			return
		}
		,  := .himport.discardAll()
		.ClearPreparedFieldsets()
		// Same registry semantics: report how many registered fieldsets
		// were removed, not how many the executing session happened to
		// hold.
		if  > 0 {
			.SetVal(int64())
		}
	}
}

// himportAfterBatch runs after all replies of a batch were read: it surfaces
// an injected PREPARE failure as the root cause on the HIMPORT SET commands
// that depended on it (their own reply is the secondary "no such fieldset"
// error), invalidates stale prepared flags for SETs that found their
// registered fieldset missing server-side, and applies registry updates for
// user-issued HIMPORT commands that succeeded in the batch.
// rawErr throughout: this runs on the execution path, before an async
// autopipeline batch completes (its ready channel closes only after the
// pipeline hook chain returns) — Err() on a user command would await and
// self-deadlock the dispatcher.
func ( *baseClient) ( *pool.Conn,  []Cmder,  []Cmder) {
	var  map[string]error
	var  map[string]struct{}
	for ,  := range  {
		if ,  := .(*HImportPrepareCmd);  {
			if  := .Err();  != nil {
				if  == nil {
					 = make(map[string]error)
				}
				[.fieldsetName] = 
			}
		}
	}
	for ,  := range  {
		,  := .(himportCmder)
		if ! {
			continue
		}
		if ,  := .(*HImportSetCmd);  {
			if ,  := [.fieldsetName];  && himportNoSuchFieldset(.rawErr()) {
				.SetErr()
				continue
			}
			// The session lost a fieldset the flags claim is prepared (e.g.
			// RESET) — and the same event may have wiped other sessions
			// whose flags also still look current. Bump the fieldset
			// version once so the SET's re-issue, the cluster re-queue on
			// whichever connection it lands, or the caller's transaction
			// retry replays the PREPARE.
			if himportNoSuchFieldset(.rawErr()) {
				if ,  := [.fieldsetName]; ! {
					if  == nil {
						 = make(map[string]struct{})
					}
					[.fieldsetName] = struct{}{}
					if ,  := .himport.lookup(.fieldsetName);  {
						.himport.refreshVersion(.fieldsetName, .version)
					}
				}
			}
			continue
		}
		if .rawErr() == nil {
			.himportAfterCmd(, )
		}
	}
}

// himportRetryFailedSets re-issues, once, the HIMPORT SET commands of a
// pipeline batch that failed with "no such fieldset" while their fieldset is
// registered — the error must not surface for managed fieldsets (NF.4). Only
// the SETs are re-sent: HIMPORT SET is a full replace, so re-execution is
// idempotent, and no other command of the batch runs again. Their prepared
// flags were invalidated by himportAfterBatch, so himportInjectedCmds
// regenerates the PREPAREs for this connection. Transport errors are
// returned; server errors stay recorded on the commands.
// (The retry does not carry an ASKING prefix. A redirected [ASKING, SET]
// pair whose injected PREPARE failed is excluded by the root-cause swap in
// himportAfterBatch; one that lost its session without an injection can be
// re-issued here, and the bare SET then draws a fresh MOVED/ASK that the
// outer cluster redirect handling resolves.)
func ( *baseClient) ( context.Context,  *pool.Conn,  []Cmder) error {
	if .himport.idle() {
		return nil
	}
	var  []Cmder
	for ,  := range  {
		// rawErr: execution path, same self-deadlock rule as himportAfterBatch.
		if ,  := .(*HImportSetCmd);  && himportNoSuchFieldset(.rawErr()) {
			if ,  := .himport.lookup(.fieldsetName);  {
				 = append(, )
			}
		}
	}
	if len() == 0 {
		return nil
	}

	 := .himportInjectedCmds(, , )
	if  := .WithWriter(.context(), .opt.WriteTimeout, func( *proto.Writer) error {
		for ,  := range  {
			if  := writeCmd(, );  != nil {
				return 
			}
		}
		return writeCmds(, )
	});  != nil {
		return 
	}
	return .WithReader(.context(), .opt.ReadTimeout, func( *proto.Reader) error {
		if  := .himportReadInjectedReplies(, , , );  != nil {
			return 
		}
		 := .pipelineReadCmds(, , , )
		if  != nil && !isRedisError() {
			return 
		}
		// Server errors (including a repeated failure) stay on the
		// individual commands; the batch as a whole is done.
		.himportAfterBatch(, , )
		return nil
	})
}

// himportShouldRetrySet reports whether a retry of cmd may succeed after it
// failed with "no such fieldset": true when the fieldset is registered
// client-side — the executing connection lost its server session state (for
// example a RESET, or a concurrent discard). The connection's prepared flag
// was already invalidated inside _process, while that goroutine still owned
// the connection, so the retry re-prepares lazily wherever it lands.
func ( *baseClient) ( Cmder,  error) bool {
	,  := .(*HImportSetCmd)
	if ! || !himportNoSuchFieldset() {
		return false
	}
	,  := .himport.lookup(.fieldsetName)
	return 
}