-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplanetary.go
More file actions
290 lines (255 loc) · 7.79 KB
/
Copy pathplanetary.go
File metadata and controls
290 lines (255 loc) · 7.79 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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
var planetarySTACURL = "https://planetarycomputer.microsoft.com/api/stac/v1"
// planetaryTokenResponse is the SAS token returned by Planetary Computer.
type planetaryTokenResponse struct {
Expiry string `json:"msft:expiry"`
Token string `json:"token"`
}
// planetaryTokenCache holds a cached SAS token and its expiry.
type planetaryTokenCache struct {
mu sync.RWMutex
token string
expiry time.Time
account string
container string
}
var planetarySASCache = &planetaryTokenCache{}
// getPlanetarySASToken returns a cached SAS token or fetches a new one.
func getPlanetarySASToken(account, container string) (string, error) {
planetarySASCache.mu.RLock()
cached, expiry := planetarySASCache.token, planetarySASCache.expiry
cachedAccount, cachedContainer := planetarySASCache.account, planetarySASCache.container
planetarySASCache.mu.RUnlock()
if cached != "" && time.Now().Add(5*time.Minute).Before(expiry) &&
cachedAccount == account && cachedContainer == container {
return cached, nil
}
planetarySASCache.mu.Lock()
defer planetarySASCache.mu.Unlock()
// double-check after acquiring write lock
if planetarySASCache.token != "" && time.Now().Add(5*time.Minute).Before(planetarySASCache.expiry) &&
planetarySASCache.account == account && planetarySASCache.container == container {
return planetarySASCache.token, nil
}
tokenURL := fmt.Sprintf("https://planetarycomputer.microsoft.com/api/sas/v1/token/%s/%s", account, container)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
client := newHTTPClient(30 * time.Second)
// The anonymous SAS token endpoint is rate-limited (HTTP 429). Retry a few
// times, honoring Retry-After when the server provides it.
const maxAttempts = 4
var body []byte
for attempt := 0; attempt < maxAttempts; attempt++ {
req, err := http.NewRequestWithContext(ctx, "GET", tokenURL, nil)
if err != nil {
return "", fmt.Errorf("create token request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
if attempt < maxAttempts-1 {
time.Sleep(time.Duration(attempt+1) * 2 * time.Second)
continue
}
return "", fmt.Errorf("token request failed: %w", err)
}
b, readErr := io.ReadAll(resp.Body)
statusCode := resp.StatusCode
retryAfter := resp.Header.Get("Retry-After")
resp.Body.Close()
if readErr != nil {
return "", fmt.Errorf("read token response: %w", readErr)
}
if statusCode == http.StatusOK {
body = b
break
}
if (statusCode == http.StatusTooManyRequests || statusCode >= 500) && attempt < maxAttempts-1 {
wait := time.Duration(attempt+1) * 2 * time.Second
if retryAfter != "" {
if secs, perr := strconv.Atoi(strings.TrimSpace(retryAfter)); perr == nil && secs > 0 {
wait = time.Duration(secs) * time.Second
}
}
time.Sleep(wait)
continue
}
return "", fmt.Errorf("token endpoint returned %d: %s", statusCode, string(b))
}
if body == nil {
return "", fmt.Errorf("SAS token endpoint rate-limited after %d attempts", maxAttempts)
}
var tr planetaryTokenResponse
if err := json.Unmarshal(body, &tr); err != nil {
return "", fmt.Errorf("decode token response: %w", err)
}
if tr.Token == "" {
return "", fmt.Errorf("empty SAS token returned")
}
expiry, perr := time.Parse(time.RFC3339, tr.Expiry)
if perr != nil {
expiry = time.Now().Add(1 * time.Hour)
}
planetarySASCache.token = tr.Token
planetarySASCache.expiry = expiry
planetarySASCache.account = account
planetarySASCache.container = container
return tr.Token, nil
}
// signPlanetaryAssetHref appends a SAS token to a Planetary Computer blob URL.
func signPlanetaryAssetHref(href string) (string, error) {
u, err := url.Parse(href)
if err != nil {
return "", fmt.Errorf("parse asset href: %w", err)
}
if !strings.Contains(u.Host, ".blob.core.windows.net") {
return href, nil
}
parts := strings.SplitN(strings.TrimPrefix(u.Path, "/"), "/", 2)
if len(parts) != 2 {
return "", fmt.Errorf("unexpected blob path: %s", u.Path)
}
account := strings.TrimSuffix(u.Host, ".blob.core.windows.net")
container := parts[0]
token, err := getPlanetarySASToken(account, container)
if err != nil {
return "", err
}
sep := "?"
if u.RawQuery != "" {
sep = "&"
}
return href + sep + token, nil
}
// runPlanetaryFlow downloads Landsat data from Microsoft Planetary Computer.
func runPlanetaryFlow(cfg *Config, auth Authenticator, destDir string) error {
sat := SatelliteType(cfg.Satellite)
if sat == "" {
sat = SatS2L2A
}
sc := satelliteConfigs[sat]
if len(cfg.Bands) == 0 {
cfg.Bands = sc.DefaultBands
}
c := *cfg
c.STACURL = planetarySTACURL
c.Collection = "landsat-c2-l2"
fmt.Println("\n=== Planetary Computer Search ===")
fmt.Printf(" Collection: %s\n", c.Collection)
fmt.Printf(" BBox: %v\n", c.BBox)
fmt.Printf(" Date: %s to %s\n", c.StartDate, c.EndDate)
if sc.NeedsCloudFilter {
fmt.Printf(" Cloud: %.0f%% - %.0f%%\n", c.MinCloud, c.MaxCloud)
}
fmt.Printf(" Bands: %v\n\n", c.Bands)
// Reuse STAC search.
opts := SearchOptions{
Bbox: c.BBox,
StartDate: c.StartDate,
EndDate: c.EndDate,
Limit: c.Limit,
MinCloud: c.MinCloud,
MaxCloud: c.MaxCloud,
STACURL: c.STACURL,
Collection: c.Collection,
Satellite: sat,
}
// landsat-c2-l2 mixes Landsat 8 and 9; restrict to the requested platform.
if sat == SatLandsat8 || sat == SatLandsat9 {
opts.Platform = string(sat)
}
stacCollection, err := SearchItems(opts, NoOpAuth{})
if err != nil {
return fmt.Errorf("search failed: %w", err)
}
if len(stacCollection.Features) == 0 {
return fmt.Errorf("no items found")
}
items := FilterItemsByCloud(stacCollection.Features, c.MinCloud, c.MaxCloud, sat)
PrintItemSummary(items)
fmt.Println("\n=== Saving KML ===")
for _, item := range items {
if _, err := SaveKML(item, destDir); err != nil {
fmt.Fprintf(os.Stderr, " [kml skip] %s: %v\n", item.ID, err)
}
}
fmt.Println("\n=== Downloading Bands ===")
tasks := make(chan downloadTask, c.MaxWorkers*2)
results := make(chan downloadResult, c.MaxWorkers*2)
var wg sync.WaitGroup
for i := 0; i < c.MaxWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
downloadWorker(tasks, results)
}()
}
go func() {
wg.Wait()
close(results)
}()
go func() {
for _, item := range items {
for _, band := range c.Bands {
assetKey := resolveAssetKey(band, c.STACURL, sat)
asset, ok := item.Assets[assetKey]
if !ok {
fmt.Printf(" [warn] band '%s' not available (tried '%s')\n", band, assetKey)
continue
}
signedHref, err := signPlanetaryAssetHref(asset.Href)
if err != nil {
fmt.Fprintf(os.Stderr, " [warn] failed to sign %s/%s: %v\n", item.ID, band, err)
continue
}
asset.Href = signedHref
tasks <- downloadTask{itemID: item.ID, band: band, asset: asset, destDir: destDir, maxRetries: c.MaxRetries, auth: NoOpAuth{}}
}
}
close(tasks)
}()
failed := 0
skipped := 0
total := 0
for res := range results {
total++
if res.skipped {
fmt.Printf(" [skip] %s_%s.tif already exists\n", res.task.itemID, res.task.band)
skipped++
} else if res.err != nil {
fmt.Fprintf(os.Stderr, " [error] %s/%s: %v\n", res.task.itemID, res.task.band, res.err)
failed++
} else {
fmt.Printf(" [saved] %s\n", filepath.Base(res.path))
}
}
if sc.SupportsRGB {
fmt.Println("\n=== Building RGB ===")
for _, item := range items {
if err := BuildRGB(destDir, item.ID, sat); err != nil {
fmt.Fprintf(os.Stderr, " [rgb skip] %s: %v\n", item.ID, err)
}
}
}
fmt.Println("\nDone.")
if failed > 0 {
return fmt.Errorf("%d/%d downloads failed", failed, total)
}
if skipped > 0 {
fmt.Printf("%d/%d already existed, skipped.\n", skipped, total)
}
return nil
}