-
Notifications
You must be signed in to change notification settings - Fork 2
/
memory-cache.ts
212 lines (195 loc) · 5.93 KB
/
memory-cache.ts
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
/**
* This example shows how to implement a storage putting everything into memory (and calculating SHA1 etags)
*/
import { join } from 'node:path';
import { createHash } from 'node:crypto';
import type { Stats } from 'node:fs';
import { fstat, close, createReadStream, readdir, constants, open as openFn, opendir as opendirFn } from 'node:fs';
import { promisify } from 'node:util';
import { Readable } from 'node:stream';
import { fastify } from 'fastify';
import type { GenericFileData, GenericFileSystemStorageOptions, StorageInfo } from '../src/send-stream';
import { GenericFileSystemStorage } from '../src/send-stream';
const open = promisify(openFn);
const opendir = promisify(opendirFn);
const app = fastify({ exposeHeadRoutes: true });
interface CachedFile {
etag: string;
stats: Stats;
chunks: Buffer[];
size: number;
}
type CachedFileDescriptor = number | CachedFile;
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
class FullCacheStorage extends GenericFileSystemStorage<CachedFileDescriptor> {
cache = new Map<string, CachedFile>();
cached: Promise<void>;
constructor(
root: string,
opts: Optional<GenericFileSystemStorageOptions<CachedFileDescriptor>, 'fsModule'> = {},
) {
super(
root,
{
fsModule: {
constants,
open: (
path: string,
_flags: number,
// eslint-disable-next-line sonarjs/no-reference-error
callback: (err: NodeJS.ErrnoException | null, fd: CachedFileDescriptor) => void,
) => {
const cached = this.cache.get(path);
if (cached) {
callback(null, cached);
return;
}
this.addFileInCache(path)
.then(cache => {
callback(null, cache);
})
.catch((err: unknown) => {
callback(err instanceof Error ? err : new Error(String(err)), Number.NaN);
});
},
fstat: (
fd: CachedFileDescriptor,
callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void,
) => {
if (typeof fd === 'number') {
fstat(fd, callback);
return;
}
callback(null, fd.stats);
},
close: (fd: CachedFileDescriptor, callback: (err: NodeJS.ErrnoException | null) => void) => {
if (typeof fd === 'number') {
close(fd, callback);
return;
}
callback(null);
},
createReadStream: (
path: string,
{ fd, start, end, autoClose }: {
fd?: CachedFileDescriptor;
start?: number;
end?: number;
autoClose: boolean;
},
) => {
if (!fd) {
return start !== undefined && end !== undefined
? createReadStream(path, { start, end, autoClose })
: createReadStream(path, { autoClose });
}
if (typeof fd === 'number') {
return start !== undefined && end !== undefined
? createReadStream(path, { fd, start, end, autoClose })
: createReadStream(path, { fd, autoClose });
}
const rangeStart = start ?? 0;
const rangeEnd = end ?? fd.size - 1;
const readable = new Readable();
let currentStart = 0;
for (const chunk of fd.chunks) {
const { byteLength } = chunk;
const currentEnd = currentStart + byteLength - 1;
if (rangeEnd >= currentStart && rangeStart <= currentEnd) {
const chunkStart = Math.max(rangeStart - currentStart, 0);
const chunkEnd = Math.min(
byteLength - Math.min(currentEnd - rangeEnd, byteLength),
byteLength,
);
if (chunkStart === 0 && chunkEnd === byteLength) {
readable.push(chunk);
} else {
const newChunk = chunk.subarray(
chunkStart,
chunkEnd,
);
readable.push(newChunk);
}
}
currentStart = currentEnd + 1;
}
readable.push(null);
return readable;
},
readdir,
},
...opts,
},
);
this.cached = this.addAllFilesInCache(root);
}
async addAllFilesInCache(dir: string) {
const files = await opendir(dir);
for await (const file of files) {
const filePath = join(dir, file.name);
await (file.isDirectory() ? this.addAllFilesInCache(filePath) : this.addFileInCache(filePath));
}
}
async addFileInCache(filePath: string) {
const fd = await open(filePath, this.fsConstants.O_RDONLY);
const stats = await this.fsFstat(fd);
return new Promise<CachedFile>((resolve, reject) => {
const stream = this.fsCreateReadStream(
filePath,
{ start: 0, end: stats.size - 1, fd, autoClose: true },
);
const chunks: Buffer[] = [];
// eslint-disable-next-line sonarjs/hashing
const hash = createHash('sha1');
hash.setEncoding('hex');
stream.on('data', chunk => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
chunks.push(<Buffer> chunk);
hash.write(chunk);
});
stream.on('error', reject);
stream.on('end', () => {
hash.end();
const etagStr = <unknown> hash.read();
if (typeof etagStr !== 'string') {
reject(new Error('hash calculation failed'));
return;
}
const etag = `"${ etagStr }"`;
const cache = { etag, stats, chunks, size: chunks.reduce((p, c) => p + c.byteLength, 0) };
this.cache.set(
filePath,
cache,
);
resolve(cache);
});
});
}
override createEtag(storageInfo: StorageInfo<GenericFileData<CachedFileDescriptor>>) {
const { attachedData: { fd } } = storageInfo;
if (typeof fd === 'number') {
return super.createEtag(storageInfo);
}
return fd.etag;
}
}
const storage = new FullCacheStorage(join(__dirname, 'assets'));
app.get('*', async (request, reply) => {
const result = await storage.prepareResponse(request.url, request.raw);
if (result.statusCode === 404) {
reply.callNotFound();
return;
}
await result.send(reply.raw);
});
storage.cached
.then(async () => {
console.info('all files are cached');
return app.listen({ port: 3000 })
.then(() => {
console.info('listening on http://localhost:3000');
});
})
.catch((err: unknown) => {
console.error(err);
});