From 94e713269d569617de45839cc4b2cde2c5a887c5 Mon Sep 17 00:00:00 2001 From: Frode Sundby Date: Wed, 18 Nov 2026 08:09:08 +0100 Subject: [PATCH 1/2] feat(postgres): add clone command for point-in-time recovery nais postgres clone creates a new database from the source's backups in the same team and environment. The source is not changed and no applications are moved. --at selects the point in time, as a local time like "2026-11-16 12:00" or RFC 3339 with an offset. Without it the clone is made from the latest available point, 10 minutes ago, to stay inside archived WAL. A local time skipped by a daylight saving change is rejected and a repeated one resolves to its earlier occurrence. PostgreSQL version and extensions come from the source. High availability, CPU, memory and disk default to the source's and can be overridden; the disk cannot be smaller than the source's. get now reports the clone source, point and status. Update the GraphQL schema from the live API. --- internal/naisapi/gql/generated.go | 229 ++++++++++++++++++ internal/postgres/clone.go | 31 +++ internal/postgres/command/clone.go | 213 +++++++++++++++++ internal/postgres/command/clone_test.go | 303 ++++++++++++++++++++++++ internal/postgres/command/flag/flag.go | 9 + internal/postgres/command/get.go | 32 +++ internal/postgres/command/postgres.go | 1 + internal/postgres/get.go | 1 + internal/postgres/instance.go | 1 + schema.graphql | 98 +++++++- 10 files changed, 917 insertions(+), 1 deletion(-) create mode 100644 internal/postgres/clone.go create mode 100644 internal/postgres/command/clone.go create mode 100644 internal/postgres/command/clone_test.go diff --git a/internal/naisapi/gql/generated.go b/internal/naisapi/gql/generated.go index c4c16427..dc381c6f 100644 --- a/internal/naisapi/gql/generated.go +++ b/internal/naisapi/gql/generated.go @@ -1190,6 +1190,8 @@ type CreatePostgresInput struct { DiskSize *string `json:"diskSize,omitempty"` // Input for creating a Postgres. Labels []ResourceLabelInput `json:"labels"` + // Input for creating a Postgres. + Recovery *PostgresRecoveryInput `json:"recovery,omitempty"` } // GetName returns CreatePostgresInput.Name, and is useful for accessing the field via an interface. @@ -1222,6 +1224,9 @@ func (v *CreatePostgresInput) GetDiskSize() *string { return v.DiskSize } // GetLabels returns CreatePostgresInput.Labels, and is useful for accessing the field via an interface. func (v *CreatePostgresInput) GetLabels() []ResourceLabelInput { return v.Labels } +// GetRecovery returns CreatePostgresInput.Recovery, and is useful for accessing the field via an interface. +func (v *CreatePostgresInput) GetRecovery() *PostgresRecoveryInput { return v.Recovery } + // CreatePostgresResponse is returned by CreatePostgres on success. type CreatePostgresResponse struct { // Create a new Postgres database. @@ -11345,6 +11350,105 @@ func (v *GetApplicationStatusTeamApplicationsApplicationConnectionNodesApplicati return v.Name } +// GetCloneSourceResponse is returned by GetCloneSource on success. +type GetCloneSourceResponse struct { + // Get a team by its slug. + Team GetCloneSourceTeam `json:"team"` +} + +// GetTeam returns GetCloneSourceResponse.Team, and is useful for accessing the field via an interface. +func (v *GetCloneSourceResponse) GetTeam() GetCloneSourceTeam { return v.Team } + +// GetCloneSourceTeam includes the requested fields of the GraphQL type Team. +// The GraphQL type's documentation follows. +// +// The team type represents a team on the [Nais platform](https://nais.io/). +// +// Learn more about what Nais teams are and what they can be used for in the [official Nais documentation](https://docs.nais.io/explanations/team/). +// +// External resources (e.g. entraIDGroupID, gitHubTeamSlug) are managed by the platform. +type GetCloneSourceTeam struct { + // Get a specific environment for the team. + Environment GetCloneSourceTeamEnvironment `json:"environment"` +} + +// GetEnvironment returns GetCloneSourceTeam.Environment, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeam) GetEnvironment() GetCloneSourceTeamEnvironment { return v.Environment } + +// GetCloneSourceTeamEnvironment includes the requested fields of the GraphQL type TeamEnvironment. +type GetCloneSourceTeamEnvironment struct { + // Postgres in the team environment. + Postgres GetCloneSourceTeamEnvironmentPostgres `json:"postgres"` +} + +// GetPostgres returns GetCloneSourceTeamEnvironment.Postgres, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironment) GetPostgres() GetCloneSourceTeamEnvironmentPostgres { + return v.Postgres +} + +// GetCloneSourceTeamEnvironmentPostgres includes the requested fields of the GraphQL type Postgres. +// The GraphQL type's documentation follows. +// +// A managed Postgres database. +type GetCloneSourceTeamEnvironmentPostgres struct { + // Name of this Postgres. + Name string `json:"name"` + // Configured PostgreSQL major version. + MajorVersion string `json:"majorVersion"` + // Whether high availability is configured. + HighAvailability bool `json:"highAvailability"` + // Observed database state; availability does not guarantee successful client connections. + State PostgresState `json:"state"` + // Earliest point in time covered by available backups, when known. + EarliestRestoreTime *time.Time `json:"earliestRestoreTime"` + // Requested CPU, memory and disk size, when present on this Postgres. + Resources GetCloneSourceTeamEnvironmentPostgresResources `json:"resources"` +} + +// GetName returns GetCloneSourceTeamEnvironmentPostgres.Name, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgres) GetName() string { return v.Name } + +// GetMajorVersion returns GetCloneSourceTeamEnvironmentPostgres.MajorVersion, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgres) GetMajorVersion() string { return v.MajorVersion } + +// GetHighAvailability returns GetCloneSourceTeamEnvironmentPostgres.HighAvailability, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgres) GetHighAvailability() bool { return v.HighAvailability } + +// GetState returns GetCloneSourceTeamEnvironmentPostgres.State, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgres) GetState() PostgresState { return v.State } + +// GetEarliestRestoreTime returns GetCloneSourceTeamEnvironmentPostgres.EarliestRestoreTime, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgres) GetEarliestRestoreTime() *time.Time { + return v.EarliestRestoreTime +} + +// GetResources returns GetCloneSourceTeamEnvironmentPostgres.Resources, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgres) GetResources() GetCloneSourceTeamEnvironmentPostgresResources { + return v.Resources +} + +// GetCloneSourceTeamEnvironmentPostgresResources includes the requested fields of the GraphQL type PostgresResources. +// The GraphQL type's documentation follows. +// +// Resource requests configured on Postgres. Omitted requests are null. +type GetCloneSourceTeamEnvironmentPostgresResources struct { + // Requested CPU. + Cpu *string `json:"cpu"` + // Requested memory. + Memory *string `json:"memory"` + // Requested disk size. + DiskSize *string `json:"diskSize"` +} + +// GetCpu returns GetCloneSourceTeamEnvironmentPostgresResources.Cpu, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgresResources) GetCpu() *string { return v.Cpu } + +// GetMemory returns GetCloneSourceTeamEnvironmentPostgresResources.Memory, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgresResources) GetMemory() *string { return v.Memory } + +// GetDiskSize returns GetCloneSourceTeamEnvironmentPostgresResources.DiskSize, and is useful for accessing the field via an interface. +func (v *GetCloneSourceTeamEnvironmentPostgresResources) GetDiskSize() *string { return v.DiskSize } + // GetConfigActivityResponse is returned by GetConfigActivity on success. type GetConfigActivityResponse struct { // Get a team by its slug. @@ -22243,6 +22347,8 @@ type GetPostgresTeamEnvironmentPostgres struct { Resources GetPostgresTeamEnvironmentPostgresResources `json:"resources"` // User-defined labels on this Postgres. Labels []GetPostgresTeamEnvironmentPostgresLabelsResourceLabel `json:"labels"` + // Where this database was restored from, if it was created by a recovery. + Recovery *GetPostgresTeamEnvironmentPostgresRecovery `json:"recovery"` } // GetName returns GetPostgresTeamEnvironmentPostgres.Name, and is useful for accessing the field via an interface. @@ -22267,6 +22373,11 @@ func (v *GetPostgresTeamEnvironmentPostgres) GetLabels() []GetPostgresTeamEnviro return v.Labels } +// GetRecovery returns GetPostgresTeamEnvironmentPostgres.Recovery, and is useful for accessing the field via an interface. +func (v *GetPostgresTeamEnvironmentPostgres) GetRecovery() *GetPostgresTeamEnvironmentPostgresRecovery { + return v.Recovery +} + // GetPostgresTeamEnvironmentPostgresLabelsResourceLabel includes the requested fields of the GraphQL type ResourceLabel. // The GraphQL type's documentation follows. // @@ -22288,6 +22399,37 @@ func (v *GetPostgresTeamEnvironmentPostgresLabelsResourceLabel) GetKey() string // GetValue returns GetPostgresTeamEnvironmentPostgresLabelsResourceLabel.Value, and is useful for accessing the field via an interface. func (v *GetPostgresTeamEnvironmentPostgresLabelsResourceLabel) GetValue() string { return v.Value } +// GetPostgresTeamEnvironmentPostgresRecovery includes the requested fields of the GraphQL type PostgresRecovery. +// The GraphQL type's documentation follows. +// +// Origin and progress of a database created by recovery. +type GetPostgresTeamEnvironmentPostgresRecovery struct { + // Name of the source database. It may have been deleted since. + SourcePostgres string `json:"sourcePostgres"` + // The point in time restored to. + TargetTime time.Time `json:"targetTime"` + // True once the database is independent of the source and has its own backup. + Completed bool `json:"completed"` + // Why recovery failed, if it did. + FailureMessage *string `json:"failureMessage"` +} + +// GetSourcePostgres returns GetPostgresTeamEnvironmentPostgresRecovery.SourcePostgres, and is useful for accessing the field via an interface. +func (v *GetPostgresTeamEnvironmentPostgresRecovery) GetSourcePostgres() string { + return v.SourcePostgres +} + +// GetTargetTime returns GetPostgresTeamEnvironmentPostgresRecovery.TargetTime, and is useful for accessing the field via an interface. +func (v *GetPostgresTeamEnvironmentPostgresRecovery) GetTargetTime() time.Time { return v.TargetTime } + +// GetCompleted returns GetPostgresTeamEnvironmentPostgresRecovery.Completed, and is useful for accessing the field via an interface. +func (v *GetPostgresTeamEnvironmentPostgresRecovery) GetCompleted() bool { return v.Completed } + +// GetFailureMessage returns GetPostgresTeamEnvironmentPostgresRecovery.FailureMessage, and is useful for accessing the field via an interface. +func (v *GetPostgresTeamEnvironmentPostgresRecovery) GetFailureMessage() *string { + return v.FailureMessage +} + // GetPostgresTeamEnvironmentPostgresResources includes the requested fields of the GraphQL type PostgresResources. // The GraphQL type's documentation follows. // @@ -36838,6 +36980,20 @@ var AllPostgresAccessState = []PostgresAccessState{ PostgresAccessStateExpired, } +// An explicit point-in-time recovery source for a new Postgres database. +type PostgresRecoveryInput struct { + // An explicit point-in-time recovery source for a new Postgres database. + SourcePostgres string `json:"sourcePostgres"` + // An explicit point-in-time recovery source for a new Postgres database. + TargetTime time.Time `json:"targetTime"` +} + +// GetSourcePostgres returns PostgresRecoveryInput.SourcePostgres, and is useful for accessing the field via an interface. +func (v *PostgresRecoveryInput) GetSourcePostgres() string { return v.SourcePostgres } + +// GetTargetTime returns PostgresRecoveryInput.TargetTime, and is useful for accessing the field via an interface. +func (v *PostgresRecoveryInput) GetTargetTime() time.Time { return v.TargetTime } + // Observed state of a Postgres database. type PostgresState string @@ -39396,6 +39552,22 @@ func (v *__GetApplicationStatusInput) GetName() string { return v.Name } // GetEnv returns __GetApplicationStatusInput.Env, and is useful for accessing the field via an interface. func (v *__GetApplicationStatusInput) GetEnv() []string { return v.Env } +// __GetCloneSourceInput is used internally by genqlient +type __GetCloneSourceInput struct { + Team string `json:"team"` + Environment string `json:"environment"` + Postgres string `json:"postgres"` +} + +// GetTeam returns __GetCloneSourceInput.Team, and is useful for accessing the field via an interface. +func (v *__GetCloneSourceInput) GetTeam() string { return v.Team } + +// GetEnvironment returns __GetCloneSourceInput.Environment, and is useful for accessing the field via an interface. +func (v *__GetCloneSourceInput) GetEnvironment() string { return v.Environment } + +// GetPostgres returns __GetCloneSourceInput.Postgres, and is useful for accessing the field via an interface. +func (v *__GetCloneSourceInput) GetPostgres() string { return v.Postgres } + // __GetConfigActivityInput is used internally by genqlient type __GetConfigActivityInput struct { Team string `json:"team"` @@ -41989,6 +42161,57 @@ func GetApplicationStatus( return data_, err_ } +// The query executed by GetCloneSource. +const GetCloneSource_Operation = ` +query GetCloneSource ($team: Slug!, $environment: String!, $postgres: String!) { + team(slug: $team) { + environment(name: $environment) { + postgres(name: $postgres) { + name + majorVersion + highAvailability + state + earliestRestoreTime + resources { + cpu + memory + diskSize + } + } + } + } +} +` + +func GetCloneSource( + ctx_ context.Context, + client_ graphql.Client, + team string, + environment string, + postgres string, +) (data_ *GetCloneSourceResponse, err_ error) { + req_ := &graphql.Request{ + OpName: "GetCloneSource", + Query: GetCloneSource_Operation, + Variables: &__GetCloneSourceInput{ + Team: team, + Environment: environment, + Postgres: postgres, + }, + } + + data_ = &GetCloneSourceResponse{} + resp_ := &graphql.Response{Data: data_} + + err_ = client_.MakeRequest( + ctx_, + req_, + resp_, + ) + + return data_, err_ +} + // The query executed by GetConfig. const GetConfig_Operation = ` query GetConfig ($name: String!, $environmentName: String!, $teamSlug: Slug!) { @@ -42638,6 +42861,12 @@ query GetPostgres ($team: Slug!, $environment: String!, $postgres: String!) { key value } + recovery { + sourcePostgres + targetTime + completed + failureMessage + } } } } diff --git a/internal/postgres/clone.go b/internal/postgres/clone.go new file mode 100644 index 00000000..c41a8a73 --- /dev/null +++ b/internal/postgres/clone.go @@ -0,0 +1,31 @@ +package postgres + +import ( + "context" + "fmt" + + "github.com/nais/cli/internal/naisapi" + "github.com/nais/cli/internal/naisapi/gql" +) + +// GetCloneSource returns the configuration a clone inherits from, and the earliest +// point in time covered by its backups. +func GetCloneSource(ctx context.Context, team, environment, name string) (*gql.GetCloneSourceTeamEnvironmentPostgres, error) { + _ = `# @genqlient + query GetCloneSource($team: Slug!, $environment: String!, $postgres: String!) { + team(slug: $team) { environment(name: $environment) { postgres(name: $postgres) { + name majorVersion highAvailability state earliestRestoreTime + resources { cpu memory diskSize } + } } } + } + ` + client, err := naisapi.GraphqlClient(ctx) + if err != nil { + return nil, err + } + result, err := gql.GetCloneSource(ctx, client, team, environment, name) + if err != nil { + return nil, fmt.Errorf("fetching Postgres %q: %w", name, err) + } + return &result.Team.Environment.Postgres, nil +} diff --git a/internal/postgres/command/clone.go b/internal/postgres/command/clone.go new file mode 100644 index 00000000..f9ba2330 --- /dev/null +++ b/internal/postgres/command/clone.go @@ -0,0 +1,213 @@ +package command + +import ( + "context" + "fmt" + "time" + + "github.com/nais/cli/internal/naisapi/gql" + "github.com/nais/cli/internal/postgres" + "github.com/nais/cli/internal/postgres/command/flag" + "github.com/nais/cli/internal/validation" + "github.com/nais/naistrix" + "github.com/nais/naistrix/input" + "github.com/nais/naistrix/output" +) + +// cloneLatestBuffer keeps a default clone safely inside the archived WAL: the newest +// transactions may not have been archived yet. +const cloneLatestBuffer = 10 * time.Minute + +func instanceCloneCommand(parent *flag.Postgres) *naistrix.Command { + f := &flag.InstanceClone{Postgres: parent} + return &naistrix.Command{ + Name: "clone", Title: "Clone a Postgres instance to a new database.", Flags: f, + Description: "Create a new Postgres from the backups of an existing one. " + + "Without --at the clone is made from the latest available point, approximately 10 minutes ago. " + + "The new database is created in the same team and environment as the source, with the same PostgreSQL version and extensions. " + + "The source is not changed and no applications are moved to the new database. " + + "Availability and resources default to the source's configuration; the disk cannot be smaller than the source's. " + + "Cloning continues asynchronously.", + Args: []naistrix.Argument{ + {Name: "source", Prompt: "Name of the Postgres instance to clone", ChoicesFunc: postgresNameChoices(parent)}, + {Name: "postgres", Prompt: "Name of the new Postgres instance"}, + }, + Examples: []naistrix.CommandExample{ + {Description: "Clone a Postgres from the latest available point.", Command: "my-postgres my-clone -t my-team"}, + {Description: "Clone a Postgres as it was at a point in time (local time).", Command: "my-postgres my-clone --at \"2026-11-16 12:00\" -t my-team"}, + {Description: "Clone with more resources than the source.", Command: "my-postgres my-clone -t my-team -e dev-gcp --cpu 500m --memory 2Gi --disk-size 50Gi"}, + }, + ValidateFlagsFunc: validation.RequireTeamFlag(f), + RunFunc: func(ctx context.Context, args *naistrix.Arguments, out *naistrix.OutputWriter) error { + source, name := args.Get("source"), args.Get("postgres") + if source == name { + return fmt.Errorf("the new Postgres must have a different name than its source") + } + now := time.Now() + target, explicit, err := resolveCloneTime(f.At, now, time.Local) + if err != nil { + return err + } + highAvailability, err := parseHighAvailability(f.HighAvailability) + if err != nil { + return err + } + env, err := resolvePostgresEnvironment(ctx, f.Team, source, string(f.Environment)) + if err != nil { + return err + } + src, err := postgres.GetCloneSource(ctx, f.Team, env, source) + if err != nil { + return err + } + if err := validateCloneWindow(target, explicit, src.EarliestRestoreTime, time.Local); err != nil { + return err + } + targetLabel := formatLocalTime(target, time.Local) + if !explicit { + targetLabel += " (latest available)" + } + rows := instanceTarget(name, f.Team, env) + rows = append(rows, + []string{"Clone of", source}, + []string{"Clone from", targetLabel}, + []string{"Earliest possible", formatLocalTime(*src.EarliestRestoreTime, time.Local)}, + []string{"Version", src.MajorVersion + " (same as source)"}, + []string{"High availability", cloneSetting(fmt.Sprint(src.HighAvailability), highAvailabilityValue(highAvailability))}, + []string{"CPU", cloneSetting(deref(src.Resources.Cpu), f.CPU)}, + []string{"Memory", cloneSetting(deref(src.Resources.Memory), f.Memory)}, + []string{"Disk size", cloneSetting(deref(src.Resources.DiskSize), f.DiskSize)}, + ) + out.Infoln("Clone Postgres with this configuration. The source is not changed and no applications are moved:") + if err := out.Table(output.TableWithMargins()).Render(rows); err != nil { + return err + } + if !f.Yes { + ok, err := input.Confirm("Clone to a new Postgres?", input.ConfirmWithDefaultTrue()) + if err != nil { + return err + } + if !ok { + return fmt.Errorf("cancelled by user") + } + } + created, err := postgres.CreateInstance(ctx, gql.CreatePostgresInput{ + Name: name, TeamSlug: f.Team, EnvironmentName: env, MajorVersion: src.MajorVersion, + HighAvailability: highAvailability, + Cpu: optional(f.CPU), Memory: optional(f.Memory), DiskSize: optional(f.DiskSize), + Recovery: &gql.PostgresRecoveryInput{SourcePostgres: source, TargetTime: target}, + }) + if err != nil { + return err + } + printPostgresHeading(out, created, env) + out.Println("Started cloning postgres. Run this command to check status:") + out.Println(postgresGetCommandLine(created, f.Team, env, f.Config)) + return nil + }, + } +} + +// localTimeLayouts are accepted without an offset and read in the local time zone. +var localTimeLayouts = []string{"2006-01-02T15:04:05", "2006-01-02 15:04:05", "2006-01-02T15:04", "2006-01-02 15:04"} + +// resolveCloneTime returns the absolute instant to clone from, in whole seconds. An empty value +// means the latest available point (now minus the safety buffer). A value with an offset or Z is +// absolute; a value without one is read in loc. Fractional seconds and the future are rejected. +func resolveCloneTime(value string, now time.Time, loc *time.Location) (target time.Time, explicit bool, err error) { + if value == "" { + return now.Add(-cloneLatestBuffer).Truncate(time.Second).UTC(), false, nil + } + parsed, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + parsed, err = parseLocalTime(value, loc) + if err != nil { + return time.Time{}, true, err + } + } + if parsed.Nanosecond() != 0 { + return time.Time{}, true, fmt.Errorf("--at must be in whole seconds") + } + if parsed.After(now) { + return time.Time{}, true, fmt.Errorf("--at must not be in the future") + } + return parsed.UTC(), true, nil +} + +func parseLocalTime(value string, loc *time.Location) (time.Time, error) { + for _, layout := range localTimeLayouts { + parsed, err := time.ParseInLocation(layout, value, loc) + if err != nil { + continue + } + // Go moves a time skipped by a DST change instead of failing; do not silently pick another instant. + if parsed.Format(layout) != value { + return time.Time{}, fmt.Errorf("--at %q does not exist in time zone %s (daylight saving change)", value, loc) + } + // The autumn change repeats an hour and Go does not say which instant it picks, so choose + // the earlier one deterministically (the same as Console). + for _, shifted := range []time.Time{parsed.Add(-time.Hour), parsed.Add(time.Hour)} { + if shifted.In(loc).Format(layout) == value && shifted.Before(parsed) { + parsed = shifted + } + } + return parsed, nil + } + return time.Time{}, fmt.Errorf("--at must be a local time like \"2026-11-16 12:00\" or RFC 3339 like 2026-11-16T12:00:00Z") +} + +// validateCloneWindow rejects targets outside the backup window. A default target that is +// too early gets its own hint, since the user never chose it. +func validateCloneWindow(target time.Time, explicit bool, earliest *time.Time, loc *time.Location) error { + if earliest == nil { + return fmt.Errorf("the source has no recoverable backup window yet; try again later") + } + if target.Before(*earliest) { + if !explicit { + return fmt.Errorf("the source's backups only reach back to %s, which is later than the default clone point (about 10 minutes ago); try again shortly or specify --at", formatLocalTime(*earliest, loc)) + } + return fmt.Errorf("--at is before the earliest possible clone time %s", formatLocalTime(*earliest, loc)) + } + return nil +} + +// formatLocalTime shows an instant in loc with its zone, so the output is unambiguous. +func formatLocalTime(t time.Time, loc *time.Location) string { + return t.In(loc).Format("2006-01-02 15:04:05 MST") +} + +func parseHighAvailability(value flag.HighAvailability) (*bool, error) { + switch value { + case "": + return nil, nil + case "true", "false": + enabled := value == "true" + return &enabled, nil + } + return nil, fmt.Errorf("--high-availability must be true or false") +} + +func highAvailabilityValue(value *bool) string { + if value == nil { + return "" + } + return fmt.Sprint(*value) +} + +// cloneSetting shows an explicit override, or the inherited source value. +func cloneSetting(inherited, explicit string) string { + if explicit != "" { + return explicit + " (overrides source)" + } + if inherited == "" { + return "platform default" + } + return inherited + " (from source)" +} + +func deref(value *string) string { + if value == nil { + return "" + } + return *value +} diff --git a/internal/postgres/command/clone_test.go b/internal/postgres/command/clone_test.go new file mode 100644 index 00000000..76500f23 --- /dev/null +++ b/internal/postgres/command/clone_test.go @@ -0,0 +1,303 @@ +package command + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/nais/cli/internal/flags" + "github.com/nais/naistrix" +) + +func TestResolveCloneTime(t *testing.T) { + oslo, err := time.LoadLocation("Europe/Oslo") + if err != nil { + t.Fatal(err) + } + now := time.Date(2026, 11, 16, 12, 0, 30, 500, time.UTC) + for _, tt := range []struct { + name, value, wantError string + want time.Time + explicit bool + }{ + {name: "default is ten minutes ago in whole seconds", want: time.Date(2026, 11, 16, 11, 50, 30, 0, time.UTC)}, + {name: "RFC 3339 UTC", value: "2026-11-16T10:00:00Z", want: time.Date(2026, 11, 16, 10, 0, 0, 0, time.UTC), explicit: true}, + {name: "RFC 3339 offset is normalized", value: "2026-11-16T11:00:00+01:00", want: time.Date(2026, 11, 16, 10, 0, 0, 0, time.UTC), explicit: true}, + {name: "local time without offset", value: "2026-11-16 11:00", want: time.Date(2026, 11, 16, 10, 0, 0, 0, time.UTC), explicit: true}, + {name: "local time with T and seconds", value: "2026-11-16T11:00:05", want: time.Date(2026, 11, 16, 10, 0, 5, 0, time.UTC), explicit: true}, + {name: "summer time uses the summer offset", value: "2026-07-01 12:00", want: time.Date(2026, 7, 1, 10, 0, 0, 0, time.UTC), explicit: true}, + {name: "ambiguous autumn hour resolves to the earlier occurrence", value: "2026-10-25 02:30", want: time.Date(2026, 10, 25, 0, 30, 0, 0, time.UTC), explicit: true}, + {name: "ambiguous hour is fine with an explicit offset", value: "2026-10-25T02:30:00+01:00", want: time.Date(2026, 10, 25, 1, 30, 0, 0, time.UTC), explicit: true}, + {name: "hour after the autumn change is unambiguous", value: "2026-10-25 03:30", want: time.Date(2026, 10, 25, 2, 30, 0, 0, time.UTC), explicit: true}, + {name: "hour skipped by daylight saving is rejected", value: "2026-03-29 02:30", wantError: "does not exist", explicit: true}, + {name: "not a time", value: "yesterday", wantError: "--at must be a local time", explicit: true}, + {name: "date only", value: "2026-11-16", wantError: "--at must be a local time", explicit: true}, + {name: "fractional seconds", value: "2026-11-16T10:00:00.5Z", wantError: "whole seconds", explicit: true}, + {name: "future", value: "2026-11-16 13:01", wantError: "future", explicit: true}, + } { + t.Run(tt.name, func(t *testing.T) { + got, explicit, err := resolveCloneTime(tt.value, now, oslo) + if tt.wantError != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantError) { + t.Fatalf("error = %v, want %q", err, tt.wantError) + } + return + } + if err != nil || !got.Equal(tt.want) || got.Location() != time.UTC || explicit != tt.explicit { + t.Fatalf("got %v explicit=%t, %v; want %v explicit=%t in UTC", got, explicit, err, tt.want, tt.explicit) + } + }) + } +} + +func TestValidateCloneWindow(t *testing.T) { + oslo, err := time.LoadLocation("Europe/Oslo") + if err != nil { + t.Fatal(err) + } + earliest := time.Date(2026, 11, 10, 0, 0, 0, 0, time.UTC) + if err := validateCloneWindow(earliest, true, &earliest, oslo); err != nil { + t.Errorf("the earliest instant itself is cloneable: %v", err) + } + err = validateCloneWindow(earliest.Add(-time.Second), true, &earliest, oslo) + if err == nil || !strings.Contains(err.Error(), "2026-11-10 01:00:00 CET") { + t.Errorf("explicit before window must name the earliest time in local time: %v", err) + } + err = validateCloneWindow(earliest.Add(-time.Second), false, &earliest, oslo) + if err == nil || !strings.Contains(err.Error(), "default clone point") { + t.Errorf("default before window must explain it was the default: %v", err) + } + if err := validateCloneWindow(earliest, true, nil, oslo); err == nil || !strings.Contains(err.Error(), "no recoverable backup window") { + t.Errorf("unknown window: %v", err) + } +} + +func TestCloneSettingExplainsInheritance(t *testing.T) { + for _, tt := range []struct{ inherited, explicit, want string }{ + {"20Gi", "", "20Gi (from source)"}, + {"20Gi", "50Gi", "50Gi (overrides source)"}, + {"", "", "platform default"}, + } { + if got := cloneSetting(tt.inherited, tt.explicit); got != tt.want { + t.Errorf("cloneSetting(%q, %q) = %q, want %q", tt.inherited, tt.explicit, got, tt.want) + } + } +} + +func TestCloneCommand(t *testing.T) { + const source = `{"name":"orders","majorVersion":"17","state":"AVAILABLE","highAvailability":true,"earliestRestoreTime":"2026-11-10T00:00:00Z","resources":{"cpu":"200m","memory":"1Gi","diskSize":"20Gi"}}` + for _, tt := range []struct { + name string + target string + extra []string + source string + wantError string + wantCreate bool + check func(t *testing.T, input map[string]any) + }{ + { + name: "inherits everything and sends the source version", extra: []string{"--at", "2026-11-12T10:00:00Z"}, source: source, wantCreate: true, + check: func(t *testing.T, input map[string]any) { + recovery, _ := input["recovery"].(map[string]any) + if recovery["sourcePostgres"] != "orders" || recovery["targetTime"] != "2026-11-12T10:00:00Z" { + t.Errorf("recovery = %v", recovery) + } + if input["majorVersion"] != "17" || input["name"] != "orders-restored" || input["environmentName"] != "dev-gcp" || input["teamSlug"] != "my-team" { + t.Errorf("input = %v", input) + } + for _, inherited := range []string{"highAvailability", "cpu", "memory", "diskSize"} { + if _, set := input[inherited]; set { + t.Errorf("%s must be omitted so the API inherits it from the source", inherited) + } + } + }, + }, + { + name: "explicit overrides are sent", extra: []string{"--at", "2026-11-12T10:00:00Z", "--cpu", "1", "--memory", "4Gi", "--disk-size", "50Gi", "--high-availability", "false"}, source: source, wantCreate: true, + check: func(t *testing.T, input map[string]any) { + if input["cpu"] != "1" || input["memory"] != "4Gi" || input["diskSize"] != "50Gi" || input["highAvailability"] != false { + t.Errorf("overrides missing: %v", input) + } + }, + }, + {name: "time before the backup window never creates", extra: []string{"--at", "2026-11-09T23:59:59Z"}, source: source, wantError: "earliest possible clone time"}, + {name: "source without a backup window never creates", extra: []string{"--at", "2026-11-12T10:00:00Z"}, source: strings.Replace(source, `"2026-11-10T00:00:00Z"`, `null`, 1), wantError: "no recoverable backup window"}, + { + name: "no time clones from the latest available point", source: strings.Replace(source, `"2026-11-10T00:00:00Z"`, `"2020-01-01T00:00:00Z"`, 1), wantCreate: true, + check: func(t *testing.T, input map[string]any) { + recovery, _ := input["recovery"].(map[string]any) + target, err := time.Parse(time.RFC3339, recovery["targetTime"].(string)) + if err != nil { + t.Fatal(err) + } + if age := time.Since(target); age < 9*time.Minute+50*time.Second || age > 10*time.Minute+30*time.Second { + t.Errorf("default target is %v old, want about 10 minutes", age) + } + }, + }, + {name: "default earlier than the backup window explains itself", source: strings.Replace(source, `"2026-11-10T00:00:00Z"`, `"2099-01-01T00:00:00Z"`, 1), wantError: "default clone point"}, + {name: "invalid time is rejected before the source is read", extra: []string{"--at", "2026-11-12T10:00:00.5Z"}, wantError: "whole seconds"}, + {name: "source cannot be its own target", target: "orders", extra: []string{"--at", "2026-11-12T10:00:00Z"}, wantError: "different name"}, + } { + t.Run(tt.name, func(t *testing.T) { + stdin, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + previous := os.Stdin + os.Stdin = stdin + t.Cleanup(func() { os.Stdin = previous; _ = stdin.Close() }) + var operations []string + var created map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var request struct { + OperationName string `json:"operationName"` + Variables map[string]any `json:"variables"` + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + t.Errorf("decoding request: %v", err) + } + operations = append(operations, request.OperationName) + w.Header().Set("Content-Type", "application/json") + switch request.OperationName { + case "GetTeamPostgreses": + _, _ = w.Write([]byte(`{"data":{"team":{"postgreses":{"nodes":[{"name":"orders","teamEnvironment":{"environment":{"name":"dev-gcp"}}}],"pageInfo":{"hasNextPage":false}}}}}`)) + case "GetCloneSource": + _, _ = w.Write([]byte(`{"data":{"team":{"environment":{"postgres":` + tt.source + `}}}}`)) + case "CreatePostgres": + created, _ = request.Variables["input"].(map[string]any) + _, _ = w.Write([]byte(`{"data":{"createPostgres":{"postgres":{"name":"orders-restored"}}}}`)) + default: + t.Errorf("unexpected operation %s", request.OperationName) + } + })) + defer server.Close() + t.Setenv("NAIS_API_LOCAL_HOST", strings.TrimPrefix(server.URL, "http://")) + t.Setenv("HOME", t.TempDir()) + config := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(config, []byte("{}\n"), 0o600); err != nil { + t.Fatal(err) + } + var output bytes.Buffer + app, global, err := naistrix.NewApplication("postgres-restore-test", "Test Postgres restore", "test", naistrix.ApplicationWithWriter(&output)) + if err != nil { + t.Fatal(err) + } + additional := &flags.AdditionalFlags{} + if err := app.AddGlobalFlags(additional); err != nil { + t.Fatal(err) + } + if err := app.AddCommand(Postgres(&flags.GlobalFlags{GlobalFlags: global, AdditionalFlags: additional})); err != nil { + t.Fatal(err) + } + target := tt.target + if target == "" { + target = "orders-restored" + } + args := append([]string{"--config", config, "--no-colors", "postgres", "clone", "orders", target, "-t", "my-team", "-e", "dev-gcp", "--yes"}, tt.extra...) + err = app.Run(naistrix.RunWithArgs(args)) + if tt.wantError != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantError) { + t.Fatalf("error = %v, want %q", err, tt.wantError) + } + } else if err != nil { + t.Fatal(err) + } + if (created != nil) != tt.wantCreate { + t.Fatalf("created = %v, want create %t (operations %v)", created, tt.wantCreate, operations) + } + if tt.wantError != "" && tt.source == "" || tt.target == "orders" { + for _, operation := range operations { + if operation == "GetCloneSource" || operation == "CreatePostgres" { + t.Errorf("rejected input must not reach %s (operations %v)", operation, operations) + } + } + } + if tt.check != nil { + tt.check(t, created) + } + if tt.wantCreate && !strings.Contains(output.String(), "Started cloning postgres") { + t.Errorf("output = %q", output.String()) + } + }) + } +} + +func TestGetShowsCloneProgress(t *testing.T) { + for _, tt := range []struct { + name, recovery string + want []string + }{ + {"in progress", `{"sourcePostgres":"orders","targetTime":"2026-11-12T10:00:00Z","completed":false,"failureMessage":null}`, []string{"Cloned from:", "orders", "Clone point:", "In progress"}}, + {"completed", `{"sourcePostgres":"orders","targetTime":"2026-11-12T10:00:00Z","completed":true,"failureMessage":null}`, []string{"Completed"}}, + {"failed", `{"sourcePostgres":"orders","targetTime":"2026-11-12T10:00:00Z","completed":false,"failureMessage":"archive missing"}`, []string{"Failed: archive missing"}}, + {"not restored", `null`, []string{"Version:"}}, + } { + t.Run(tt.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var request struct { + OperationName string `json:"operationName"` + } + _ = json.NewDecoder(r.Body).Decode(&request) + w.Header().Set("Content-Type", "application/json") + if request.OperationName == "GetTeamPostgreses" { + _, _ = w.Write([]byte(`{"data":{"team":{"postgreses":{"nodes":[{"name":"restored","teamEnvironment":{"environment":{"name":"dev-gcp"}}}],"pageInfo":{"hasNextPage":false}}}}}`)) + return + } + _, _ = w.Write([]byte(`{"data":{"team":{"environment":{"postgres":{"name":"restored","majorVersion":"18","state":"AVAILABLE","highAvailability":false,"resources":{},"labels":[],"recovery":` + tt.recovery + `}}}}}}`)) + })) + defer server.Close() + t.Setenv("NAIS_API_LOCAL_HOST", strings.TrimPrefix(server.URL, "http://")) + t.Setenv("HOME", t.TempDir()) + config := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(config, []byte("{}\n"), 0o600); err != nil { + t.Fatal(err) + } + for _, format := range []string{"", "json"} { + var output bytes.Buffer + app, global, err := naistrix.NewApplication("postgres-get-test", "Test", "test", naistrix.ApplicationWithWriter(&output)) + if err != nil { + t.Fatal(err) + } + additional := &flags.AdditionalFlags{} + if err := app.AddGlobalFlags(additional); err != nil { + t.Fatal(err) + } + if err := app.AddCommand(Postgres(&flags.GlobalFlags{GlobalFlags: global, AdditionalFlags: additional})); err != nil { + t.Fatal(err) + } + args := []string{"--config", config, "--no-colors", "postgres", "get", "restored", "-t", "my-team", "-e", "dev-gcp"} + if format != "" { + args = append(args, "--output", format) + } + if err := app.Run(naistrix.RunWithArgs(args)); err != nil { + t.Fatal(err) + } + if format == "json" { + var detail postgresDetails + if err := json.Unmarshal(output.Bytes(), &detail); err != nil { + t.Fatalf("invalid JSON %q: %v", output.String(), err) + } + if (detail.Recovery != nil) != (tt.recovery != "null") { + t.Errorf("recovery = %+v for %s", detail.Recovery, tt.recovery) + } + continue + } + for _, want := range tt.want { + if !strings.Contains(output.String(), want) { + t.Errorf("output missing %q:\n%s", want, output.String()) + } + } + if tt.recovery == "null" && strings.Contains(output.String(), "Clone") { + t.Errorf("a database that was not restored must not show restore details:\n%s", output.String()) + } + } + }) + } +} diff --git a/internal/postgres/command/flag/flag.go b/internal/postgres/command/flag/flag.go index 5b98c471..3e059681 100644 --- a/internal/postgres/command/flag/flag.go +++ b/internal/postgres/command/flag/flag.go @@ -38,6 +38,15 @@ type ( Memory string `name:"memory" usage:"Requested memory, e.g. 512Mi."` DiskSize string `name:"disk-size" usage:"Requested disk size, e.g. 10Gi."` } + InstanceClone struct { + *Postgres + Yes bool `name:"yes" short:"y" usage:"Confirm without a prompt."` + At string `name:"at" usage:"Point in time to clone from, in local time (e.g. \"2026-11-16 12:00\") or RFC 3339 with offset. Defaults to the latest available point, about 10 minutes ago."` + HighAvailability HighAvailability `name:"high-availability" usage:"Enable or disable high availability (true or false). Defaults to the source's setting."` + CPU string `name:"cpu" usage:"Requested CPU, e.g. 100m. Defaults to the source's request."` + Memory string `name:"memory" usage:"Requested memory, e.g. 512Mi. Defaults to the source's request."` + DiskSize string `name:"disk-size" usage:"Requested disk size, e.g. 10Gi. Defaults to the source's size and must not be smaller."` + } InstanceDelete struct { *Postgres Yes bool `name:"yes" short:"y" usage:"Confirm irreversible deletion without a prompt."` diff --git a/internal/postgres/command/get.go b/internal/postgres/command/get.go index e1c653e9..fb7d075c 100644 --- a/internal/postgres/command/get.go +++ b/internal/postgres/command/get.go @@ -3,6 +3,7 @@ package command import ( "context" "strings" + "time" "github.com/nais/cli/internal/postgres" "github.com/nais/cli/internal/postgres/command/flag" @@ -21,6 +22,23 @@ type postgresDetails struct { HighAvailability bool `json:"highAvailability"` Resources postgresResourceRequests `json:"resources"` Labels []postgresLabel `json:"labels"` + Recovery *postgresRecovery `json:"recovery"` +} + +// targetTimeLocal shows the recovery point in the user's time zone; JSON keeps the UTC instant. +func (r postgresRecovery) targetTimeLocal() string { + parsed, err := time.Parse(time.RFC3339, r.TargetTime) + if err != nil { + return r.TargetTime + } + return formatLocalTime(parsed, time.Local) +} + +type postgresRecovery struct { + Source string `json:"source"` + TargetTime string `json:"targetTime"` + Completed bool `json:"completed"` + FailureMessage *string `json:"failureMessage"` } type postgresResourceRequests struct { @@ -67,6 +85,9 @@ func instanceGetCommand(parent *flag.Postgres) *naistrix.Command { for _, label := range p.Labels { detail.Labels = append(detail.Labels, postgresLabel{Key: label.Key, Value: label.Value}) } + if r := p.Recovery; r != nil { + detail.Recovery = &postgresRecovery{Source: r.SourcePostgres, TargetTime: r.TargetTime.UTC().Format(time.RFC3339), Completed: r.Completed, FailureMessage: r.FailureMessage} + } if f.Output == "json" { return out.JSON(output.JSONWithPrettyOutput()).Render(detail) } @@ -100,6 +121,17 @@ func instanceGetCommand(parent *flag.Postgres) *naistrix.Command { } { out.Printf(" %-18s %s\n", setting.label, setting.value) } + if r := detail.Recovery; r != nil { + status := "In progress" + if r.FailureMessage != nil { + status = "Failed: " + *r.FailureMessage + } else if r.Completed { + status = "Completed" + } + out.Printf("\n %-18s %s\n", "Cloned from:", r.Source) + out.Printf(" %-18s %s\n", "Clone point:", r.targetTimeLocal()) + out.Printf(" %-18s %s\n", "Clone status:", status) + } if len(detail.Labels) > 0 { labels := make([]string, 0, len(detail.Labels)) for _, label := range detail.Labels { diff --git a/internal/postgres/command/postgres.go b/internal/postgres/command/postgres.go index 5852969e..ba61c84d 100644 --- a/internal/postgres/command/postgres.go +++ b/internal/postgres/command/postgres.go @@ -22,6 +22,7 @@ func Postgres(parentFlags *flags.GlobalFlags) *naistrix.Command { listCommand(flags), instanceGetCommand(flags), instanceCreateCommand(flags), + instanceCloneCommand(flags), instanceUpdateCommand(flags), instanceDeleteCommand(flags), psqlCommand(flags), diff --git a/internal/postgres/get.go b/internal/postgres/get.go index 244d022b..f87378ab 100644 --- a/internal/postgres/get.go +++ b/internal/postgres/get.go @@ -16,6 +16,7 @@ func GetPostgres(ctx context.Context, team, environment, name string) (*gql.GetP name majorVersion highAvailability state resources { cpu memory diskSize } labels { key value } + recovery { sourcePostgres targetTime completed failureMessage } } } } } ` diff --git a/internal/postgres/instance.go b/internal/postgres/instance.go index 92ae1891..4f198564 100644 --- a/internal/postgres/instance.go +++ b/internal/postgres/instance.go @@ -32,6 +32,7 @@ func CreateInstance(ctx context.Context, input gql.CreatePostgresInput) (string, # @genqlient(for: "CreatePostgresInput.cpu", omitempty: true) # @genqlient(for: "CreatePostgresInput.memory", omitempty: true) # @genqlient(for: "CreatePostgresInput.diskSize", omitempty: true) + # @genqlient(for: "CreatePostgresInput.recovery", omitempty: true) mutation CreatePostgres( $input: CreatePostgresInput! ) { diff --git a/schema.graphql b/schema.graphql index 6ba9c460..b48c52bc 100644 --- a/schema.graphql +++ b/schema.graphql @@ -3044,6 +3044,10 @@ Input for creating a Postgres. Input for creating a Postgres. """ labels: [ResourceLabelInput!] +""" +Input for creating a Postgres. +""" + recovery: PostgresRecoveryInput } """ @@ -4324,6 +4328,10 @@ Link to the vulnerability details. type ImageVulnerabilityConnection { """ +Facets over all matching findings, ignoring pagination and respecting the current filter. +""" + facets: ImageVulnerabilityFacets +""" Information to aid in pagination. """ pageInfo: PageInfo! @@ -4348,6 +4356,16 @@ The image vulnerability. node: ImageVulnerability! } +""" +Distribution counts over all matching image findings, ignoring pagination and respecting the current filter. +""" +type ImageVulnerabilityFacets { +""" +Distribution of matching findings by PURL type. +""" + packageTypes: [StringFacetItem!]! +} + """ Input for filtering image vulnerabilities. """ @@ -7640,6 +7658,10 @@ Earliest point in time covered by available backups, when known. """ earliestRestoreTime: Time """ +Where this database was restored from, if it was created by a recovery. +""" + recovery: PostgresRecovery +""" Issues reported for this database. """ issues( @@ -7734,6 +7756,10 @@ Filter items. """ filter: ActivityLogFilter ): ActivityLogEntryConnection! +""" +The cost for this Postgres. Billing data is delayed by at least two days. +""" + cost: PostgresCost! } """ @@ -7961,6 +7987,40 @@ Labels across team Postgres databases, independent of pagination. facets: PostgresFacets! } +""" +The cost for a Postgres. +""" +type PostgresCost { +""" +Daily cost in ascending date order. Dates without cost data are omitted. Null when there is no cost data in the period. +""" + daily( +""" +Start date of the period, inclusive. +""" + from: Date! +""" +End date of the period, inclusive; must not be in the future. +""" + to: Date! + ): PostgresCostPeriod +""" +Monthly cost for the last 12 months, newest first. The date is the last day with cost data in the month. Null when there is no cost data. +""" + monthly: PostgresCostPeriod +} + +type PostgresCostPeriod { +""" +The total cost in euros for the period. +""" + sum: Float! +""" +The cost series. +""" + series: [ServiceCostSeries!]! +} + """ Activity log entry for a Postgres that was created. """ @@ -8255,6 +8315,42 @@ Caller-provided audit reason. reason: String! } +""" +Origin and progress of a database created by recovery. +""" +type PostgresRecovery { +""" +Name of the source database. It may have been deleted since. +""" + sourcePostgres: String! +""" +The point in time restored to. +""" + targetTime: Time! +""" +True once the database is independent of the source and has its own backup. +""" + completed: Boolean! +""" +Why recovery failed, if it did. +""" + failureMessage: String +} + +""" +An explicit point-in-time recovery source for a new Postgres database. +""" +input PostgresRecoveryInput { +""" +An explicit point-in-time recovery source for a new Postgres database. +""" + sourcePostgres: String! +""" +An explicit point-in-time recovery source for a new Postgres database. +""" + targetTime: Time! +} + """ Resource requests configured on Postgres. Omitted requests are null. """ @@ -11251,7 +11347,7 @@ The sum of the cost across all services. """ sum: Float! """ -The cost for the services used by the workload. +The cost for the services used by the resource. """ services: [ServiceCostSample!]! } From b49ee04a9f0fc61e6413228d351668d03933c36d Mon Sep 17 00:00:00 2001 From: Frode Sundby Date: Wed, 18 Nov 2026 10:21:15 +0100 Subject: [PATCH 2/2] fix(postgres): resolve repeated local times using the zone's actual offsets The overlap check assumed every clock change is one hour, so a half-hour change such as Australia/Lord_Howe resolved a repeated time to the later occurrence. Enumerate the offsets in effect around the date instead; a time that no offset produces does not exist, and a repeated one resolves to the earliest instant. Cover half-hour repeats and gaps. --- internal/postgres/command/clone.go | 36 ++++++++++++++++-------- internal/postgres/command/clone_test.go | 37 +++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 11 deletions(-) diff --git a/internal/postgres/command/clone.go b/internal/postgres/command/clone.go index f9ba2330..16966211 100644 --- a/internal/postgres/command/clone.go +++ b/internal/postgres/command/clone.go @@ -3,6 +3,7 @@ package command import ( "context" "fmt" + "slices" "time" "github.com/nais/cli/internal/naisapi/gql" @@ -136,26 +137,39 @@ func resolveCloneTime(value string, now time.Time, loc *time.Location) (target t func parseLocalTime(value string, loc *time.Location) (time.Time, error) { for _, layout := range localTimeLayouts { - parsed, err := time.ParseInLocation(layout, value, loc) + wall, err := time.Parse(layout, value) if err != nil { continue } - // Go moves a time skipped by a DST change instead of failing; do not silently pick another instant. - if parsed.Format(layout) != value { + instants := localInstants(wall, layout, loc) + if len(instants) == 0 { return time.Time{}, fmt.Errorf("--at %q does not exist in time zone %s (daylight saving change)", value, loc) } - // The autumn change repeats an hour and Go does not say which instant it picks, so choose - // the earlier one deterministically (the same as Console). - for _, shifted := range []time.Time{parsed.Add(-time.Hour), parsed.Add(time.Hour)} { - if shifted.In(loc).Format(layout) == value && shifted.Before(parsed) { - parsed = shifted - } - } - return parsed, nil + // A repeated time occurs more than once; choose the earliest, the same as Console. + return slices.MinFunc(instants, func(a, b time.Time) int { return a.Compare(b) }), nil } return time.Time{}, fmt.Errorf("--at must be a local time like \"2026-11-16 12:00\" or RFC 3339 like 2026-11-16T12:00:00Z") } +// localInstants returns every instant at which loc's wall clock shows wall: none when the time is +// skipped by a clock change, two when it is repeated. It tries the zone's actual offsets around the +// date rather than assuming a clock change is one hour. +func localInstants(wall time.Time, layout string, loc *time.Location) []time.Time { + offsets := map[int]bool{} + for _, day := range []int{-1, 0, 1} { + _, offset := wall.AddDate(0, 0, day).In(loc).Zone() + offsets[offset] = true + } + var instants []time.Time + for offset := range offsets { + instant := wall.Add(-time.Duration(offset) * time.Second) + if instant.In(loc).Format(layout) == wall.Format(layout) { + instants = append(instants, instant) + } + } + return instants +} + // validateCloneWindow rejects targets outside the backup window. A default target that is // too early gets its own hint, since the user never chose it. func validateCloneWindow(target time.Time, explicit bool, earliest *time.Time, loc *time.Location) error { diff --git a/internal/postgres/command/clone_test.go b/internal/postgres/command/clone_test.go index 76500f23..b614edec 100644 --- a/internal/postgres/command/clone_test.go +++ b/internal/postgres/command/clone_test.go @@ -301,3 +301,40 @@ func TestGetShowsCloneProgress(t *testing.T) { }) } } + +// Lord Howe Island shifts its clocks by 30 minutes, so a repeated or skipped local time cannot be +// found by trying one-hour offsets. +func TestParseLocalTimeWithHalfHourDaylightSaving(t *testing.T) { + lordHowe, err := time.LoadLocation("Australia/Lord_Howe") + if err != nil { + t.Fatal(err) + } + now := time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC) + for _, tt := range []struct { + name, value, wantError string + want time.Time + }{ + {name: "repeated half hour resolves to the earlier occurrence", value: "2026-04-05 01:45", want: time.Date(2026, 4, 4, 14, 45, 0, 0, time.UTC)}, + {name: "end of the repeated half hour is still the earlier occurrence", value: "2026-04-05 01:59:59", want: time.Date(2026, 4, 4, 14, 59, 59, 0, time.UTC)}, + {name: "first time after the repeat is unambiguous", value: "2026-04-05 02:00", want: time.Date(2026, 4, 4, 15, 30, 0, 0, time.UTC)}, + {name: "before the repeat is unambiguous", value: "2026-04-05 01:15", want: time.Date(2026, 4, 4, 14, 15, 0, 0, time.UTC)}, + {name: "half hour skipped in spring is rejected", value: "2026-10-04 02:15", wantError: "does not exist"}, + {name: "first time after the skipped half hour", value: "2026-10-04 02:30", want: time.Date(2026, 10, 3, 15, 30, 0, 0, time.UTC)}, + } { + t.Run(tt.name, func(t *testing.T) { + got, err := parseLocalTime(tt.value, lordHowe) + if tt.wantError != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantError) { + t.Fatalf("error = %v, want %q", err, tt.wantError) + } + return + } + if err != nil || !got.Equal(tt.want) { + t.Fatalf("got %v, %v; want %v", got.UTC(), err, tt.want) + } + if _, _, err := resolveCloneTime(tt.value, now, lordHowe); err != nil { + t.Errorf("resolveCloneTime: %v", err) + } + }) + } +}