Debian Codegraph @

extra/haxelib_src/src/haxelib/server/FileStorage.hx

raw
1 /*
2 * Copyright (C)2005-2016 Haxe Foundation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
21 */
22 package haxelib.server;
23
24 import sys.FileSystem;
25 import sys.io.*;
26 import haxe.io.Path;
27 import haxelib.server.Paths;
28 import neko.Web;
29 import aws.*;
30 import aws.s3.*;
31 import aws.s3.model.*;
32 import aws.transfer.*;
33 using Lambda;
34
35 /**
36 `FileStorage` is an abstraction to a file system.
37 It maps relative paths to absolute paths, effectively hides the actual location of the storage.
38 */
39 class FileStorage {
40 /**
41 An static instance of `FileStorage` that everyone use.
42 One should not create their own instance of `FileStorage` except when testing.
43
44 When both the enviroment variables, HAXELIB_S3BUCKET and AWS_DEFAULT_REGION, are set,
45 `instance` will be a `S3FileStorage`. Otherwise, it will be a `LocalFileStorage`.
46 */
47 static public var instance(get, null):FileStorage;
48 static function get_instance() return instance != null ? instance : instance = {
49 var vars = [
50 Sys.getEnv("HAXELIB_S3BUCKET"),
51 Sys.getEnv("AWS_DEFAULT_REGION")
52 ];
53 switch (vars) {
54 case [bucket, region] if (vars.foreach(function(v) return v != null && v != "")):
55 Web.logMessage('using S3FileStorage with bucket $bucket in ${region}');
56 new S3FileStorage(Paths.CWD, bucket, region);
57 case _:
58 Web.logMessage('using LocalFileStorage');
59 new LocalFileStorage(Paths.CWD);
60 }
61 }
62
63 /**
64 Request reading `file` in the function `f`.
65 `file` should be the relative path to the required file, e.g. `files/3.0/library.zip`.
66 If the file does not exist, an error will be thrown, and `f` will not be called.
67 If `file` exist, its abolute path will be given to `f` as input.
68 It only guarantees `file` exists and the abolute path to it is valid within the call of `f`.
69 */
70 public function readFile<T>(file:RelPath, f:AbsPath->T):T
71 return throw "should be implemented by subclass";
72
73 /**
74 Request writing `file` in the function `f`.
75 `file` should be a relative path to the required file, e.g. `files/3.0/library.zip`.
76 Any of the parent directories of `file` that doesn't exist will be created.
77 The mapped abolute path of `file` will be given to `f` as input.
78 The abolute path to `file` may and may not contain previously written file.
79 */
80 public function writeFile<T>(file:RelPath, f:AbsPath->T):T
81 return throw "should be implemented by subclass";
82
83 /**
84 Copy existing local `srcFile` to the storage as `dstFile`.
85 Existing `dstFile` will be overwritten.
86 If `move` is true, `srcFile` will be deleted, unless `dstFile` happens to located
87 at the same path of `srcFile`.
88 */
89 public function importFile<T>(srcFile:AbsPath, dstFile:RelPath, move:Bool):Void
90 throw "should be implemented by subclass";
91
92 /**
93 Delete `file` in the storage.
94 It will be a no-op if `file` does not exist.
95 */
96 public function deleteFile(file:RelPath):Void
97 throw "should be implemented by subclass";
98
99 function assertAbsolute(path:String):Void {
100 #if (haxe_ver >= 3.2) // Path.isAbsolute is added in haxe 3.2
101 if (!Path.isAbsolute(path))
102 throw '$path is not absolute.';
103 #end
104 }
105
106 function assertRelative(path:String):Void {
107 #if (haxe_ver >= 3.2) // Path.isAbsolute is added in haxe 3.2
108 if (Path.isAbsolute(path))
109 throw '$path is not relative.';
110 #end
111 }
112 }
113
114 class LocalFileStorage extends FileStorage {
115 /**
116 The local directory of the file storage.
117 */
118 public var path(default, null):AbsPath;
119
120 /**
121 Create a `FileStorage` located at a local directory specified by an absolute `path`.
122 */
123 public function new(path:AbsPath):Void {
124 assertAbsolute(path);
125 this.path = path;
126 }
127
128 override public function readFile<T>(file:RelPath, f:AbsPath->T):T {
129 assertRelative(file);
130 var file:AbsPath = Path.join([path, file]);
131 if (!FileSystem.exists(file))
132 throw '$file does not exist.';
133 return f(file);
134 }
135
136 override public function writeFile<T>(file:RelPath, f:AbsPath->T):T {
137 assertRelative(file);
138 var file:AbsPath = Path.join([path, file]);
139 FileSystem.createDirectory(Path.directory(file));
140 return f(file);
141 }
142
143 override public function importFile<T>(srcFile:AbsPath, dstFile:RelPath, move:Bool):Void {
144 var localFile:AbsPath = Path.join([path, dstFile]);
145 if (
146 FileSystem.exists(localFile) &&
147 FileSystem.fullPath(localFile) == FileSystem.fullPath(srcFile)
148 ) {
149 // srcFile already located at dstFile
150 return;
151 }
152 FileSystem.createDirectory(Path.directory(localFile));
153 File.copy(srcFile, localFile);
154 if (move)
155 FileSystem.deleteFile(srcFile);
156 }
157
158 override public function deleteFile(file:RelPath):Void {
159 var localFile:AbsPath = Path.join([path, file]);
160 if (FileSystem.exists(localFile))
161 FileSystem.deleteFile(localFile);
162 }
163 }
164
165 class S3FileStorage extends FileStorage {
166 /**
167 The local directory for caching.
168 */
169 public var localPath(default, null):AbsPath;
170
171 /**
172 The S3 bucket name.
173 */
174 public var bucketName(default, null):String;
175
176 /**
177 The region where the S3 bucket is located.
178 e.g. 'us-east-1'
179 */
180 public var bucketRegion(default, null):aws.Region;
181
182 /**
183 The public endpoint of the S3 bucket.
184 e.g. 'http://${bucket}.s3-website-${region}.amazonaws.com/'
185 */
186 public var bucketEndpoint(get, never):String;
187 function get_bucketEndpoint()
188 return 'http://${bucketName}.s3-website-${bucketRegion}.amazonaws.com/';
189
190 var s3Client(default, null):S3Client;
191 var transferClient(default, null):TransferClient;
192
193 static var awsInited = false;
194
195 public function new(localPath:AbsPath, bucketName:String, bucketRegion:String):Void {
196 assertAbsolute(localPath);
197 this.localPath = localPath;
198 this.bucketName = bucketName;
199 this.bucketRegion = bucketRegion;
200
201 if (!awsInited) {
202 Aws.initAPI();
203 awsInited = true;
204 }
205
206 this.transferClient = new TransferClient(this.s3Client = new S3Client(bucketRegion));
207 }
208
209 override public function readFile<T>(file:RelPath, f:AbsPath->T):T {
210 assertRelative(file);
211 var s3Path = Path.join(['s3://${bucketName}', file]);
212 var localFile:AbsPath = Path.join([localPath, file]);
213 FileSystem.createDirectory(Path.directory(localFile));
214 if (!FileSystem.exists(localFile)) {
215 var request = transferClient.downloadFile(localFile, bucketName, file);
216 while (!request.isDone()) {
217 Sys.sleep(0.01);
218 }
219 if (!request.completedSuccessfully()) {
220 throw 'failed to download ${s3Path} to ${localFile}\n${request.getFailure()}';
221 }
222 if (!FileSystem.exists(localFile)) {
223 throw 'failed to download ${s3Path} to ${localFile}';
224 }
225 }
226 return f(localFile);
227 }
228
229 function uploadToS3(localFile:AbsPath, file:RelPath, contentType = "application/octet-stream") {
230 var s3Path = Path.join(['s3://${bucketName}', file]);
231 var request = transferClient.uploadFile(localFile, bucketName, file, contentType);
232 while (!request.isDone()) {
233 Sys.sleep(0.01);
234 }
235 switch (request.getFailure()) {
236 case null:
237 //pass
238 case failure:
239 throw 'failed to upload ${localFile} to ${s3Path}\n${failure}';
240 }
241 }
242
243 override public function writeFile<T>(file:RelPath, f:AbsPath->T):T {
244 assertRelative(file);
245 var localFile:AbsPath = Path.join([localPath, file]);
246 if (!FileSystem.exists(localFile))
247 throw '$localFile does not exist';
248 FileSystem.createDirectory(Path.directory(localFile));
249 var r = f(localFile);
250 uploadToS3(localFile, file);
251 return r;
252 }
253
254 override public function importFile<T>(srcFile:AbsPath, dstFile:RelPath, move:Bool):Void {
255 var localFile:AbsPath = Path.join([localPath, dstFile]);
256 if (
257 FileSystem.exists(localFile) &&
258 FileSystem.fullPath(localFile) == FileSystem.fullPath(srcFile)
259 ) {
260 // srcFile already located at dstFile
261 uploadToS3(localFile, dstFile);
262 return;
263 }
264 FileSystem.createDirectory(Path.directory(localFile));
265 File.copy(srcFile, localFile);
266 uploadToS3(localFile, dstFile);
267 if (move)
268 FileSystem.deleteFile(srcFile);
269 }
270
271 override public function deleteFile(file:RelPath):Void {
272 var localFile:AbsPath = Path.join([localPath, file]);
273 if (FileSystem.exists(localFile))
274 FileSystem.deleteFile(localFile);
275
276 var del = new DeleteObjectRequest();
277 del.setBucket(bucketName);
278 del.setKey(file);
279 try {
280 s3Client.deleteObject(del);
281 } catch (e:Dynamic) {
282 // maybe the object does not exist
283 }
284 }
285 }