12345678module remote910import net.http11import time1213pub const s3_service = 's3'14pub const retry_attempts = 31516pub struct S3 {17pub:18 endpoint string19 bucket string20 region string21 access_key string22 secret_key string23mut:24 signer Signer25 root string 26}2728pub fn new_s3(endpoint string, bucket string, region string, access_key string, secret_key string) !S3 {29 if endpoint == '' || bucket == '' || region == '' {30 return error('the S3 remote needs an endpoint, a bucket and a region')31 }32 if access_key == '' || secret_key == '' {33 return error('the S3 remote needs an access key and a secret key')34 }35 if !endpoint.starts_with('http://') && !endpoint.starts_with('https://') {36 return error('the S3 endpoint should start with https:// — got "${endpoint}"')37 }38 root := endpoint.trim_right('/')39 return S3{40 endpoint: root41 bucket: bucket42 region: region43 access_key: access_key44 secret_key: secret_key45 signer: Signer{46 access_key: access_key47 secret_key: secret_key48 region: region49 service: s3_service50 sign_payload: true51 }52 root: root53 }54}555657pub fn (mut s S3) get(key string) !Object {58 response := s.send('GET', key, '', map[string]string{}, []u8{})!59 match response.status_code {60 404 {61 return Object{}62 }63 200 {64 return Object{65 found: true66 body: response.body.bytes()67 68 69 tag: header_of(response, 'ETag').trim_space()70 }71 }72 else {73 return error('s3 GET ${key} failed: ${response.status_code} ${short_body(response)}')74 }75 }76}77787980pub fn (mut s S3) list_dirs(prefix string) ![]string {81 mut names := []string{}82 mut token := ''83 for {84 mut query := 'list-type=2&delimiter=/&prefix=${prefix}'85 if token != '' {86 query += '&continuation-token=${token}'87 }88 response := s.send('GET', '', query, map[string]string{}, []u8{})!89 if response.status_code != 200 {90 return error('s3 list failed: ${response.status_code} ${short_body(response)}')91 }92 for raw in elements(response.body, 'Prefix') {93 rest := raw[prefix.len..].trim_right('/')94 if rest != '' && !rest.contains('/') {95 names << rest96 }97 }98 if !response.body.contains('<IsTruncated>true</IsTruncated>') {99 break100 }101 token = first_element(response.body, 'NextContinuationToken') or {102 return error('s3 listing ${prefix} was truncated with no continuation token')103 }104 }105 names.sort()106 return names107}108109110111112pub fn (mut s S3) list(prefix string) ![]string {113 mut keys := []string{}114 mut token := ''115 for {116 117 118 mut query := 'list-type=2&prefix=${prefix}'119 if token != '' {120 query += '&continuation-token=${token}'121 }122 response := s.send('GET', '', query, map[string]string{}, []u8{})!123 if response.status_code != 200 {124 return error('s3 list failed: ${response.status_code} ${short_body(response)}')125 }126 keys << elements(response.body, 'Key')127 if !response.body.contains('<IsTruncated>true</IsTruncated>') {128 break129 }130 token = first_element(response.body, 'NextContinuationToken') or {131 return error('s3 listing ${prefix} was truncated with no continuation token')132 }133 }134 return keys135}136137138pub fn (mut s S3) put_if_absent(key string, body []u8) !bool {139 response := s.send('PUT', key, '', {140 'If-None-Match': '*'141 }, body)!142 if response.status_code == 412 {143 return false144 }145 if !success(response.status_code) {146 return error('s3 PUT ${key} failed: ${response.status_code} ${short_body(response)}')147 }148 return true149}150151152153pub fn (mut s S3) put_if_match(key string, body []u8, tag string) !bool {154 mut headers := map[string]string{}155 if tag == '' {156 157 headers['If-None-Match'] = '*'158 } else {159 headers['If-Match'] = tag160 }161 response := s.send('PUT', key, '', headers, body)!162 if response.status_code == 412 {163 return false164 }165 if !success(response.status_code) {166 return error('s3 PUT ${key} failed: ${response.status_code} ${short_body(response)}')167 }168 return true169}170171172pub fn (mut s S3) delete(key string) ! {173 response := s.send('DELETE', key, '', map[string]string{}, []u8{})!174 if !success(response.status_code) && response.status_code != 404 {175 return error('s3 DELETE ${key} failed: ${response.status_code} ${short_body(response)}')176 }177}178179180181182fn (mut s S3) send(method string, key string, query string, headers map[string]string, body []u8) !http.Response {183 url := s.url_for(key, query)184 mut last := ''185 for attempt in 1 .. retry_attempts + 1 {186 signed := s.signer.sign(method, url, query, headers, body, time.now().local_to_utc())187 mut outbound := http.new_header()188 for name, value in signed {189 outbound.add_custom(header_case(name), value) or {}190 }191 192 193 194 response := http.fetch(195 url: url196 validate: true197 verify: tls_roots(url)!198 method: method_from(method)199 header: outbound200 data: body.bytestr()201 enable_http2: false202 ) or {203 last = err.msg()204 time.sleep(backoff(attempt))205 continue206 }207 if response.status_code >= 500 || response.status_code == 429 {208 last = '${response.status_code}'209 time.sleep(backoff(attempt))210 continue211 }212 return response213 }214 return error('s3 ${method} ${key} failed after ${retry_attempts} attempts: ${last}')215}216217218219fn (s &S3) url_for(key string, query string) string {220 mut url := '${s.root}/${encode(s.bucket, false)}'221 if key != '' {222 url += '/${encode(key, true)}'223 }224 if query != '' {225 url += '?${canonical_query(query)}'226 }227 return url228}229230fn backoff(attempt int) time.Duration {231 return time.Duration(attempt) * 200 * time.millisecond232}233234fn method_from(method string) http.Method {235 return match method {236 'GET' { .get }237 'PUT' { .put }238 'POST' { .post }239 'DELETE' { .delete }240 'HEAD' { .head }241 else { .get }242 }243}244245fn success(status int) bool {246 return status >= 200 && status < 300247}248249fn header_of(response http.Response, name string) string {250 return response.header.get_custom(name, http.HeaderQueryConfig{}) or { '' }251}252253fn header_case(name string) string {254 return match name {255 'authorization' { 'Authorization' }256 'host' { 'Host' }257 'x-amz-date' { 'X-Amz-Date' }258 'x-amz-content-sha256' { 'X-Amz-Content-Sha256' }259 'if-none-match' { 'If-None-Match' }260 'if-match' { 'If-Match' }261 else { name }262 }263}264265fn short_body(response http.Response) string {266 body := response.body267 if body.len <= 200 {268 return body269 }270 return body[..200]271}272273274275276pub fn elements(xml string, name string) []string {277 open := '<${name}>'278 close := '</${name}>'279 mut out := []string{}280 mut rest := xml281 for {282 start := rest.index(open) or { break }283 after := rest[start + open.len..]284 end := after.index(close) or { break }285 out << unescape(after[..end])286 rest = after[end + close.len..]287 }288 return out289}290291fn first_element(xml string, name string) ?string {292 values := elements(xml, name)293 if values.len == 0 {294 return none295 }296 return values[0]297}298299fn unescape(text string) string {300 return text.replace('&', '&').replace('<', '<').replace('>', '>').replace('"',301 '"').replace(''', "'")302}