@@ -13,6 +13,7 @@ type ActorIdentity struct {
|
||||
UnionID string `json:"union_id"`
|
||||
}
|
||||
type OrganizationVersion struct {
|
||||
RegionNames []string `json:"region_names"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
|
||||
@@ -31,7 +31,7 @@ func recordAttribution(ctx context.Context, config Config) (*qaopsorg.Attributio
|
||||
return p, nil
|
||||
}
|
||||
func attributionVersion(p *qaopsorg.Attribution) dobotaiops.OrganizationVersion {
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory"}
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory", RegionNames: p.Metadata.RegionLabels()}
|
||||
}
|
||||
func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) {
|
||||
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID)
|
||||
@@ -92,7 +92,7 @@ type qaUsage struct {
|
||||
|
||||
func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, query dobotaiops.RecordQuery) qaUsage {
|
||||
result := qaUsage{Organization: attributionVersion(p), AsOf: groups.AsOf, Start: query.Window.Start, End: query.Window.End, Keyword: query.Keyword, Rows: []qaUsageRow{}}
|
||||
keys := append(append([]string{}, qaopsorg.RegionNames...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
keys := append(append([]string{}, p.Metadata.RegionLabels()...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
rows := map[string]*qaUsageRow{}
|
||||
members := map[string]map[string]bool{}
|
||||
all := map[string]bool{}
|
||||
@@ -108,7 +108,12 @@ func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, qu
|
||||
n = p.Metadata.View.ConflictingPeople
|
||||
default:
|
||||
var ok bool
|
||||
n, ok = p.Metadata.View.Regions[key]
|
||||
for _, region := range p.Metadata.RegionDefinitions() {
|
||||
if region.Name == key {
|
||||
n, ok = p.Metadata.View.Regions[region.ID]
|
||||
break
|
||||
}
|
||||
}
|
||||
valid = ok
|
||||
}
|
||||
if valid {
|
||||
|
||||
@@ -97,11 +97,7 @@ func parseMonthlyFilter(values url.Values, now time.Time) (monthlyFilter, error)
|
||||
if f.Activity != "all" && f.Activity != "used" && f.Activity != "zero" {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
validRegion := f.Region == "" || f.Region == "unassigned" || f.Region == "cross_region"
|
||||
for _, r := range qaopsorg.RegionNames {
|
||||
validRegion = validRegion || f.Region == r
|
||||
}
|
||||
if !validRegion {
|
||||
if !utf8.ValidString(f.Region) || len(f.Region) > 256 || strings.TrimSpace(f.Region) != f.Region || strings.ContainsAny(f.Region, "\x00\r\n") {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !utf8.ValidString(f.Search) || utf8.RuneCountInString(f.Search) > 100 || strings.ContainsRune(f.Search, 0) {
|
||||
@@ -288,6 +284,16 @@ func qaMonthlyPeople(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Region != "" && f.Region != "unassigned" && f.Region != "cross_region" {
|
||||
found := false
|
||||
for _, name := range p.Metadata.RegionLabels() {
|
||||
found = found || f.Region == name
|
||||
}
|
||||
if !found {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Department != "" {
|
||||
found := false
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -36,9 +37,14 @@ func qaOrganization(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
var request qaopsorg.SaveRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
raw, readErr := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
var fields map[string]json.RawMessage
|
||||
var extra any
|
||||
invalidJSON := readErr != nil || json.Unmarshal(raw, &fields) != nil || fields == nil || fields["base_revision"] == nil || walkQualityJSON(check) != nil || check.Decode(&extra) != io.EOF
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&request) != nil || decoder.Decode(&struct{}{}) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
if invalidJSON || decoder.Decode(&request) != nil || decoder.Decode(&extra) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -52,6 +52,12 @@ func TestQAOrganizationGuardsIdentityIntentAndErrors(t *testing.T) {
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{} {}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":null}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":null,"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[null],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[{"id":"edu","name":null}],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[],"rules":[]}`, 400},
|
||||
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
{"POST", base + "/preview", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
} {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAUsageConsumesTheCustomRegionCatalog(t *testing.T) {
|
||||
p, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "fixture-directory", Regions: []qaopsorg.RegionDefinition{{ID: "edu", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "edu"}}}, qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "a", Name: "示例部门"}}, People: []qaopsorg.Person{{ID: "fixture-person", DepartmentIDs: []string{"a"}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
usage := summarizeQAUsage(dobotaiops.UsageGroups{Groups: []dobotaiops.UsageGroup{{Identity: dobotaiops.ActorIdentity{StaffID: "fixture-person"}, Total: 3, Succeeded: 2, Failed: 1}}}, p, dobotaiops.RecordQuery{})
|
||||
if usage.Questions != 3 || usage.IdentifiedUsers != 1 {
|
||||
t.Fatal("the historical whitelist dropped custom-region events")
|
||||
}
|
||||
found := false
|
||||
for _, row := range usage.Rows {
|
||||
if row.Key == "国内教育" {
|
||||
found = true
|
||||
if row.Questions != 3 || row.RosterPeople == nil || *row.RosterPeople != 1 || row.Users == nil || *row.Users != 1 {
|
||||
t.Fatal("custom-region counts or roster denominator were lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("custom-region row missing")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM qa_ops_region_revisions WHERE region_definitions <> '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb) THEN
|
||||
RAISE EXCEPTION 'custom region catalog exists; application rollback may keep migration 51, destructive catalog rollback refused';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE qa_ops_region_revisions DROP COLUMN region_definitions;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE qa_ops_region_revisions ADD COLUMN region_definitions JSONB NOT NULL DEFAULT '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb CHECK (jsonb_typeof(region_definitions)='array');
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 50 {
|
||||
t.Fatalf("migration count = %d, want 50", len(migrations))
|
||||
if len(migrations) != 51 {
|
||||
t.Fatalf("migration count = %d, want 51", len(migrations))
|
||||
}
|
||||
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
|
||||
t.Fatalf("migration 1 = %#v", migrations[0])
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegionCatalogMigrationIsAdditiveAndRefusesLossyDown(t *testing.T) {
|
||||
migrations, e := loadMigrations()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var up, down string
|
||||
for _, m := range migrations {
|
||||
if m.Version == 51 {
|
||||
up = m.UpSQL
|
||||
down = m.DownSQL
|
||||
}
|
||||
}
|
||||
for _, fragment := range []string{"ADD COLUMN region_definitions JSONB NOT NULL DEFAULT", "jsonb_typeof(region_definitions)='array'", "国内工业", "APAC", "EMEA", "America"} {
|
||||
if !strings.Contains(up, fragment) {
|
||||
t.Fatal("missing additive/backfill region contract", fragment)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(down, "RAISE EXCEPTION") || !strings.Contains(down, "region_definitions <>") || !strings.Contains(down, "DROP COLUMN region_definitions") {
|
||||
t.Fatal("lossy down migration was not guarded")
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
if state.State != "ready" || state.DirectoryID == "" {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
view, err := Preview(directory, state.Rules)
|
||||
view, err := PreviewRegions(directory, state.Rules, state.RegionDefinitions())
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
@@ -65,7 +65,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
if len(regions) == 1 {
|
||||
item.State = "matched"
|
||||
for region := range regions {
|
||||
item.Region = region
|
||||
item.Region = state.RegionLabel(region)
|
||||
}
|
||||
} else if len(regions) > 1 {
|
||||
item.State = "cross_region"
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package qaopsorg
|
||||
|
||||
import "unicode/utf8"
|
||||
|
||||
// IDs are immutable mapping keys; names are editable labels. Existing keys remain
|
||||
// intact when migrating the historical four-region configuration.
|
||||
type RegionDefinition struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func DefaultRegions() []RegionDefinition {
|
||||
result := make([]RegionDefinition, 0, len(RegionNames))
|
||||
for _, name := range RegionNames {
|
||||
result = append(result, RegionDefinition{ID: name, Name: name})
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (s State) RegionDefinitions() []RegionDefinition {
|
||||
if s.Regions == nil {
|
||||
return DefaultRegions()
|
||||
}
|
||||
return s.Regions
|
||||
}
|
||||
func (s State) RegionLabels() []string {
|
||||
labels := []string{}
|
||||
for _, region := range s.RegionDefinitions() {
|
||||
labels = append(labels, region.Name)
|
||||
}
|
||||
return labels
|
||||
}
|
||||
func (s State) RegionLabel(id string) string {
|
||||
for _, region := range s.RegionDefinitions() {
|
||||
if region.ID == id {
|
||||
return region.Name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func validRegions(regions []RegionDefinition) bool {
|
||||
if len(regions) > 100 {
|
||||
return false
|
||||
}
|
||||
reserved := map[string]bool{"unassigned": true, "cross_region": true, "unmatched": true, "identity_conflict": true, "no_identity": true, "directory_missing": true, "__proto__": true, "constructor": true, "prototype": true}
|
||||
ids, names := map[string]bool{}, map[string]bool{}
|
||||
for _, region := range regions {
|
||||
if !validID(region.ID) || !validID(region.Name) || !utf8.ValidString(region.ID) || !utf8.ValidString(region.Name) || reserved[region.ID] || reserved[region.Name] || ids[region.ID] || names[region.Name] {
|
||||
return false
|
||||
}
|
||||
ids[region.ID] = true
|
||||
names[region.Name] = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCustomRegionCatalogRejectsAmbiguousOrReservedDefinitions(t *testing.T) {
|
||||
for _, regions := range [][]RegionDefinition{
|
||||
{{ID: "one", Name: "国内教育"}, {ID: "one", Name: "国外工业Amercia"}},
|
||||
{{ID: "one", Name: "国内教育"}, {ID: "two", Name: "国内教育"}},
|
||||
{{ID: "unassigned", Name: "区域"}}, {{ID: "one", Name: "cross_region"}},
|
||||
{{ID: "__proto__", Name: "区域"}}, {{ID: "one", Name: "constructor"}},
|
||||
{{ID: "one", Name: ""}}, {{ID: "one", Name: " 区域"}},
|
||||
} {
|
||||
if _, err := PreviewRegions(exampleDirectory(), nil, regions); err == nil {
|
||||
t.Fatal("invalid region catalog was accepted")
|
||||
}
|
||||
}
|
||||
if _, err := PreviewRegions(exampleDirectory(), []Rule{{DepartmentID: "sales", Region: "missing"}}, []RegionDefinition{{ID: "education", Name: "国内教育"}}); err == nil {
|
||||
t.Fatal("unknown mapping ID accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomRegionCatalogBindsStableIDAndRenamePreservesRules(t *testing.T) {
|
||||
directory := exampleDirectory()
|
||||
state := State{State: "ready", DirectoryID: "d", Rules: []Rule{}}
|
||||
var request SaveRequest
|
||||
if err := json.Unmarshal([]byte(`{"directory_id":"d","base_revision":"","regions":[{"id":"education","name":"国内教育"},{"id":"overseas","name":"国外工业Amercia"}],"rules":[{"department_id":"sales","region":"education"},{"department_id":"apac","region":"overseas"}]}`), &request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := applyRequest(state, directory, request)
|
||||
if err != nil {
|
||||
t.Fatalf("custom business regions must not be rejected by the old four-name whitelist: %v", err)
|
||||
}
|
||||
if next.View.Regions["education"] != 1 || next.View.Regions["overseas"] != 1 || next.View.ConflictingPeople != 1 {
|
||||
t.Fatal("inheritance or stable-ID person dedup changed")
|
||||
}
|
||||
projection, err := BuildAttribution(next, directory)
|
||||
if err != nil || projection.Resolve("p2", "").Region != "国外工业Amercia" {
|
||||
t.Fatal("attribution did not use the same catalog display name")
|
||||
}
|
||||
raw, _ := json.Marshal(request)
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
body["regions"].([]any)[1].(map[string]any)["name"] = "国外工业 EMEA"
|
||||
raw, _ = json.Marshal(body)
|
||||
_ = json.Unmarshal(raw, &request)
|
||||
renamed, err := applyRequest(next, directory, request)
|
||||
if err != nil || renamed.Rules[0].Region != next.Rules[0].Region {
|
||||
t.Fatal("renaming changed the stable mapping")
|
||||
}
|
||||
projection, err = BuildAttribution(renamed, directory)
|
||||
if err != nil || projection.Resolve("p2", "").Region != "国外工业 EMEA" {
|
||||
t.Fatal("renamed catalog not consumed by attribution")
|
||||
}
|
||||
}
|
||||
@@ -46,12 +46,18 @@ type PreviewResult struct {
|
||||
|
||||
// Identity is department ID. Names and legacy keyword rules never decide ownership.
|
||||
func Preview(directory Directory, rules []Rule) (PreviewResult, error) {
|
||||
return PreviewRegions(directory, rules, DefaultRegions())
|
||||
}
|
||||
func PreviewRegions(directory Directory, rules []Rule, regions []RegionDefinition) (PreviewResult, error) {
|
||||
result := PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}, TotalPeople: len(directory.People)}
|
||||
if len(directory.Departments) == 0 || len(directory.Departments) > 20000 || len(directory.People) == 0 || len(directory.People) > 100000 || len(rules) > 20000 {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
for _, region := range RegionNames {
|
||||
result.Regions[region] = 0
|
||||
if !validRegions(regions) {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
for _, region := range regions {
|
||||
result.Regions[region.ID] = 0
|
||||
}
|
||||
departments := make(map[string]Department, len(directory.Departments))
|
||||
for _, d := range directory.Departments {
|
||||
|
||||
+32
-21
@@ -26,20 +26,22 @@ type Import struct {
|
||||
Directory Directory `json:"directory"`
|
||||
}
|
||||
type SaveRequest struct {
|
||||
DirectoryID string `json:"directory_id"`
|
||||
BaseRevision string `json:"base_revision"`
|
||||
Rules []Rule `json:"rules"`
|
||||
Regions []RegionDefinition `json:"regions,omitempty"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
BaseRevision string `json:"base_revision"`
|
||||
Rules []Rule `json:"rules"`
|
||||
}
|
||||
type State struct {
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
DirectorySyncedAt *time.Time `json:"directory_synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Rules []Rule `json:"rules"`
|
||||
View PreviewResult `json:"view"`
|
||||
Regions []RegionDefinition `json:"regions"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
DirectorySyncedAt *time.Time `json:"directory_synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Rules []Rule `json:"rules"`
|
||||
View PreviewResult `json:"view"`
|
||||
}
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
@@ -53,12 +55,14 @@ type orgQuerier interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}
|
||||
|
||||
const readStateSQL = `SELECT d.id,d.source,d.synced_at,d.payload,COALESCE(r.id,''),COALESCE(r.rules,'[]'::jsonb),COALESCE(r.updated_by,''),r.created_at
|
||||
const defaultRegionsJSON = `[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]`
|
||||
|
||||
const readStateSQL = `SELECT d.id,d.source,d.synced_at,d.payload,COALESCE(r.id,''),COALESCE(r.rules,'[]'::jsonb),COALESCE(r.updated_by,''),r.created_at,COALESCE(r.region_definitions,'` + defaultRegionsJSON + `'::jsonb)
|
||||
FROM qa_ops_organization_state st JOIN qa_ops_directory_snapshots d ON d.tenant_key=st.tenant_key AND d.id=st.directory_id
|
||||
LEFT JOIN qa_ops_region_revisions r ON r.tenant_key=st.tenant_key AND r.id=st.revision_id WHERE st.tenant_key=$1`
|
||||
|
||||
func (s *Store) read(ctx context.Context, q orgQuerier, lock bool) (State, Directory, error) {
|
||||
state := State{State: "empty", Rules: []Rule{}, View: PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}}}
|
||||
state := State{Regions: DefaultRegions(), State: "empty", Rules: []Rule{}, View: PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}}}
|
||||
for _, r := range RegionNames {
|
||||
state.View.Regions[r] = 0
|
||||
}
|
||||
@@ -67,15 +71,15 @@ func (s *Store) read(ctx context.Context, q orgQuerier, lock bool) (State, Direc
|
||||
if lock {
|
||||
query += " FOR UPDATE OF st"
|
||||
}
|
||||
var payload, rules []byte
|
||||
err := q.QueryRow(ctx, query, s.tenant).Scan(&state.DirectoryID, &state.DirectorySource, &state.DirectorySyncedAt, &payload, &state.RevisionID, &rules, &state.UpdatedBy, &state.UpdatedAt)
|
||||
var payload, rules, regions []byte
|
||||
err := q.QueryRow(ctx, query, s.tenant).Scan(&state.DirectoryID, &state.DirectorySource, &state.DirectorySyncedAt, &payload, &state.RevisionID, &rules, &state.UpdatedBy, &state.UpdatedAt, ®ions)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return state, directory, nil
|
||||
}
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil {
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil || json.Unmarshal(regions, &state.Regions) != nil || state.Regions == nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
state.View, err = Preview(directory, state.Rules)
|
||||
state.View, err = PreviewRegions(directory, state.Rules, state.RegionDefinitions())
|
||||
if err != nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
@@ -106,7 +110,11 @@ func applyRequest(state State, directory Directory, request SaveRequest) (State,
|
||||
if request.DirectoryID != state.DirectoryID || request.BaseRevision != state.RevisionID {
|
||||
return State{}, ErrConflict
|
||||
}
|
||||
view, err := Preview(directory, request.Rules)
|
||||
regions := request.Regions
|
||||
if regions == nil {
|
||||
regions = state.RegionDefinitions()
|
||||
}
|
||||
view, err := PreviewRegions(directory, request.Rules, regions)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
@@ -123,6 +131,7 @@ func applyRequest(state State, directory Directory, request SaveRequest) (State,
|
||||
}
|
||||
}
|
||||
state.View = view
|
||||
state.Regions = append([]RegionDefinition{}, regions...)
|
||||
state.Rules = append([]Rule{}, request.Rules...)
|
||||
sort.Slice(state.Rules, func(i, j int) bool { return state.Rules[i].DepartmentID < state.Rules[j].DepartmentID })
|
||||
return state, nil
|
||||
@@ -151,7 +160,9 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
sort.Slice(before, func(i, j int) bool { return before[i].DepartmentID < before[j].DepartmentID })
|
||||
oldJSON, _ := json.Marshal(before)
|
||||
newJSON, _ := json.Marshal(next.Rules)
|
||||
if current.RevisionID != "" && string(oldJSON) == string(newJSON) {
|
||||
oldRegions, _ := json.Marshal(current.RegionDefinitions())
|
||||
newRegions, _ := json.Marshal(next.RegionDefinitions())
|
||||
if current.RevisionID != "" && string(oldJSON) == string(newJSON) && string(oldRegions) == string(newRegions) {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
@@ -164,7 +175,7 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
next.RevisionID = "reg-" + hex.EncodeToString(nonce[:])
|
||||
next.UpdatedBy = actor
|
||||
var at time.Time
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO qa_ops_region_revisions(tenant_key,id,directory_id,rules,updated_by) VALUES($1,$2,$3,$4,$5) RETURNING created_at`, s.tenant, next.RevisionID, next.DirectoryID, newJSON, actor).Scan(&at); err != nil {
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO qa_ops_region_revisions(tenant_key,id,directory_id,rules,updated_by,region_definitions) VALUES($1,$2,$3,$4,$5,$6) RETURNING created_at`, s.tenant, next.RevisionID, next.DirectoryID, newJSON, actor, newRegions).Scan(&at); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
next.UpdatedAt = &at
|
||||
|
||||
@@ -134,6 +134,65 @@ func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) {
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM qa_ops_region_revisions WHERE tenant_key=$1", "fixture-tenant").Scan(&revisions); err != nil || revisions != 2 {
|
||||
t.Fatal("revision history changed unexpectedly")
|
||||
}
|
||||
|
||||
t.Run("custom catalog persists with the mapping and rename advances revision", func(t *testing.T) {
|
||||
custom := qaopsorg.NewStore(pool, "catalog-fixture")
|
||||
imported, e := custom.ReplaceDirectory(ctx, input)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
request := qaopsorg.SaveRequest{DirectoryID: imported.DirectoryID, Regions: []qaopsorg.RegionDefinition{{ID: "education", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "education"}}}
|
||||
preview, e := custom.PreviewRules(ctx, request)
|
||||
if e != nil || preview.View.Regions["education"] != 1 {
|
||||
t.Fatal("custom preview failed", e)
|
||||
}
|
||||
unchanged, _ := custom.GetView(ctx)
|
||||
if unchanged.RevisionID != "" {
|
||||
t.Fatal("catalog preview wrote data")
|
||||
}
|
||||
saved, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer fresh.Close()
|
||||
read, e := qaopsorg.NewStore(fresh, "catalog-fixture").GetView(ctx)
|
||||
if e != nil || len(read.Regions) != 1 || read.Regions[0].Name != "国内教育" || read.Rules[0].Region != "education" {
|
||||
t.Fatal("catalog was not persisted with its rules", e)
|
||||
}
|
||||
request.BaseRevision = saved.RevisionID
|
||||
request.Regions[0].Name = "国外工业Amercia"
|
||||
renamed, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil || renamed.RevisionID == saved.RevisionID {
|
||||
t.Fatal("rename did not create an atomic revision", e)
|
||||
}
|
||||
projection, e := custom.GetAttribution(ctx)
|
||||
if e != nil || projection.Resolve("u1", "").Region != "国外工业Amercia" {
|
||||
t.Fatal("renamed labels not shared by the read paths")
|
||||
}
|
||||
if _, e = custom.SaveRules(ctx, request, "stale-admin"); !errors.Is(e, qaopsorg.ErrConflict) {
|
||||
t.Fatal("rename allowed stale overwrite")
|
||||
}
|
||||
request.BaseRevision = renamed.RevisionID
|
||||
repeated, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil || repeated.RevisionID != renamed.RevisionID {
|
||||
t.Fatal("unchanged catalog appended another revision")
|
||||
}
|
||||
if e = postgresstore.RollbackLatestMigration(ctx, pool); e == nil {
|
||||
t.Fatal("down migration discarded a custom catalog")
|
||||
}
|
||||
if _, e = custom.GetView(ctx); e != nil {
|
||||
t.Fatal("refused down migration damaged last-good catalog")
|
||||
}
|
||||
for _, table := range []string{"qa_ops_organization_state", "qa_ops_region_revisions", "qa_ops_directory_snapshots"} {
|
||||
if _, e = pool.Exec(ctx, "DELETE FROM "+table+" WHERE tenant_key=$1", "catalog-fixture"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
})
|
||||
// This test exercises migration 48, not whichever unrelated migration is latest.
|
||||
for {
|
||||
var latest int64
|
||||
|
||||
Reference in New Issue
Block a user