-
Notifications
You must be signed in to change notification settings - Fork 111
/
github.go
231 lines (192 loc) · 5.13 KB
/
github.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package github
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"time"
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/eapache/go-resiliency/retrier"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/rilldata/rill/runtime/drivers"
"go.uber.org/zap"
)
const (
retryN = 3
retryWait = 500 * time.Millisecond
)
type DSN struct {
GithubURL string `json:"github_url"`
Subpath string `json:"subpath"`
Branch string `json:"branch"`
InstallationID int64 `json:"installation_id"`
}
func init() {
drivers.Register("github", driver{})
}
type driver struct{}
func (d driver) Open(dsnStr string, logger *zap.Logger) (drivers.Connection, error) {
var dsn DSN
err := json.Unmarshal([]byte(dsnStr), &dsn)
if err != nil {
return nil, err
}
var c *connection
r := retrier.New(retrier.ExponentialBackoff(retryN, retryWait), nil)
err = r.Run(func() error {
tempdir, err := os.MkdirTemp("", "github_repo_driver")
if err != nil {
return err
}
tempdir, err = filepath.Abs(tempdir)
if err != nil {
return err
}
projectDir := tempdir
if dsn.Subpath != "" {
projectDir = filepath.Join(tempdir, dsn.Subpath)
}
c = &connection{
dsnStr: dsnStr,
dsn: dsn,
tempdir: tempdir,
projectdir: projectDir,
}
err = c.clone(context.Background())
if err != nil {
_ = os.RemoveAll(tempdir)
return err
}
return nil
})
if err != nil {
return nil, err
}
return c, nil
}
type connection struct {
dsnStr string
dsn DSN
// tempdir path should be absolute
tempdir string
projectdir string
cloneURLWithToken string
cloneURLRefreshedOn time.Time
}
// Close implements drivers.Connection.
func (c *connection) Close() error {
err := os.RemoveAll(c.tempdir)
if err != nil {
return err
}
return nil
}
// Registry implements drivers.Connection.
func (c *connection) RegistryStore() (drivers.RegistryStore, bool) {
return nil, false
}
// Catalog implements drivers.Connection.
func (c *connection) CatalogStore() (drivers.CatalogStore, bool) {
return nil, false
}
// Repo implements drivers.Connection.
func (c *connection) RepoStore() (drivers.RepoStore, bool) {
return c, true
}
// OLAP implements drivers.Connection.
func (c *connection) OLAPStore() (drivers.OLAPStore, bool) {
return nil, false
}
// Migrate implements drivers.Connection.
func (c *connection) Migrate(ctx context.Context) (err error) {
return nil
}
// MigrationStatus implements drivers.Connection.
func (c *connection) MigrationStatus(ctx context.Context) (current, desired int, err error) {
return 0, 0, nil
}
// clone runs the initial clone of the repo.
func (c *connection) clone(ctx context.Context) error {
cloneURL, err := c.cloneURL(ctx)
if err != nil {
return err
}
_, err = git.PlainClone(c.tempdir, false, &git.CloneOptions{
URL: cloneURL,
ReferenceName: plumbing.NewBranchReferenceName(c.dsn.Branch),
SingleBranch: true,
})
if err != nil {
return err
}
return nil
}
// pull pulls changes from the repo. It must have been successfully cloned already.
func (c *connection) pull(ctx context.Context) error {
cloneURL, err := c.cloneURL(ctx)
if err != nil {
return err
}
repo, err := git.PlainOpen(c.tempdir)
if err != nil {
return err
}
wt, err := repo.Worktree()
if err != nil {
return err
}
err = wt.Pull(&git.PullOptions{RemoteURL: cloneURL})
if errors.Is(err, git.NoErrAlreadyUpToDate) {
return nil
} else if err != nil {
return err
}
return nil
}
const cloneURLTTL = 30 * time.Minute
// renewCloneURL retrieves a new clone URL containing an authentication token for the repo.
func (c *connection) cloneURL(ctx context.Context) (string, error) {
// Return cached token if not expired
if c.cloneURLWithToken != "" && time.Since(c.cloneURLRefreshedOn) < cloneURLTTL {
return c.cloneURLWithToken, nil
}
// This driver expects Github App credentials to be available from the environment.
// TODO: The parsing probably should not happen here.
appID, _ := strconv.ParseInt(os.Getenv("RILL_RUNTIME_GITHUB_APP_ID"), 10, 64)
if appID == 0 {
return "", fmt.Errorf("invalid value provided for RILL_RUNTIME_GITHUB_APP_ID")
}
privateKey := os.Getenv("RILL_RUNTIME_GITHUB_APP_PRIVATE_KEY")
if privateKey == "" {
return "", fmt.Errorf("invalid value provided for RILL_RUNTIME_GITHUB_APP_PRIVATE_KEY")
}
// Get a Github token for this installation ID
itr, err := ghinstallation.New(http.DefaultTransport, appID, c.dsn.InstallationID, []byte(privateKey))
if err != nil {
log.Fatal(err)
}
token, err := itr.Token(ctx)
if err != nil {
return "", err
}
// Create clone URL
ep, err := transport.NewEndpoint(c.dsn.GithubURL + ".git") // TODO: Can the clone URL be different from the HTTP URL of a Github repo?
if err != nil {
return "", fmt.Errorf("failed to create endpoint from %q: %w", c.dsn.GithubURL, err)
}
ep.User = "x-access-token"
ep.Password = token
cloneURL := ep.String()
// Cache it
c.cloneURLWithToken = cloneURL
c.cloneURLRefreshedOn = time.Now()
// Done
return cloneURL, nil
}