Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion base/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ const (
// How long to wait for response headers once a request has been written.
DefaultHttpResponseHeaderTimeout = 30 * time.Second

// DefaultClientPartitionWindow is the metadata purge interval that Sync Gateway uses when it cannot read one from
// the bucket, so it is also the client partition window when client_partition_window_secs is not set.
DefaultClientPartitionWindow = time.Hour * 24 * 30

// Number of kv connections (pipelines) per Couchbase Server node
DefaultGocbKvPoolSize = 2

Expand Down Expand Up @@ -198,7 +202,6 @@ var (
DefaultWarnThresholdChannelsPerUser = uint32(50000)
DefaultWarnThresholdGrantsPerDoc = uint32(50)
DefaultWarnThresholdChannelNameSize = uint32(250)
DefaultClientPartitionWindow = time.Hour * 24 * 30

// ErrUnknownField is marked as the cause of the error when trying to decode a JSON snippet with unknown fields
ErrUnknownField = errors.New("unrecognized JSON field")
Expand Down
35 changes: 25 additions & 10 deletions db/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,7 @@ const (
DefaultRevsLimitNoConflicts = 50
DefaultRevsLimitConflicts = 100

// DefaultPurgeInterval represents a time duration of 30 days to be
// used as default metadata purge interval when the server’s purge
// interval (either bucket specific or cluster wide) is not available.
DefaultPurgeInterval = 30 * 24 * time.Hour
DefaultVersionPruningWindow = DefaultPurgeInterval
DefaultVersionPruningWindow = base.DefaultClientPartitionWindow
DefaultSGReplicateEnabled = true
DefaultSGReplicateWebsocketPingInterval = time.Minute * 5
DefaultCompactInterval = 24 * time.Hour
Expand Down Expand Up @@ -220,7 +216,7 @@ type DatabaseContextOptions struct {
SlowQueryWarningThreshold time.Duration
QueryPaginationLimit int // Limit used for pagination of queries. If not set defaults to DefaultQueryPaginationLimit
UserXattrKey string // Key of user xattr that will be accessible from the Sync Function. If empty the feature will be disabled.
ClientPartitionWindow time.Duration
ClientPartitionWindow *time.Duration
BcryptCost int
GroupID string
JavascriptTimeout time.Duration // Max time the JS functions run for (ie. sync fn, import filter)
Expand Down Expand Up @@ -644,6 +640,9 @@ func NewDatabaseContext(ctx context.Context, dbName string, bucket base.Bucket,
}
dbContext.DBStateManager = NewDatabaseStateMgr(metadataStore, metaKeys.DatabaseStateKey(), joinResync)

// Fill the purge interval cache before any request can run, so that later callers do not read Bucket during Close.
dbContext.GetMetadataPurgeInterval(ctx, true)

return dbContext, nil
}

Expand Down Expand Up @@ -1032,7 +1031,7 @@ func (context *DatabaseContext) Authenticator(ctx context.Context) *auth.Authent

// Authenticators are lightweight & stateless, so it's OK to return a new one every time
authenticator := auth.NewAuthenticator(context.MetadataStore, context, auth.AuthenticatorOptions{
ClientPartitionWindow: context.Options.ClientPartitionWindow,
ClientPartitionWindow: context.ClientPartitionWindow(),
Comment thread
bbrks marked this conversation as resolved.
Resolved
ChannelsWarningThreshold: channelsWarningThreshold,
SessionCookieName: sessionCookieName,
BcryptCost: context.Options.BcryptCost,
Expand Down Expand Up @@ -1757,14 +1756,15 @@ func (db *DatabaseContext) GetMetadataPurgeInterval(ctx context.Context, forceRe
// fetch from server
cbStore, ok := base.AsCouchbaseBucketStore(db.Bucket)
if !ok {
return DefaultPurgeInterval
db.CachedPurgeInterval.Store(new(base.DefaultClientPartitionWindow))
return base.DefaultClientPartitionWindow
}
serverPurgeInterval, err := cbStore.MetadataPurgeInterval(ctx)
if err != nil {
base.WarnfCtx(ctx, "Unable to retrieve server's metadata purge interval - using default purge interval %.2f days. %s", DefaultPurgeInterval.Hours()/24, err)
base.WarnfCtx(ctx, "Unable to retrieve server's metadata purge interval - using default purge interval %.2f days. %s", base.DefaultClientPartitionWindow.Hours()/24, err)
}

mpi := DefaultPurgeInterval
mpi := base.DefaultClientPartitionWindow
if serverPurgeInterval > 0 {
mpi = serverPurgeInterval
}
Expand Down Expand Up @@ -2800,3 +2800,18 @@ func (db *DatabaseContext) collections(names base.CollectionNames) (DatabaseColl
}
return collections, nil
}

// ClientPartitionWindow returns client_partition_window_secs if set, otherwise the cached metadata purge
// interval. It never fetches from the bucket, so request paths can call it at any time.
func (db *DatabaseContext) ClientPartitionWindow() time.Duration {
if w := db.Options.ClientPartitionWindow; w != nil {
return *w
}
if o := db.Options.TestPurgeIntervalOverride; o != nil {
return *o
}
if mpi := db.CachedPurgeInterval.Load(); mpi != nil {
return *mpi
}
return base.DefaultClientPartitionWindow
}
3 changes: 1 addition & 2 deletions docs/api/components/schemas.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1208,9 +1208,8 @@ Database:
description: |-
How long (in seconds) clients can remain offline for without losing replication metadata.

Defaults to 30 days (in seconds)
If this is not set, Sync Gateway uses the metadata purge interval of the bucket. If the bucket has no purge interval of its own, Sync Gateway uses the cluster-wide value.
Comment thread
RIT3shSapata marked this conversation as resolved.
Resolved
type: integer
default: 2592000
compact_interval_days:
description: |-
The interval between scheduled tombstone compaction runs (in days). This can be a floating point number.
Expand Down
2 changes: 2 additions & 0 deletions rest/admin_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,7 @@ func (h *handler) handleGetDbConfig() error {
if err != nil {
return err
}
setRuntimeClientPartitionWindow(responseConfig, h.db.DatabaseContext)
}

// defensive check - there could've been an in-flight request to remove the database between entering the handler and getting the config above.
Expand Down Expand Up @@ -705,6 +706,7 @@ func (h *handler) handleGetConfig() error {
if err != nil {
return err
}
setRuntimeClientPartitionWindow(dbConfig, database)

if database.SGReplicateMgr != nil {
replications, err := database.SGReplicateMgr.GetReplications()
Expand Down
2 changes: 1 addition & 1 deletion rest/adminapitest/admin_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3790,7 +3790,7 @@ func TestTombstoneCompactionPurgeInterval(t *testing.T) {
{
name: "Default purge interval updated after db creation",
newServerInterval: "1",
dbPurgeInterval: db.DefaultPurgeInterval,
dbPurgeInterval: base.DefaultClientPartitionWindow,
expectedPurgeIntervalAfterCompact: time.Hour * 24,
},
{
Expand Down
96 changes: 96 additions & 0 deletions rest/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4509,3 +4509,99 @@ func TestLocalEndpointForPublicAPI(t *testing.T) {
})
}
}

// TestDefaultClientPartitionWindow makes sure that the database config reports client_partition_window_secs when it is
// set, and reports the server purge interval only with include_runtime when it is not set.
func TestDefaultClientPartitionWindow(t *testing.T) {
// Rosmar always returns base.DefaultClientPartitionWindow as the purge interval, so the default cases cannot tell
// the server purge interval apart from the fallback there.
if sgtest.UnitTestUrlIsWalrus() {
t.Skip("Test requires Couchbase Server")
}
base.RequireNumTestBuckets(t, 2)
ctx := base.TestCtx(t)

rt1 := NewRestTester(t, nil)
Comment thread
Copilot marked this conversation as resolved.
Resolved
defer rt1.Close()
rt2 := NewRestTester(t, &RestTesterConfig{PersistentConfig: true})
defer rt2.Close()

serverPurgeIntervalSecs := func(rt *RestTester) int {
cbStore, ok := base.AsCouchbaseBucketStore(rt.Bucket())
require.True(t, ok)
purgeInterval, err := cbStore.MetadataPurgeInterval(ctx)
require.NoError(t, err)
return int(purgeInterval.Seconds())
}

// Non-persistent config has no bootstrap credentials, so the database config must carry the bucket credentials.
rt1DbConfig := rt1.NewDbConfig()
rt1DbConfig.Username, rt1DbConfig.Password, _ = rt1.TestBucket.BucketSpec.Auth.GetCredentials()

testers := []struct {
name string
rt *RestTester
dbConfig DbConfig
purgeInterval int
}{
{name: "non-persistent config", rt: rt1, dbConfig: rt1DbConfig, purgeInterval: serverPurgeIntervalSecs(rt1)},
{name: "persistent config", rt: rt2, dbConfig: rt2.NewDbConfig(), purgeInterval: serverPurgeIntervalSecs(rt2)},
}

// rt1 creates a database at startup, so remove it to let each test case create its own. This also closes the
// test bucket of rt1, which is why the configs and purge intervals above are read first.
RequireStatus(t, rt1.SendAdminRequest(http.MethodDelete, "/db/", ""), http.StatusOK)

explicitWindow := int((7 * 24 * time.Hour).Seconds())
for _, tester := range testers {
tests := []struct {
name string
clientPartition int // 0 leaves client_partition_window_secs unset
includeRuntime bool
expectedValue int // 0 means that the config must not report client_partition_window_secs
}{
{name: "explicit value with include_runtime", clientPartition: explicitWindow, includeRuntime: true, expectedValue: explicitWindow},
{name: "explicit value without include_runtime", clientPartition: explicitWindow, includeRuntime: false, expectedValue: explicitWindow},
{name: "default value with include_runtime", includeRuntime: true, expectedValue: tester.purgeInterval},
{name: "default value without include_runtime", includeRuntime: false},
}
t.Run(tester.name, func(t *testing.T) {
rt := tester.rt
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
dbConfig := tester.dbConfig
if test.clientPartition != 0 {
dbConfig.ClientPartitionWindowSecs = new(test.clientPartition)
}
RequireStatus(t, rt.CreateDatabase("db", dbConfig), http.StatusCreated)
defer func() {
RequireStatus(t, rt.SendAdminRequest(http.MethodDelete, "/db/", ""), http.StatusOK)
}()

resp := rt.SendAdminRequest(http.MethodGet, fmt.Sprintf("/db/_config?include_runtime=%t", test.includeRuntime), "")
RequireStatus(t, resp, http.StatusOK)
var cfg DbConfig
require.NoError(t, base.JSONUnmarshal(resp.BodyBytes(), &cfg))

if test.expectedValue == 0 {
assert.Nil(t, cfg.ClientPartitionWindowSecs)
} else {
require.NotNil(t, cfg.ClientPartitionWindowSecs)
assert.Equal(t, test.expectedValue, *cfg.ClientPartitionWindowSecs)
}

// The server-level config lists the databases only with include_runtime.
if test.includeRuntime {
resp = rt.SendAdminRequest(http.MethodGet, "/_config?include_runtime=true", "")
RequireStatus(t, resp, http.StatusOK)
var serverCfg RunTimeServerConfigResponse
require.NoError(t, base.JSONUnmarshal(resp.BodyBytes(), &serverCfg))
require.Contains(t, maps.Keys(serverCfg.Databases), "db")
require.NotNil(t, serverCfg.Databases["db"].ClientPartitionWindowSecs)
assert.Equal(t, test.expectedValue, *serverCfg.Databases["db"].ClientPartitionWindowSecs)
}
})
}
})
}
}
2 changes: 1 addition & 1 deletion rest/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ type DbConfig struct {
ServeInsecureAttachmentTypes *bool `json:"serve_insecure_attachment_types,omitempty"` // Attachment content type will bypass the content-disposition handling, default false
QueryPaginationLimit *int `json:"query_pagination_limit,omitempty"` // Query limit to be used during pagination of large queries
UserXattrKey *string `json:"user_xattr_key,omitempty"` // Key of user xattr that will be accessible from the Sync Function. If empty or nil the feature will be disabled.
ClientPartitionWindowSecs *int `json:"client_partition_window_secs,omitempty"` // How long clients can remain offline for without losing replication metadata. Default 30 days (in seconds)
ClientPartitionWindowSecs *int `json:"client_partition_window_secs,omitempty"` // How long clients can remain offline for without losing replication metadata (in seconds). Defaults to the metadata purge interval of the bucket.
Guest *auth.PrincipalConfig `json:"guest,omitempty"` // Guest user settings
JavascriptTimeoutSecs *uint32 `json:"javascript_timeout_secs,omitempty"` // The amount of seconds a Javascript function can run for. Set to 0 for no timeout.
UserFunctions *functions.FunctionsConfig `json:"functions,omitempty"` // Named JS fns for clients to call
Expand Down
8 changes: 7 additions & 1 deletion rest/config_database.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ func MergeDatabaseConfigWithDefaults(sc *StartupConfig, dbConfig *DbConfig) (*Db
return defaultDbConfig, nil
}

// setRuntimeClientPartitionWindow sets the window that the database uses when the config does not set one.
func setRuntimeClientPartitionWindow(config *DbConfig, database *db.DatabaseContext) {
if config.ClientPartitionWindowSecs == nil {
config.ClientPartitionWindowSecs = new(int(database.ClientPartitionWindow().Seconds()))
}
}

// DefaultDbConfig provides a DbConfig with all the default values populated. Used with MergeDatabaseConfigWithDefaults
// to provide defaults to include_runtime config endpoints.
// Note that this does not include unsupported options
Expand Down Expand Up @@ -184,7 +191,6 @@ func DefaultDbConfig(sc *StartupConfig) *DbConfig {
ServeInsecureAttachmentTypes: new(false),
QueryPaginationLimit: new(db.DefaultQueryPaginationLimit),
UserXattrKey: nil,
ClientPartitionWindowSecs: new(int(base.DefaultClientPartitionWindow.Seconds())),
Guest: &auth.PrincipalConfig{Disabled: new(true)},
JavascriptTimeoutSecs: new(base.DefaultJavascriptTimeoutSecs),
ChangesRequestPlus: new(false),
Expand Down
41 changes: 21 additions & 20 deletions rest/config_database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,26 +43,27 @@ func TestDefaultDbConfigFieldCoverage(t *testing.T) {
// When adding a field here, add a comment explaining why it doesn't need a default.
intentionallyUnsetFields := map[string]string{
// Embedded struct - fields checked separately
"BucketConfig": "embedded struct, fields checked separately",
"Scopes": "opt-in with no default",
"Replications": "opt-in with no default",
"UserFunctions": "opt-in with no default",
"OIDCConfig": "opt-in with no default",
"LocalJWTConfig": "opt-in with no default",
"CORS": "opt-in with no default",
"EventHandlers": "opt-in with no default",
"ImportFilter": "opt-in with no default",
"UserXattrKey": "opt-in with no default",
"Name": "stamped at runtime",
"UpdatedAt": "persisted timestamp",
"CreatedAt": "persisted timestamp",
"Unsupported": "unsupported",
"DeprecatedRevCacheSize": "deprecated",
"NumIndexReplicas": "deprecated",
"FeedType": "deprecated",
"Suspendable": "deprecated",
"Users": "legacy config",
"Roles": "legacy config",
"BucketConfig": "embedded struct, fields checked separately",
"Scopes": "opt-in with no default",
"Replications": "opt-in with no default",
"UserFunctions": "opt-in with no default",
"OIDCConfig": "opt-in with no default",
"LocalJWTConfig": "opt-in with no default",
"CORS": "opt-in with no default",
"EventHandlers": "opt-in with no default",
"ImportFilter": "opt-in with no default",
"UserXattrKey": "opt-in with no default",
"ClientPartitionWindowSecs": "defaults to the bucket metadata purge interval, which only the running database knows",
"Name": "stamped at runtime",
"UpdatedAt": "persisted timestamp",
"CreatedAt": "persisted timestamp",
"Unsupported": "unsupported",
"DeprecatedRevCacheSize": "deprecated",
"NumIndexReplicas": "deprecated",
"FeedType": "deprecated",
"Suspendable": "deprecated",
"Users": "legacy config",
"Roles": "legacy config",
}
if !base.IsEnterpriseEdition() {
intentionallyUnsetFields["ImportPartitions"] = "set only in EE"
Expand Down
4 changes: 2 additions & 2 deletions rest/server_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -1527,9 +1527,9 @@ func dbcOptionsFromConfig(ctx context.Context, sc *ServerContext, config *DbConf
userXattrKey = *config.UserXattrKey
}

clientPartitionWindow := base.DefaultClientPartitionWindow
var clientPartitionWindow *time.Duration
if config.ClientPartitionWindowSecs != nil {
clientPartitionWindow = time.Duration(*config.ClientPartitionWindowSecs) * time.Second
clientPartitionWindow = new(time.Duration(*config.ClientPartitionWindowSecs) * time.Second)
}

bcryptCost := sc.Config.Auth.BcryptCost
Expand Down
Loading