-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.clj
1148 lines (1066 loc) · 59 KB
/
core.clj
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns s4.core
(:require aleph.http
[cemerick.uri :as uri]
[clojure.core.async :as async]
[clojure.data.xml :as xml]
[clojure.data.xml.node :as node]
[clojure.string :as string]
[clojure.tools.logging :as log]
[clojure.walk :refer [keywordize-keys]]
[konserve.memory :as km]
[konserve.protocols :as kp]
[manifold.deferred :as d]
[s4.$$$$ :as $]
[s4.auth :as auth]
[superv.async :as sv]
[konserve.serializers :as ser])
(:import [java.time ZonedDateTime ZoneId Instant ZoneOffset]
[java.time.format DateTimeFormatter DateTimeParseException]
[java.nio ByteBuffer]
[java.security SecureRandom MessageDigest]
[java.util Base64 List]
[com.google.common.io ByteStreams]
[java.io ByteArrayInputStream]
[org.fressian.handlers ReadHandler WriteHandler]
[clojure.lang PersistentTreeMap]
[java.net InetSocketAddress]))
(def write-handlers
(atom {PersistentTreeMap
{"sorted-map"
(reify WriteHandler
(write [_ wtr m]
(.writeTag wtr "sorted-map" 1)
(.writeObject wtr (mapcat identity m))))}
ZonedDateTime
{"zoned-inst"
(reify WriteHandler
(write [_ wtr t]
(.writeTag wtr "zoned-inst" 2)
(.writeInt wtr (-> ^ZonedDateTime t ^Instant (.toInstant) (.toEpochMilli)))
(.writeString wtr (.getId (.getZone ^ZonedDateTime t)))))}}))
(def read-handlers
(atom {"sorted-map"
(reify ReadHandler
(read [_ rdr tag component-count]
(let [kvs ^List (.readObject rdr)]
(PersistentTreeMap/create (seq kvs)))))
"zoned-inst"
(reify ReadHandler
(read [_ rdr tag component-count]
(let [milli (.readInt rdr)
zone-id ^String (.readObject rdr)]
(ZonedDateTime/ofInstant (Instant/ofEpochMilli milli)
(ZoneId/of zone-id)))))}))
(defn- drop-leading-slashes
[path]
(.substring path (loop [i 0]
(if (and (< i (count path))
(= \/ (.charAt path i)))
(recur (inc i))
i))))
(defn- read-bucket-object
[request hostname]
(let [host-header (get-in request [:headers "host"])]
(if (and (string/ends-with? host-header hostname)
(not= host-header hostname))
[(.substring (get-in request [:headers "host"]) 0 (- (count host-header) (count hostname) 1))
(drop-leading-slashes (:uri request))]
(vec (.split (drop-leading-slashes (:uri request)) "/" 2)))))
(def xml-content-type {"content-type" "application/xml"})
(def s3-xmlns "http://s3.amazonaws.com/doc/2006-03-01/")
(defn bucket-put-ops
[bucket request {:keys [konserve]} request-id]
(sv/go-try sv/S
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(if (empty? params)
(if-let [existing-bucket (not-empty (sv/<? sv/S (kp/-get-in konserve [:bucket-meta bucket])))]
{:status 409
:headers xml-content-type
:body [:Error
[:Code "BucketAlreadyExists"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]}
(do
(sv/<? sv/S (kp/-assoc-in konserve [:bucket-meta bucket] {:created (ZonedDateTime/now auth/UTC)
:object-count 0}))
(sv/<? sv/S (kp/-assoc-in konserve [:version-meta bucket] (sorted-map)))
{:status 200
:headers {"location" (str \/ bucket)}}))
(if-let [existing-bucket (sv/<? sv/S (kp/-get-in konserve [:bucket-meta bucket]))]
(cond (some? (:versioning params))
(if-let [config (some-> (:body request) (xml/parse :namespace-aware false))]
(if (= "VersioningConfiguration" (name (:tag config)))
(if-let [new-state (#{"Enabled" "Suspended"} (some->> config
:content
(filter #(= :Status (:tag %)))
(first)
:content
(first)))]
(let [current-state (:versioning existing-bucket)]
(when (not= current-state new-state)
(sv/<? sv/S (kp/-assoc-in konserve [:bucket-meta bucket :versioning] new-state)))
{:status 200})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "IllegalVersioningConfigurationException"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "IllegalVersioningConfigurationException"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "MissingRequestBodyError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:tagging params))
(if-let [config (some-> (:body request) (xml/parse :namespace-aware false))]
(if (= :Tagging (:tag config))
(let [tags (->> (:content config)
(filter #(= :TagSet (:tag %)))
first
:content
(filter #(= :Tag (:tag %)))
(map :content)
(map (fn [tags] (filter #(#{:Key :Value} (:tag %)) tags)))
(map (fn [tags] [(->> tags (filter #(= :Key (:tag %))) first :content first)
(->> tags (filter #(= :Value (:tag %))) first :content first)])))]
(sv/<? sv/S (kp/-assoc-in konserve [:bucket-meta bucket :tags] tags))
{:status 204}))
{:status 400
:headers xml-content-type
:body [:Error
[:Code "MissingRequestBodyError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
; todo cors - too lazy to parse out the damn xml right now
:else
{:status 200
:headers xml-content-type
:body [:Error [:Code "NotImplemented"] [:Resource (str \/ bucket)] [:RequestId request-id]]})
{:status 404
:headers xml-content-type
:body [:Error [:Code "NoSuchBucket"] [:Resource (str \/ bucket)] [:RequestId request-id]]})))))
(defn list-objects-v2
[bucket bucket-meta request {:keys [konserve]} request-id]
(sv/go-try sv/S
(let [{:keys [delimiter encoding-type max-keys prefix continuation-token fetch-owner start-after]
:or {max-keys "1000"}}
(keywordize-keys (uri/query->map (:query-string request)))
max-keys (Integer/parseInt max-keys)
encode-key (fn [k] (if (= "url" encoding-type) (uri/uri-encode k) k))
objects (remove nil? (map (fn [[k v]] (when-not (:deleted? (first v))
(assoc (first v) :key k)))
(sv/<? sv/S (kp/-get-in konserve [:version-meta bucket]))))
objects (drop-while (fn [{:keys [key]}]
(neg? (compare key (or continuation-token start-after))))
objects)
objects (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (:key %) prefix) objects)
objects)
common-prefixes (when (some? delimiter)
(->> objects
(map :key)
(dedupe)
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))))
truncated? (> (count objects) max-keys)
objects (take max-keys objects)
objects (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (:key %) (count prefix)) delimiter)) objects)
(filter #(not (string/includes? (:key %) delimiter)) objects))
objects)
response [:ListBucketResult {:xmlns s3-xmlns}
[:Name bucket]
[:Prefix prefix]
[:KeyCount (count objects)]
[:IsTruncated truncated?]
[:Delimiter delimiter]
[:MaxKeys max-keys]]
response (if truncated?
(conj response [:NextContinuationToken (:key (last objects))])
response)
response (reduce conj response
(map (fn [object]
(let [obj [:Contents
[:Key (encode-key (:key object))]
[:LastModified (.format (:created object) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:ETag (:etag object)]
[:Size (:content-length object)]
[:StorageClass "STANDARD"]]]
(if (= "true" fetch-owner)
(conj obj [:Owner [:ID "S4"] [:DisplayName "You Know, for Data"]])
obj)))
objects))
response (reduce conj response
(map (fn [prefix]
[:CommonPrefixes [:Prefix prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body response})))
(defn list-versions
[bucket bucket-meta request {:keys [konserve]} request-id]
(sv/go-try sv/S
(let [{:keys [delimiter encoding-type key-marker max-keys prefix version-id-marker]
:or {max-keys "1000" key-marker "" version-id-marker ""}}
(keywordize-keys (uri/query->map (:query-string request)))
encode-key (fn [k] (if (= "uri" encoding-type)
(uri/uri-encode k)
k))
max-keys (Integer/parseInt max-keys)
versions (sv/<? sv/S (kp/-get-in konserve [:version-meta bucket]))
versions (mapcat (fn [[key versions]]
(let [[current & others] versions]
(cons (assoc current :key key :current? true)
(map #(assoc % :key key) others))))
versions)
versions (drop-while (fn [{:keys [key]}]
(neg? (compare key key-marker)))
versions)
versions (if (empty? version-id-marker)
versions
(let [seen? (atom false)]
(drop-while (fn [{:keys [version-id]}]
(if @seen?
false
(do
(when (= (or version-id "null") version-id-marker)
(reset! seen? true))
true)))
versions)))
versions (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (:key %) prefix) versions)
versions)
common-prefixes (when (some? delimiter)
(->> versions
(map :key)
(dedupe)
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))))
versions (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (:key %) (count prefix)) delimiter)) versions)
(filter #(not (string/includes? (:key %) delimiter)) versions))
versions)
truncated? (> (count versions) max-keys)
versions (take max-keys versions)
last-version (when truncated? (last versions))
{:keys [delete-markers versions]} (group-by (fn [{:keys [deleted?]}]
(if deleted? :delete-markers :versions))
versions)
result [:ListVersionsResult {:xmlns s3-xmlns}
[:Name bucket]
[:Prefix prefix]
[:KeyMarker key-marker]
[:VersionIdMarker version-id-marker]
[:MaxKeys max-keys]
[:IsTruncated truncated?]]
result (if truncated?
(conj result [:NextKeyMarker (:key last-version)]
[:NextVersionIdMarker (or (:version-id last-version) "null")])
result)
result (reduce conj result (map (fn [marker]
[:DeleteMarker
[:Key (encode-key (:key marker))]
[:VersionId (or (:version-id marker) "null")]
[:IsLatest (boolean (:current? marker))]
[:LastModified (.format (:created marker) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:Owner [:ID "S4"]]])
delete-markers))
result (reduce conj result (map (fn [version]
[:Version
[:Key (encode-key (:key version))]
[:VersionId (or (:version-id version) "null")]
[:IsLatest (boolean (:current? version))]
[:LastModified (.format (:created version) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:ETag (:etag version)]
[:Size (:content-length version)]
[:Owner [:ID "S4"]]
[:StorageClass "STANDARD"]])
versions))
result (reduce conj result (map (fn [prefix]
[:CommonPrefixes [:Prefix prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body result})))
(defn list-objects
[bucket bucket-meta request system request-id]
(sv/go-try sv/S
(let [request (update request :query-string
(fn [query-string]
(let [query (uri/query->map query-string)]
(-> query
(assoc "continuation-token" (get query "marker"))
(dissoc "marker")
(assoc "fetch-owner" "true")
(uri/map->query)))))
response (:body (sv/<? sv/S (list-objects-v2 bucket bucket-meta request system request-id)))
response (vec (map (fn [element]
(cond (keyword? element) element
(map? element) element
:else (condp = (first element)
:ContinuationToken (into [:Marker] (rest element))
:NextContinuationToken (into [:NextMarker] (rest element))
element)))
response))]
{:status 200
:headers xml-content-type
:body response})))
(defn bucket-get-ops
[bucket request {:keys [konserve cost-tracker] :as system} request-id]
(sv/go-try sv/S
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(log/debug :task ::s3-handler :phase :get-bucket-request :bucket bucket :params params)
(if-let [existing-bucket (not-empty (sv/<? sv/S (kp/-get-in konserve [:bucket-meta bucket])))]
(cond
(= "2" (:list-type params))
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-objects-v2 bucket existing-bucket request system request-id)))
(some? (:versions params))
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-versions bucket existing-bucket request system request-id)))
(some? (:accelerate params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:AccelerateConfiguration {:xmlns s3-xmlns}
[:Status {} "Suspended"]]})
(some? (:cors params))
(let [cors (:cors existing-bucket)]
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:CORSConfiguration {}
(map (fn [{:keys [header origin method max-age expose-header]}]
[:CORSRule {}
(concat
(map (fn [header] [:AllowedHeader {} header]) header)
(map (fn [origin] [:AllowedOrigin {} origin]) origin)
(map (fn [method] [:AllowedMethod {} method]) method)
(map (fn [max-age] [:MaxAgeSeconds {} max-age]) max-age)
(map (fn [header] [:ExposeHeader {} header]) expose-header))])
cors)]})
(some? (:encryption params)) ; todo maybe support this?
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "ServerSideEncryptionConfigurationNotFoundError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:acl params)) ; todo maybe support this?
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:AccessControlPolicy {}
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:AccessControlList {}
[:Grant
[:Grantee {"xmlns:xsi" "http://www.w3.org/2001/XMLSchema-instance"
"xsi:type" "CanonicalUser"}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Permission {} "FULL_CONTROL"]]]]})
(some? (:inventory params))
(if (some? (:id params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:InventoryConfiguration {}]})
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListInventoryConfigurationsResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]}))
(some? (:lifecycle params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchLifecycleConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:location params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:LocationConstraint {}]})
(some? (:publicAccessBlock params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchPublicAccessBlockConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:logging params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:BucketLoggingStatus {:xmlns "http://doc.s3.amazonaws.com/2006-03-01"}]})
(some? (:metrics params))
(if (some? (:id params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:MetricsConfiguration {:xmlns s3-xmlns}]})
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListMetricsConfigurationsResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]}))
(some? (:notification params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:NotificationConfiguration {:xmlns s3-xmlns}]})
(or (some? (:policyStatus params)) (some? (:policy params)))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucketPolicy"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:versions params))
(do
($/-track-put-request! cost-tracker)
{:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:replication params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "ReplicationConfigurationNotFoundError"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:requestPayment params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:RequestPaymentConfiguration {:xmlns s3-xmlns}
[:Payer {} "BucketOwner"]]})
(some? (:tagging params))
(do
($/-track-get-request! cost-tracker)
(if-let [tags (not-empty (get existing-bucket :tags))]
{:status 200
:headers xml-content-type
:body [:Tagging {}
[:TagSet {}
(map (fn [[key value]]
[:Tag {}
[:Key {} (str key)]
[:Value {} (str value)]])
tags)]]}
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchTagSet"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]}))
(some? (:versioning params))
(do
($/-track-get-request! cost-tracker)
(let [config (get existing-bucket :versioning)]
(cond (nil? config)
{:status 200
:headers xml-content-type
:body [:VersioningConfiguration {:xmlns s3-xmlns}]}
:else
{:status 200
:headers xml-content-type
:body [:VersioningConfiguration {:xmlns s3-xmlns}
[:Status {} config]]})))
(some? (:website params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchWebsiteConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:analytics params))
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListBucketAnalyticsConfigurationResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]})
(some? (:uploads params))
(do
($/-track-put-request! cost-tracker)
(let [{:keys [delimiter encoding-type max-uploads key-marker prefix upload-id-marker]
:or {max-uploads "1000" key-marker "" upload-id-marker ""}}
params
max-uploads (Integer/parseInt max-uploads)
uploads (sv/<? sv/S (kp/-get-in konserve [:uploads bucket]))
uploads (doall (drop-while (fn [[[key upload-id]]]
(and (not (pos? (compare key key-marker)))
(not (pos? (compare upload-id upload-id-marker)))))
uploads))
uploads (doall (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (first (key %)) prefix) uploads)
uploads))
common-prefixes (doall (when (some? delimiter)
(->> uploads
(map (comp first key))
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))
(set))))
uploads (doall (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (first (key %)) (count prefix)) delimiter)) uploads)
(filter #(not (string/includes? (first (key %)) delimiter)) uploads))
uploads))
truncated? (> (count uploads) max-uploads)
uploads (take max-uploads uploads)
result [:ListMultipartUploadsResult {:xmlns s3-xmlns}
[:Bucket {} bucket]
[:KeyMarker {} key-marker]
[:UploadIdMarker {} upload-id-marker]
[:NextKeyMarker {} (if truncated? (first (key (last uploads))) "")]
[:NextUploadIdMarker {} (if truncated? (second (key (last uploads))) "")]
[:MaxUploads {} (str max-uploads)]
[:IsTruncated {} truncated?]]
result (if encoding-type
(conj result [:EncodingType {} encoding-type])
result)
result (reduce conj result
(map (fn [[[key upload-id] {:keys [created]}]]
[:Upload {}
[:Key {} key]
[:UploadId {} upload-id]
[:Initiator {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:StorageClass {} "STANDARD"]
[:Initiated {} (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME created)]])
uploads))
result (reduce conj result
(map (fn [prefix]
[:CommonPrefixes {}
[:Prefix {} prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body result}))
:else
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-objects bucket existing-bucket request system request-id))))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucket"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})))))
(def random (SecureRandom.))
(defn put-object
[bucket object request {:keys [konserve cost-tracker]} request-id]
(sv/go-try sv/S
(if-let [existing-bucket (not-empty (sv/<? sv/S (kp/-get-in konserve [:bucket-meta bucket])))]
(let [blob-id (let [b (byte-array 16)
buf (ByteBuffer/wrap b)]
(.putLong buf (System/currentTimeMillis))
(.putLong buf (.nextLong random))
(.encodeToString (Base64/getUrlEncoder) b))
version-id (when (= "Enabled" (:versioning existing-bucket))
blob-id)
content (some-> (:body request) (ByteStreams/toByteArray))
etag (let [md (MessageDigest/getInstance "MD5")]
(some->> content (.update md))
(->> (.digest md)
(map #(format "%02x" %))
(string/join)))
content-type (get-in request [:headers "content-type"] "binary/octet-stream")]
(when (some? content)
($/-track-data-in! cost-tracker (count content))
(sv/<? sv/S (kp/-assoc-in konserve [:blobs bucket blob-id] content)))
(sv/<? sv/S (kp/-update-in konserve [:version-meta bucket object]
(fn [versions]
(cons
{:blob-id blob-id
:version-id version-id
:created (ZonedDateTime/now ^ZoneId auth/UTC)
:etag (str \" etag \")
:content-type content-type
:content-length (count content)}
(if (= "Enabled" (:versioning existing-bucket))
versions
(vec (filter #(= version-id (:version-id %)) versions)))))))
{:status 200
:headers (as-> {"ETag" etag} h
(if (some? version-id)
(assoc h "x-amz-version-id" version-id)
h))})
{:status 404
:headers xml-content-type
:body [:Error
[:Code "NoSuchBucket"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})))
(defn parse-date-header
[d]
(try
(ZonedDateTime/parse d DateTimeFormatter/RFC_1123_DATE_TIME)
(catch DateTimeParseException _
(try
(ZonedDateTime/parse d auth/RFC-1036-FORMATTER)
(catch DateTimeParseException _
(ZonedDateTime/parse d auth/ASCTIME-FORMATTER))))))
(defn parse-range
[r]
(let [[begin end] (rest (re-matches #"bytes=([0-9]+)-([0-9]*)" r))]
(when (some? begin)
[(Long/parseLong begin)
(some-> (not-empty end) (Long/parseLong))])))
(defn get-object
[bucket object request {:keys [konserve cost-tracker]} request-id with-body?]
(sv/go-try sv/S
($/-track-get-request! cost-tracker)
(if-let [existing-bucket (not-empty (sv/<? sv/S (kp/-get-in konserve [:bucket-meta bucket])))]
(if-let [versions (sv/<? sv/S (kp/-get-in konserve [:version-meta bucket object]))]
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(cond (some? (:acl params))
(as-> {:status 200
:headers xml-content-type} r
(if with-body?
(assoc r :body [:AccessControlPolicy
[:Owner
[:ID "S4"]
[:DisplayName "You Know, for Data"]]
[:AccessControlList
[:Grant
[:Grantee {"xmlns:xsi" "http://www.w3.org/2001/XMLSchema-instance"
"xsi:type" "CanonicalUser"}
[:ID "S4"]
[:DisplayName "You Know, for Data"]]
[:Permission "FULL_CONTROL"]]]])
r))
(or (some? (:legal-hold params))
(some? (:retention params))
(some? (:torrent params))
(some? (:tagging params)))
(as-> {:status 501
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NotImplemented"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r))
:else
(if-let [version (let [v (if-let [version-id (:versionId params)]
(first (filter #(= version-id (:version-id %)) versions))
(first versions))]
(log/debug :task ::get-object :phase :got-version :version v)
v)]
(if (:deleted? version)
(as-> {:status 404
:headers (as-> xml-content-type h
(if (some? (:versioning existing-bucket))
(assoc h "x-amz-version-id" (or (:version-id version) "null")
"x-amz-delete-marker" "true")
h))} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchKey"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r))
(let [if-modified-since (some-> (get-in request [:headers "if-modified-since"]) parse-date-header)
if-unmodified-since (some-> (get-in request [:headers "if-unmodified-since"]) parse-date-header)
if-match (get-in request [:headers "if-match"])
if-none-match (get-in request [:headers "if-none-match"])
content-type (or (:response-content-type params)
(:content-type version))
headers (as-> {"content-type" content-type
"last-modified" (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME (:created version))
"accept-ranges" "bytes"} h
(if-let [etag (:etag version)]
(assoc h "etag" etag)
h)
(if-let [v (:response-content-language params)]
(assoc h "content-language" v)
h)
(if-let [v (:response-expires params)]
(assoc h "expires" v)
h)
(if-let [v (:response-cache-control params)]
(assoc h "cache-control" v)
h)
(if-let [v (:response-content-disposition params)]
(assoc h "content-disposition" v)
h)
(if-let [v (:response-content-encoding params)]
(assoc h "content-encoding" v)
h)
(if (= "Enabled" (:versioning existing-bucket))
(assoc h "x-amz-version-id" (or (:version-id version) "null"))
h))
range (some-> (get-in request [:headers "range"]) parse-range)]
(log/debug :task ::get-object :phase :checking-object :version version
:if-modified-since if-modified-since
:if-unmodified-since if-unmodified-since
:if-match if-match
:if-none-match if-none-match)
(cond (and (some? if-modified-since)
(pos? (compare if-modified-since (:created version))))
{:status 304
:headers headers}
(and (some? if-unmodified-since)
(pos? (compare (:created version) if-unmodified-since)))
{:status 412
:headers headers}
(and (some? if-match)
(not= if-match (:etag version)))
{:status 412
:headers headers}
(and (some? if-none-match)
(= if-none-match (:etag version)))
{:status 304
:headers headers}
(and (some? range)
(or (and (some? (second range)) (> (first range) (second range)))
(> (first range) (:content-length version))
(and (some? (second range)) (> (second range) (:content-length version)))))
{:status 416
:headers headers}
(and (some? range)
(or (pos? (first range))
(and (some? (second range))
(not= (second range) (:content-length version)))))
(let [range [(first range) (or (second range) (:content-length version))]
response {:status 206
:headers (assoc headers
"content-range" (str "bytes " (first range) \- (second range) \/ (:content-length version)))}]
(if with-body?
(let [content (or (sv/<? sv/S (kp/-get-in konserve [:blobs bucket (:blob-id version)])) (byte-array 0))]
($/-track-data-out! cost-tracker (- (second range) (first range)))
(assoc response :body (ByteArrayInputStream. content (first range) (- (second range) (first range)))))
response))
:else
(let [response {:status 200
:headers headers}]
(if with-body?
(let [content (or (sv/<? sv/S (kp/-get-in konserve [:blobs bucket (:blob-id version)])) (byte-array 0))]
($/-track-data-out! cost-tracker (:content-length version))
(assoc response :body (ByteArrayInputStream. content)))
response)))))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchVersion"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchKey"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchBucket"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))))
(defn s3-handler
[{:keys [konserve hostname request-id-prefix request-counter cost-tracker] :as system}]
(fn [request respond error]
(async/go
(let [request-id (str request-id-prefix (format "%016x" (swap! request-counter inc)))]
(try
(log/debug :task ::s3-handler :phase :begin :request (pr-str request))
(let [respond (fn respond-wrapper
[response]
(log/debug :task ::s3-handler :phase :end :response (pr-str response))
(let [body (:body response)
body (if (and (= "application/xml" (get-in response [:headers "content-type"]))
(sequential? body))
(xml/emit-str (xml/sexp-as-element body) :encoding "UTF-8")
body)]
(respond (assoc
(assoc-in response [:headers "x-amz-request-id"] request-id)
:body body))))
[bucket object] (read-bucket-object request hostname)]
(log/debug :task ::s3-handler :bucket bucket :object object)
(case (:request-method request)
:head (cond (and (not-empty bucket)
(empty? object))
(do
($/-track-get-request! cost-tracker)
(if (not-empty (sv/<? sv/S (kp/-get-in konserve [:bucket-meta bucket])))
(respond {:status 200})
(respond {:status 404})))
(and (not-empty bucket)
(not-empty object))
(do
($/-track-get-request! cost-tracker)
(respond (sv/<? sv/S (get-object bucket object request system request-id false))))
:else
(do
($/-track-get-request! cost-tracker)
(respond {:status 200})))
:get (cond (empty? bucket)
(let [buckets (sv/<? sv/S (kp/-get-in konserve [:bucket-meta]))
buckets-response [:ListAllMyBucketsResult {:xmlns "http://s3.amazonaws.com/doc/2006-03-01"}
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Buckets {}
(map (fn [[bucket-name {:keys [created]}]]
[:Bucket {}
[:Name {} bucket-name]
[:CreationDate {} (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME created)]])
buckets)]]]
($/-track-put-request! cost-tracker)
(respond {:status 200
:headers xml-content-type
:body buckets-response}))
(empty? object)
(respond (sv/<? sv/S (bucket-get-ops bucket request system request-id)))
:else
(respond (sv/<? sv/S (get-object bucket object request system request-id true))))
:put (do
($/-track-put-request! cost-tracker)
(cond (and (not-empty bucket) (empty? object))
(respond (sv/<? sv/S (bucket-put-ops bucket request system request-id)))
(and (not-empty bucket) (not-empty object))
(respond (sv/<? sv/S (put-object bucket object request system request-id)))
:else (respond {:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))
:post (let [params (keywordize-keys (uri/query->map (:query-string request)))]
($/-track-put-request! cost-tracker)
(respond {:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]}))
:delete (do
($/-track-get-request! cost-tracker)
(cond (and (not-empty bucket) (empty? object))
(if-let [bucket-meta (not-empty (sv/<? sv/S (kp/-get-in konserve [:bucket-meta bucket])))]
(if (pos? (:object-count bucket-meta 0))
(respond {:status 409
:headers xml-content-type
:body [:Error {}
[:Code {} "BucketNotEmpty"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(do
(sv/<? sv/S (kp/-update-in konserve [:blobs] #(dissoc % bucket)))
(sv/<? sv/S (kp/-update-in konserve [:bucket-meta] #(dissoc % bucket)))
(sv/<? sv/S (kp/-update-in konserve [:version-meta] #(dissoc % bucket)))
(respond {:status 204})))
(respond {:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucket"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]}))
(and (not-empty bucket) (not-empty object))
(if-let [bucket-meta (not-empty (sv/<? sv/S (kp/-get-in konserve [:bucket-meta bucket])))]
(let [{:keys [versionId tagging]}
(keywordize-keys (uri/query->map (:query-string request)))]
(if (some? tagging)
(respond {:status 501
:headers xml-content-type
:body [:Error [:Code "NotImplemented"] [:Resource (str \/ bucket \/ object)]]})
(let [[old new] (sv/<?
sv/S
(kp/-update-in konserve [:version-meta bucket object]
(fn [versions]
(cond (some? versionId)
(remove #(= versionId (:version-id %)) versions)
(= "Enabled" (:versioning bucket-meta))
(let [version-id (let [b (byte-array 16)
buf (ByteBuffer/wrap b)]
(.putLong buf (System/currentTimeMillis))
(.putLong buf (.nextLong random))
(.encodeToString (Base64/getUrlEncoder) b))]
(cons {:version-id version-id
:deleted? true