a6499917690d94bf590168c52f960aefa8748a42
[nodejs-repoproxy.git] / lib / cache.js
1 var fs = require("fs");
2 var http = require("http");
3 var url = require("url");
4 var path = require("path");
5
6 function maintainCache() {
7         // TODO i should check that im already running here and exit if i am
8         console.log("Cache maintainence routine starting...");
9         console.log("Cache maintainence routine ended...");
10 }
11
12 exports.startTimer = function() {
13         // our once-a-day cache maintainer
14         var cacheTimer = global.repoproxy.scancache*3600*1000;
15         //var cacheTimer = global.repoproxy.scancache*100;
16         setInterval(maintainCache, cacheTimer);
17 }
18
19 function upstreamRequest(unify) {
20         // first do a head request
21         console.log("upsteram as ", unify.requestFor);
22         
23         var endData = false;
24         var xpath = "";
25         var filefd = null;
26         if(unify.topPath !=null) if(unify.topPath != "") if(typeof global.repoproxy.repo[unify.topPath] != "undefined") {
27                 var uplink = global.repoproxy.repo[unify.topPath].url;
28                 xpath = uplink + unify.subPath;
29         }
30         
31         //unify.b.write("would send to '" + xpath + "'");
32         //unify.b.end();
33         
34         // not doing this properly yet...
35         if(typeof global.repoproxy.downloads[unify.fullFilePath] != undefined && global.repoproxy.downloads[unify.fullFilePath] == 1) {
36                 console.log("request for file thats being downloaded already, doing inline request");
37                 inlineService(unify);
38                 return;
39         }
40         
41         console.log("sending off to '%s'", xpath);
42         
43         var headReq = url.parse(xpath);
44         headReq["method"] = "HEAD";
45         
46         getup = http.request(headReq, function(res) {
47                 //res.setEncoding("utf8");
48                 
49                 if(!endData) {
50                         console.log("status code is ", typeof res.statusCode);
51                         switch(res.statusCode) {
52                         // TODO: this 301 directory redirect thing needs to work better
53                         case 301:
54                         case 302:
55                                 
56                                 var loc = res.headers.location.substr(res.headers.location.length-4);
57                                 var against_t = xpath + "/";
58                                 var against = against_t.substr(against_t.length-4);
59                                 
60                                 if(loc == against) {
61                                         console.log("got a redirect, upstream for loc => loc/ assuming its a directory");
62                                         makeCacheDir(unify);
63                                         unify.b.writeHead(302, { "Location": unify.originalReq + "/" });
64                                 } else {
65                                         console.log("checked '%s' against '%s', was false, sending 404", loc, against);
66                                         unify.b.writeHead(404, {"Content-Type": "text/plain"});
67                                         unify.b.write("404 Not Found\n");
68                                 }
69                                 unify.b.end();
70                                 endData = true;
71                                 break;
72                                 
73                         case 404:
74                                 unify.b.writeHead(404, {"Content-Type": "text/plain"});
75                                 unify.b.write("404 Not Found\n");
76                                 unify.b.end();
77                                 endData = true;
78                                 break;
79                         case 200:
80                                 makeCacheDir(unify);
81                                 if(unify.isDirectoryRequest) {
82                                         serviceDirectory(unify);                                        
83                                         endData = true;
84                                 } else {
85                                         // this is where it gets ugly
86                                         var filesize = res.headers["content-length"];
87                                         console.log("do ugly write: ", unify);
88                                         //unify.b.write(data);
89                                         var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
90                                         var metafile = fs.createWriteStream(metafilename);
91                                         metafile.write(filesize);
92                                         metafile.end();
93                                         getAndService(unify, xpath, filesize);
94                                         
95                                 }
96                                 break;
97                         default:
98                                 console.log(".... data");
99                                 //unify.b.write(data);
100                         }
101                 }               
102                 //console.log("res is now ", res);
103         });
104         
105         getup.end();
106         
107         //console.log("getup: ", getup);
108 }
109
110 exports.upstreamRequest = upstreamRequest;
111
112 function getAndService(unify, xpath, filesize) {
113         
114         console.log("calling in here with filesize, ", filesize)
115         unify.b.writeHead(200, {'Content-Length' : filesize});
116
117         
118         global.repoproxy.downloads[unify.fullFilePath] = 1;
119         
120
121         http.get(xpath, function(res) {
122
123             var file = fs.createWriteStream(unify.fullFilePath);
124         
125             //console.log("res: ", res);
126         
127             //res.setEncoding("utf8");
128         
129             res.on("data", function(data) {
130                     //console.log("chunk");
131                     file.write(data);
132                     unify.b.write(data);
133             });
134         
135             res.on("end", function() {
136                     console.log("end...");
137                     unify.b.end();
138                     file.end();
139                     global.repoproxy.downloads[unify.fullFilePath] = 0;
140             });
141             
142             res.on("error", function(err) {
143                 console.log("res threw error... ", err);
144             });
145         });
146 }
147
148 // this is nasty nasty thing that can go horribly wrong in some ways, but currently works...
149 function inlineService(unify) {
150         // this method is called when we need to service a file thats being downloaded by something else
151         var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
152         var fsizef = fs.createReadStream(metafilename);
153         var fsize = "";
154         fsizef.on("data", function(data) {
155                 fsize += data;
156         });
157         
158         fsizef.on("end", function() {
159                 var sentSoFar = 0;
160                 unify.b.writeHead(200, {"Content-Length" : fsize });
161                 
162                 // now we go into the file reading loop.
163                 console.log("start of inline services");
164                 // we loop every 0.5s and do our thing
165                 
166                 function sendPieces() {
167                         // this is going to be so fun i want to play real life frogger in real life traffic...
168                         fs.stat(unify.fullFilePath, function(err, stats) {
169                                 if(err == null) {
170                                         if(stats["size"] > sentSoFar) {
171                                                 // open the file, send the data
172                                                 var rs = fs.createReadStream(unify.fullFilePath, {start: sentSoFar, end: stats["size"]});
173                                                 
174                                                 rs.on("data", function(thisdata) {
175                                                         //console.log("inline chunk: ", thisdata.length);
176                                                         unify.b.write(thisdata);
177                                                 });
178                                                 
179                                                 rs.on("end", function() {
180                                                         sentSoFar = stats["size"];
181                                                         // every second, we start again
182                                                         if(sentSoFar != fsize) {
183                                                                 setTimeout(sendPieces, 1000);
184                                                         } else {
185                                                                 // we're done!
186                                                                 unify.b.end();
187                                                         }
188                                                 });
189                                         }
190                                 } else {
191                                         console.log("inline service - we're in a very bad place");
192                                 }
193                         });
194                         
195                 }
196                 
197                 setTimeout(sendPieces, 100);
198         });
199 }
200
201 // the service file routine .... PLEASE KILL ME!
202 function serviceFile(unify) {
203         
204         // for now, ignore range.
205         // however we need to check if a metadata file exists describing the filesize, check if its all correct
206         // and if not, erase the file (and metafile) and forward the request back to upstream request
207
208         
209         checkFile(unify, function() {
210                 
211                 // file should already exist, so we just poop it out
212                 var inp = fs.createReadStream(unify.fullFilePath);
213                 //inp.setEncoding("utf8");
214                 inp.on("data", function(data) {
215                         unify.b.write(data);
216                 });
217                 
218                 inp.on("end", function(closed) {
219                         unify.b.end();
220                 });
221         });
222 }
223
224 exports.serviceFile = serviceFile;
225
226
227 function checkFile(unify, callback) {
228         // in here we do the metadata checks
229         var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
230         
231         fs.exists(metafilename, function(existence) {
232                 if(existence) {
233                         var fsizef = fs.createReadStream(metafilename);
234                         var fsize = "";
235                         fsizef.on("data", function(data) {
236                                 fsize += data;
237                         });
238                         
239                         fsizef.on("end", function() {
240                                 fs.stat(unify.fullFilePath, function(err, stats) {
241                                         var rfsize = stats["size"];
242                                         if(rfsize != fsize.trim()) {
243                                                 // remove the file and start again
244                                                 console.log("reported filesizes dont match, '%s', '%s', removing file and starting again", rfsize, stats["size"]);
245                                                 try {
246                                                         fs.unlink(metafilename, function(){
247                                                                 fs.unlink(unify.fullFilePath, function(){
248                                                                         upstreamRequest(unify);                                                 
249                                                                 })
250                                                         });
251                                                 } catch(e) {
252                                                         upstreamRequest(unify);
253                                                 }
254                                         } else {
255                                                 // we're good
256                                                 unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
257                                                 callback();
258                                         }
259                                 });
260                         });
261                 } else {
262                         console.log("file, '%s' exists but has no filesize meta data, assuming it was put here manually and servicing", unify.fullFilePath);
263                         unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
264                         callback();
265                 }
266         });
267 }
268
269 function makeCacheDir(path) {
270         console.log("attempting to create... '%s' as '%s'", path.fullPathDirName, path.subPathDirName);
271         
272         var startAt = path.topFullPath;
273         var nextbits = path.subPathDirName.split("/");
274         for(var i=0; i < nextbits.length; i++) {
275                 startAt += "/" + nextbits[i];
276                 console.log("attempt mkdir on '%s'", startAt);
277                 try {
278                         fs.mkdirSync(startAt);
279                 } catch(e) {
280                         //console.log("e in mkdir, ", e);
281                 }
282         }
283         //process.exit(0);
284 }
285
286 function serviceDirectory(unify) {
287         var nfiles = 0;
288         var res = unify.b;
289         
290         res.write("<html><h1>Directory listing for " + unify.originalReq + "</h1><hr><pre>");
291         if(unify.originalReq != "/") res.write("<a href=\"..\">Parent</a>\n\n");
292         fs.readdir(unify.fullFilePath, function(err, files) {
293                 console.log("doing directory listing on: ", unify.fullFilePath);
294                 if(err == null) {
295                         
296                         // TODO: make this work asynchronously...
297                         for(var i=0; i<files.length; i++) {
298                                 // avoiding statSync is too hard for now, will fix later TODO: fix this sync bit
299                                 var stats = fs.statSync(unify.fullFilePath+"/"+files[i]);
300                                 
301                                 if(files[i].match(/^\..*/) == null) {
302                                         if(stats.isDirectory()) {
303                                                 
304                                                 res.write("Directory: <a href=\""+files[i]+"/\">"+files[i]+"/</a>\n");
305                                                 nfiles++;
306                                         } else if(stats.isFile()) {
307                                                 var padlength = 80 - (files[i].length) - stats.size.toString().length;
308                                                 var padding = "";
309                                                 if(padlength > 0) {
310                                                         padding = new Array(padlength).join(" ");
311                                                 }
312                                                 res.write("File:      <a href=\""+files[i]+"\">"+files[i]+"</a>"+padding+stats.size+" bytes\n");
313                                                 nfiles++;
314                                         }
315                                 } else {
316                                         console.log("ignoring file, ", files[i]);
317                                 }
318                         }
319                         
320                         if(nfiles == 0) res.write("Empty directory....\n");
321                         
322                         res.write("<hr></pre>");
323                         res.end();
324                 } else {
325                         res.write("we have entered bizaro world...\n");
326                         res.write("</pre>");
327                         res.end();
328                 }
329         });
330 }
331
332 exports.serviceDirectory = serviceDirectory;