|
| 1 | +package plan |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/sha256" |
| 6 | + "database/sql" |
| 7 | + "encoding/hex" |
| 8 | + "errors" |
| 9 | + "fmt" |
| 10 | + "sort" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/LAA-Software-Engineering/agentic-control-plane/internal/state" |
| 14 | +) |
| 15 | + |
| 16 | +// DeploymentStateFingerprint returns a stable SHA-256 hex digest of deployment rows for env. |
| 17 | +// It covers every applied_resources row for env (kind, name, spec hash, normalized JSON) and |
| 18 | +// the applied_projects row for (env, projectName), or a sentinel when that row is missing. |
| 19 | +// Used for optimistic concurrency between plan and apply (issue #78). |
| 20 | +func DeploymentStateFingerprint(ctx context.Context, dep state.DeploymentStore, env, projectName string) (string, error) { |
| 21 | + if dep == nil { |
| 22 | + return "", errors.New("plan: nil deployment store") |
| 23 | + } |
| 24 | + env = strings.TrimSpace(env) |
| 25 | + projectName = strings.TrimSpace(projectName) |
| 26 | + if env == "" || projectName == "" { |
| 27 | + return "", errors.New("plan: empty env or project name") |
| 28 | + } |
| 29 | + list, err := dep.ListAppliedResourcesByEnv(ctx, env) |
| 30 | + if err != nil { |
| 31 | + return "", err |
| 32 | + } |
| 33 | + sort.Slice(list, func(i, j int) bool { |
| 34 | + if list[i].Kind != list[j].Kind { |
| 35 | + return list[i].Kind < list[j].Kind |
| 36 | + } |
| 37 | + return list[i].Name < list[j].Name |
| 38 | + }) |
| 39 | + var b strings.Builder |
| 40 | + for _, r := range list { |
| 41 | + fmt.Fprintf(&b, "%s\x00%s\x00%s\x00%s\n", r.Kind, r.Name, r.SpecHash, r.NormalizedSpecJSON) |
| 42 | + } |
| 43 | + proj, err := dep.GetAppliedProject(ctx, env, projectName) |
| 44 | + switch { |
| 45 | + case err != nil && errors.Is(err, sql.ErrNoRows): |
| 46 | + b.WriteString("applied_projects\x00MISSING\n") |
| 47 | + case err != nil: |
| 48 | + return "", err |
| 49 | + default: |
| 50 | + if proj == nil { |
| 51 | + b.WriteString("applied_projects\x00MISSING\n") |
| 52 | + } else { |
| 53 | + fmt.Fprintf(&b, "applied_projects\x00%s\x00%s\x00%s\n", proj.ProjectName, proj.Env, proj.Version) |
| 54 | + } |
| 55 | + } |
| 56 | + sum := sha256.Sum256([]byte(b.String())) |
| 57 | + return hex.EncodeToString(sum[:]), nil |
| 58 | +} |
0 commit comments