...
1 package retriever
2
3 import (
4 "context"
5 "database/sql"
6 "fmt"
7 "slices"
8
9 "edge-infra.dev/pkg/lib/fog"
10 "edge-infra.dev/pkg/sds/emergencyaccess/apierror"
11 )
12
13
14
15
16 type Client struct {
17 db *sql.DB
18 }
19
20
21 func New(db *sql.DB) (*Client, error) {
22 return &Client{db: db}, nil
23 }
24
25
26 func (c *Client) Artifact(ctx context.Context, name string, artifactType ArtifactType) (Artifact, error) {
27 artifact := Artifact{
28 Name: name,
29 Type: artifactType,
30 }
31
32 err := verifyArtifactType(artifactType)
33 if err != nil {
34 return artifact, err
35 }
36
37 row := c.db.QueryRowContext(ctx, sqlStmt, name, artifactType)
38 err = row.Scan(&artifact.Artifact, &artifact.SHA)
39 switch {
40 case err == sql.ErrNoRows:
41 return artifact, apierror.E(
42 apierror.ErrUnknownCommand,
43 fmt.Errorf("unknown artifact: (name: %q), (type: %q)", name, string(artifactType)),
44 fmt.Sprintf("Command %q of type %q is unknown", name, userType(artifactType)),
45 )
46 case err != nil:
47 return artifact, fmt.Errorf("error scanning row: %w", err)
48 }
49
50 fog.FromContext(ctx).Info(
51 "Retrieved artifact from the db",
52 "artifactName", artifact.Name,
53 "artifactType", artifact.Type,
54 "artifactSHA", fmt.Sprintf("%x", artifact.SHA),
55 )
56
57 return artifact, nil
58 }
59
60
61 func verifyArtifactType(artifactType ArtifactType) error {
62 if !slices.Contains(allArtifactTypes, artifactType) {
63 return fmt.Errorf("unknown artifact type: %q", artifactType)
64 }
65 return nil
66 }
67
68
69 func userType(artifactType ArtifactType) string {
70 name := ""
71 if artifactType == Executable {
72 name = "script"
73 }
74 return name
75 }
76
View as plain text