|
| 1 | +// Copyright 2025 syzkaller project authors. All rights reserved. |
| 2 | +// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. |
| 3 | + |
| 4 | +package aidb |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + |
| 9 | + "cloud.google.com/go/spanner" |
| 10 | + //"google.golang.org/api/iterator" |
| 11 | + "google.golang.org/appengine/v2" |
| 12 | +) |
| 13 | + |
| 14 | +func LoadWorkflows(ctx context.Context) ([]*Workflow, error) { |
| 15 | + client, err := dbClient(ctx) |
| 16 | + if err != nil { |
| 17 | + return nil, err |
| 18 | + } |
| 19 | + defer client.Close() |
| 20 | + iter := client.Single().Query(ctx, spanner.Statement{ |
| 21 | + SQL: `select * from workflows`, |
| 22 | + }) |
| 23 | + defer iter.Stop() |
| 24 | + var workflows []*Workflow |
| 25 | + err = spanner.SelectAll(iter, &workflows) |
| 26 | + return workflows, err |
| 27 | +} |
| 28 | + |
| 29 | +func LoadActiveWorkflows(ctx context.Context) ([]string, error) { |
| 30 | + workflows, err := LoadWorkflows(ctx) |
| 31 | + if err != nil { |
| 32 | + return nil, err |
| 33 | + } |
| 34 | + var active []string |
| 35 | + for _, flow := range workflows { |
| 36 | + if flow.Active { |
| 37 | + active = append(active, flow.Name) |
| 38 | + } |
| 39 | + } |
| 40 | + return active, nil |
| 41 | +} |
| 42 | + |
| 43 | +func UpdateWorkflows(ctx context.Context, active []string) error { |
| 44 | + workflows, err := LoadWorkflows(ctx) |
| 45 | + if err != nil { |
| 46 | + return err |
| 47 | + } |
| 48 | + m := make(map[string]bool) |
| 49 | + for _, flow := range active { |
| 50 | + m[flow] = true |
| 51 | + } |
| 52 | + update := false |
| 53 | + for _, flow := range workflows { |
| 54 | + active := m[flow.Name] |
| 55 | + delete(m, flow.Name) |
| 56 | + if flow.Active != active { |
| 57 | + update = true |
| 58 | + flow.Active = active |
| 59 | + } |
| 60 | + } |
| 61 | + for name := range m { |
| 62 | + update = true |
| 63 | + workflows = append(workflows, &Workflow{ |
| 64 | + Name: name, |
| 65 | + Active: true, |
| 66 | + }) |
| 67 | + } |
| 68 | + if !update { |
| 69 | + return nil |
| 70 | + } |
| 71 | + client, err := dbClient(ctx) |
| 72 | + if err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + defer client.Close() |
| 76 | + var mutations []*spanner.Mutation |
| 77 | + for _, flow := range workflows { |
| 78 | + mut, err := spanner.InsertOrUpdateStruct("workflows", flow) |
| 79 | + if err != nil { |
| 80 | + return err |
| 81 | + } |
| 82 | + mutations = append(mutations, mut) |
| 83 | + } |
| 84 | + _, err = client.Apply(ctx, mutations) |
| 85 | + return err |
| 86 | +} |
| 87 | + |
| 88 | +func dbClient(ctx context.Context) (*spanner.Client, error) { |
| 89 | + database := "projects/" + appengine.AppID(ctx) + "/instances/syzbot/databases/ai" |
| 90 | + return spanner.NewClient(ctx, database) |
| 91 | +} |
0 commit comments