Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
292 lines (273 loc) · 11.2 KB
/
Copy pathclient.go
File metadata and controls
292 lines (273 loc) · 11.2 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package gitsync
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"entire.io/entire/git-sync/internal/syncer"
"entire.io/entire/git-sync/internal/validation"
)
// Options configures a Client. It is intentionally small in the first public cut.
type Options struct {
HTTPClient *http.Client
Auth AuthProvider
// BootstrapLogger receives one structured diagnostic per checkpoint upload,
// including failures, and one per GitHub repository-size lookup (warning
// level when the size could not be read), independently of verbose
// protocol logging. Nil disables these diagnostics. Bytes read are not
// proof of bytes accepted by the target.
BootstrapLogger *slog.Logger
// BootstrapFallbackMaxPackBytes bounds indivisible checkpoint uploads when
// the target has not announced a limit. Positive values disable projection
// and the batching margin for these uploads only. Non-positive disables the
// fallback. This is local policy, not evidence of the target's capacity.
BootstrapFallbackMaxPackBytes int64
}
// Client provides the public orchestration API for git-sync.
type Client struct {
httpClient *http.Client
auth AuthProvider
bootstrapLogger *slog.Logger
bootstrapFallbackMaxPackBytes int64
}
// New constructs a new Client.
func New(opts Options) *Client {
return &Client{httpClient: opts.HTTPClient, auth: opts.Auth, bootstrapLogger: opts.BootstrapLogger, bootstrapFallbackMaxPackBytes: opts.BootstrapFallbackMaxPackBytes}
}
// Probe inspects a source remote and optional target remote.
func (c *Client) Probe(ctx context.Context, req ProbeRequest) (ProbeResult, error) {
if err := req.Validate(); err != nil {
return ProbeResult{}, err
}
cfg, err := c.buildProbeConfig(ctx, req)
if err != nil {
return ProbeResult{}, err
}
result, err := syncer.Probe(ctx, cfg)
if err != nil {
return ProbeResult{}, fmt.Errorf("probe: %w", err)
}
return fromProbeResult(result), nil
}
// Plan computes ref actions without pushing.
//
// On a run that reached the remotes, the returned PlanResult is populated even when
// the error is non-nil: Execution carries the strategy that ran (OperationMode,
// TransferMode, Reason, Batch) and Refs the plan it attempted, so a caller can
// report WHICH path failed rather than only that something did. Counts are NOT
// populated on that path — Applied is 0 even where refs were pushed before the
// failure — so read Refs for what was attempted and ignore Counts entirely.
//
// A request that never got that far — Validate or config resolution failing —
// still returns a zero PlanResult, since there is no run to describe.
func (c *Client) Plan(ctx context.Context, req PlanRequest) (PlanResult, error) {
if err := req.Validate(); err != nil {
return PlanResult{}, err
}
cfg, err := c.buildSyncConfig(ctx, SyncRequest(req), true)
if err != nil {
return PlanResult{}, err
}
result, err := syncer.Run(ctx, cfg)
if err != nil {
return fromSyncResult(result), fmt.Errorf("plan: %w", err)
}
return fromSyncResult(result), nil
}
// Sync executes a sync between two remotes.
//
// On a run that reached the remotes, the returned SyncResult is populated even when
// the error is non-nil: Execution carries the strategy that ran (OperationMode,
// TransferMode, Reason, Batch) and Refs the plan it attempted, so a caller can
// report WHICH path failed rather than only that something did. Counts are NOT
// populated on that path — Applied is 0 even where refs were pushed before the
// failure — so read Refs for what was attempted and ignore Counts entirely.
//
// A request that never got that far — Validate or config resolution failing —
// still returns a zero SyncResult, since there is no run to describe.
func (c *Client) Sync(ctx context.Context, req SyncRequest) (SyncResult, error) {
if err := req.Validate(); err != nil {
return SyncResult{}, err
}
cfg, err := c.buildSyncConfig(ctx, req, false)
if err != nil {
return SyncResult{}, err
}
result, err := syncer.Run(ctx, cfg)
if err != nil {
return fromSyncResult(result), fmt.Errorf("sync: %w", err)
}
return fromSyncResult(result), nil
}
// Replicate executes source-authoritative relay-only replication between two remotes.
//
// Populates the returned SyncResult on error the same way Sync does.
func (c *Client) Replicate(ctx context.Context, req SyncRequest) (SyncResult, error) {
req.Policy.Mode = ModeReplicate
return c.Sync(ctx, req)
}
func (c *Client) buildProbeConfig(ctx context.Context, req ProbeRequest) (syncer.Config, error) {
sourceAuth, err := c.authFor(ctx, req.Source, SourceRole)
if err != nil {
return syncer.Config{}, err
}
cfg := syncer.Config{
Source: syncerEndpoint(req.Source, sourceAuth),
HTTPClient: c.httpClient,
IncludeTags: req.IncludeTags,
AllRefs: req.AllRefs,
ExcludeRefPrefixes: append([]string(nil), req.ExcludeRefPrefixes...),
ShowStats: req.CollectStats,
ProtocolMode: string(req.Protocol),
}
if req.Target != nil {
targetAuth, err := c.authFor(ctx, *req.Target, TargetRole)
if err != nil {
return syncer.Config{}, err
}
cfg.Target = syncerEndpoint(*req.Target, targetAuth)
}
return cfg, nil
}
func (c *Client) buildSyncConfig(ctx context.Context, req SyncRequest, dryRun bool) (syncer.Config, error) {
sourceAuth, err := c.authFor(ctx, req.Source, SourceRole)
if err != nil {
return syncer.Config{}, err
}
targetAuth, err := c.authFor(ctx, req.Target, TargetRole)
if err != nil {
return syncer.Config{}, err
}
return syncer.Config{
Source: syncerEndpoint(req.Source, sourceAuth),
Target: syncerEndpoint(req.Target, targetAuth),
BootstrapLogger: c.bootstrapLogger,
BootstrapFallbackMaxPackBytes: c.bootstrapFallbackMaxPackBytes,
HTTPClient: c.httpClient,
Branches: append([]string(nil), req.Scope.Branches...),
Mappings: validationMappings(req.Scope.Mappings),
AllRefs: req.Scope.AllRefs,
ExcludeRefPrefixes: append([]string(nil), req.Scope.ExcludeRefPrefixes...),
ExcludeRefs: append([]string(nil), req.Scope.ExcludeRefs...),
IncludeRefPrefixes: append([]string(nil), req.Scope.IncludeRefPrefixes...),
IncludeTags: req.Policy.IncludeTags,
DryRun: dryRun,
ShowStats: req.CollectStats,
Mode: string(req.Policy.Mode),
ForceWithLease: req.Policy.ForceWithLease,
ForceBlind: req.Policy.ForceBlind,
Prune: req.Policy.Prune,
BestEffort: req.Policy.BestEffort,
AllowEmptySource: req.Policy.AllowEmptySource,
AllowEmptyScope: req.Policy.AllowEmptyScope,
SourceAssertedEmpty: req.Policy.SourceAssertedEmpty,
TargetAssertedEmpty: req.Policy.TargetAssertedEmpty,
ProtocolMode: string(req.Policy.Protocol),
MaterializedMaxObjects: syncer.DefaultMaterializedMaxObjects,
}, nil
}
func (c *Client) authFor(ctx context.Context, endpoint Endpoint, role EndpointRole) (EndpointAuth, error) {
if c.auth == nil {
return EndpointAuth{}, nil
}
auth, err := c.auth.AuthFor(ctx, endpoint, role)
if err != nil {
return EndpointAuth{}, fmt.Errorf("resolve auth for %s: %w", role, err)
}
return auth, nil
}
func (r SyncRequest) Validate() error {
return validateSyncFields(r.Source, r.Target, r.Scope, r.Policy)
}
func (r PlanRequest) Validate() error {
return validateSyncFields(r.Source, r.Target, r.Scope, r.Policy)
}
// validateSyncFields validates the fields shared by SyncRequest and
// PlanRequest, whose Validate methods are otherwise identical.
func validateSyncFields(source, target Endpoint, scope RefScope, policy SyncPolicy) error {
if source.URL == "" {
return errors.New("source URL is required")
}
if target.URL == "" {
return errors.New("target URL is required")
}
if err := validateOperationMode(policy.Mode); err != nil {
return err
}
if err := policy.Validate(); err != nil {
return err
}
if _, err := validation.NormalizeProtocolMode(string(policy.Protocol)); err != nil {
return fmt.Errorf("normalize protocol: %w", err)
}
if _, err := validation.ValidateMappings(validationMappings(scope.Mappings), scope.AllRefs); err != nil {
return fmt.Errorf("validate mappings: %w", err)
}
// The half of the AllowEmptySource contract that needs the scope as well as
// the policy, so it cannot live on SyncPolicy.Validate. Silently accepting
// it left the caller with the historical "no source refs matched" and no
// hint that their policy had been discarded.
if policy.AllowEmptySource && !scope.AllRefs {
return errors.New("AllowEmptySource requires Scope.AllRefs; a narrowed scope cannot establish that a repository is empty")
}
// The scoped members of the same family. The syncer repeats them at the
// edge that covers the callers which bypass this one.
if err := validation.ValidateIncludeRefPrefixes(scope.IncludeRefPrefixes); err != nil {
return fmt.Errorf("validate include ref prefixes: %w", err)
}
if policy.AllowEmptyScope && len(scope.IncludeRefPrefixes) == 0 {
return errors.New("AllowEmptyScope requires Scope.IncludeRefPrefixes; without a scope to be empty the policy has nothing to act on")
}
// The empty-scope rule reads "the source advertised refs" off a listing
// AllRefs keeps unnarrowed; under a narrower scope RefPrefixes asks for
// refs/heads/ alone, so a refs/tags/ include prefix would see an empty
// advertisement for a reason that has nothing to do with the namespace.
if policy.AllowEmptyScope && !scope.AllRefs {
return errors.New("AllowEmptyScope requires Scope.AllRefs; a narrowed listing cannot tell an empty namespace from one it never asked about")
}
if policy.AllowEmptySource && len(scope.IncludeRefPrefixes) > 0 {
return errors.New("AllowEmptySource and Scope.IncludeRefPrefixes are mutually exclusive; a prefix-scoped listing cannot establish that a repository is empty (use AllowEmptyScope)")
}
return nil
}
func (r ProbeRequest) Validate() error {
if r.Source.URL == "" {
return errors.New("source URL is required")
}
if r.Target != nil && r.Target.URL == "" {
return errors.New("target URL is required when target endpoint is provided")
}
if _, err := validation.NormalizeProtocolMode(string(r.Protocol)); err != nil {
return fmt.Errorf("normalize protocol: %w", err)
}
return nil
}
func syncerEndpoint(ep Endpoint, auth EndpointAuth) syncer.Endpoint {
return syncer.Endpoint{
URL: ep.URL,
Username: auth.Username,
Token: auth.Token,
BearerToken: auth.BearerToken,
SkipTLSVerify: auth.SkipTLSVerify,
FollowInfoRefsRedirect: ep.FollowInfoRefsRedirect,
}
}
func validateOperationMode(mode OperationMode) error {
switch mode {
case "", ModeSync, ModeReplicate:
return nil
default:
return fmt.Errorf("unsupported operation mode %q", mode)
}
}
func validationMappings(mappings []RefMapping) []validation.RefMapping {
out := make([]validation.RefMapping, 0, len(mappings))
for _, mapping := range mappings {
out = append(out, validation.RefMapping{
Source: mapping.Source,
Target: mapping.Target,
})
}
return out
}