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}7778798081pub fn (mut s S3) list(prefix string) ![]string {82 mut keys := []string{}83 mut token := ''84 for {85 86 87 mut query := 'list-type=2&prefix=${prefix}'88 if token != '' {89 query += '&continuation-token=${token}'90 }91 response := s.send('GET', '', query, map[string]string{}, []u8{})!92 if response.status_code != 200 {93 return error('s3 list failed: ${response.status_code} ${short_body(response)}')94 }95 keys << elements(response.body, 'Key')96 if !response.body.contains('<IsTruncated>true</IsTruncated>') {97 break98 }99 token = first_element(response.body, 'NextContinuationToken') or {100 return error('s3 listing ${prefix} was truncated with no continuation token')101 }102 }103 return keys104}105106107pub fn (mut s S3) put_if_absent(key string, body []u8) !bool {108 response := s.send('PUT', key, '', {109 'If-None-Match': '*'110 }, body)!111 if response.status_code == 412 {112 return false113 }114 if !success(response.status_code) {115 return error('s3 PUT ${key} failed: ${response.status_code} ${short_body(response)}')116 }117 return true118}119120121122pub fn (mut s S3) put_if_match(key string, body []u8, tag string) !bool {123 mut headers := map[string]string{}124 if tag == '' {125 126 headers['If-None-Match'] = '*'127 } else {128 headers['If-Match'] = tag129 }130 response := s.send('PUT', key, '', headers, body)!131 if response.status_code == 412 {132 return false133 }134 if !success(response.status_code) {135 return error('s3 PUT ${key} failed: ${response.status_code} ${short_body(response)}')136 }137 return true138}139140141pub fn (mut s S3) delete(key string) ! {142 response := s.send('DELETE', key, '', map[string]string{}, []u8{})!143 if !success(response.status_code) && response.status_code != 404 {144 return error('s3 DELETE ${key} failed: ${response.status_code} ${short_body(response)}')145 }146}147148149150151fn (mut s S3) send(method string, key string, query string, headers map[string]string, body []u8) !http.Response {152 url := s.url_for(key, query)153 mut last := ''154 for attempt in 1 .. retry_attempts + 1 {155 signed := s.signer.sign(method, url, query, headers, body, time.now().local_to_utc())156 mut outbound := http.new_header()157 for name, value in signed {158 outbound.add_custom(header_case(name), value) or {}159 }160 161 162 163 response := http.fetch(164 url: url165 validate: true166 verify: tls_roots(url)!167 method: method_from(method)168 header: outbound169 data: body.bytestr()170 enable_http2: false171 ) or {172 last = err.msg()173 time.sleep(backoff(attempt))174 continue175 }176 if response.status_code >= 500 || response.status_code == 429 {177 last = '${response.status_code}'178 time.sleep(backoff(attempt))179 continue180 }181 return response182 }183 return error('s3 ${method} ${key} failed after ${retry_attempts} attempts: ${last}')184}185186187188fn (s &S3) url_for(key string, query string) string {189 mut url := '${s.root}/${encode(s.bucket, false)}'190 if key != '' {191 url += '/${encode(key, true)}'192 }193 if query != '' {194 url += '?${canonical_query(query)}'195 }196 return url197}198199fn backoff(attempt int) time.Duration {200 return time.Duration(attempt) * 200 * time.millisecond201}202203fn method_from(method string) http.Method {204 return match method {205 'GET' { .get }206 'PUT' { .put }207 'POST' { .post }208 'DELETE' { .delete }209 'HEAD' { .head }210 else { .get }211 }212}213214fn success(status int) bool {215 return status >= 200 && status < 300216}217218fn header_of(response http.Response, name string) string {219 return response.header.get_custom(name, http.HeaderQueryConfig{}) or { '' }220}221222fn header_case(name string) string {223 return match name {224 'authorization' { 'Authorization' }225 'host' { 'Host' }226 'x-amz-date' { 'X-Amz-Date' }227 'x-amz-content-sha256' { 'X-Amz-Content-Sha256' }228 'if-none-match' { 'If-None-Match' }229 'if-match' { 'If-Match' }230 else { name }231 }232}233234fn short_body(response http.Response) string {235 body := response.body236 if body.len <= 200 {237 return body238 }239 return body[..200]240}241242243244245pub fn elements(xml string, name string) []string {246 open := '<${name}>'247 close := '</${name}>'248 mut out := []string{}249 mut rest := xml250 for {251 start := rest.index(open) or { break }252 after := rest[start + open.len..]253 end := after.index(close) or { break }254 out << unescape(after[..end])255 rest = after[end + close.len..]256 }257 return out258}259260fn first_element(xml string, name string) ?string {261 values := elements(xml, name)262 if values.len == 0 {263 return none264 }265 return values[0]266}267268fn unescape(text string) string {269 return text.replace('&', '&').replace('<', '<').replace('>', '>').replace('"',270 '"').replace(''', "'")271}