aboutsummaryrefslogtreecommitdiff
path: root/src/storage/index.ts
blob: 8d7debde7a289051755cfd04747e895876739a30 (plain) (blame)
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
import { randomUUID } from 'crypto';
import { mkdir, writeFile, readFile } from 'fs/promises';
import { watch } from 'fs';
import { basename, join } from 'path';
import { parse as parseToml } from 'smol-toml';
import { isSafeRouteName, isRouteConfig, type RouteConfig, type StoredRequest } from '../types/index.js';
import { Either, type IEither } from '@emprespresso/pengueno';

type IncomingUpload = {
    fieldName: string;
    filename: string;
    contentType: string;
    size: number;
    data: Uint8Array;
};

function sanitizeFilename(filename: string): string {
    const base = basename(filename);
    const safe = base.replace(/[^a-zA-Z0-9._-]/g, '_');
    return safe.length > 0 ? safe.slice(0, 200) : 'upload.bin';
}

export class Storage {
    private routes: Map<string, RouteConfig> = new Map();
    private configPath: string;

    constructor(
        private readonly dataDir: string = './data',
        configPath: string = './routes.toml',
    ) {
        this.configPath = configPath;
    }

    async init(): Promise<IEither<Error, void>> {
        try {
            await mkdir(this.dataDir, { recursive: true });
            await this.loadRoutes();
            this.watchConfig();
            return Either.right(<void>undefined);
        } catch (err) {
            return Either.left(err instanceof Error ? err : new Error(String(err)));
        }
    }

    private async loadRoutes(): Promise<void> {
        try {
            const data = await readFile(this.configPath, 'utf-8');
            const parsed = parseToml(data);

            if (!parsed || typeof parsed !== 'object' || !('route' in parsed)) {
                console.error('Invalid routes.toml: missing [[route]] sections');
                process.exit(1);
            }

            const routes = parsed.route;
            if (!Array.isArray(routes)) {
                console.error('Invalid routes.toml: "route" must be an array of tables');
                process.exit(1);
            }

            const newRoutes = new Map<string, RouteConfig>();
            for (const route of routes) {
                if (!isRouteConfig(route)) {
                    console.error('Invalid route configuration:', route);
                    process.exit(1);
                }
                if (newRoutes.has(route.name)) {
                    console.error(`Duplicate route name: ${route.name}`);
                    process.exit(1);
                }
                newRoutes.set(route.name, route);

                // Ensure route directory exists
                const routeDir = join(this.dataDir, route.name);
                await mkdir(routeDir, { recursive: true });
            }

            this.routes = newRoutes;
            console.log(`Loaded ${this.routes.size} route(s) from ${this.configPath}`);
        } catch (err) {
            if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
                console.log(`No ${this.configPath} found, starting with empty routes`);
                return;
            }
            console.error(`Failed to load routes from ${this.configPath}:`, err);
            process.exit(1);
        }
    }

    private watchConfig(): void {
        const watcher = watch(this.configPath, async (eventType) => {
            if (eventType === 'change') {
                console.log(`${this.configPath} changed, reloading...`);
                await this.loadRoutes();
            }
        });

        watcher.on('error', (err) => {
            console.error(`Error watching ${this.configPath}:`, err);
        });
    }

    getRoute(name: string): RouteConfig | undefined {
        if (!isSafeRouteName(name)) return undefined;
        return this.routes.get(name);
    }

    listRoutes(): RouteConfig[] {
        return Array.from(this.routes.values());
    }

    async storeRequest(
        routeName: string,
        method: string,
        headers: Record<string, string>,
        body: unknown,
        uploads?: IncomingUpload[],
    ): Promise<IEither<Error, StoredRequest>> {
        if (!isSafeRouteName(routeName)) {
            return Either.left(new Error('Invalid route name'));
        }

        const timestamp = Date.now();
        const uuid = randomUUID();
        const baseName = `${timestamp}_${uuid}`;
        const routeDir = join(this.dataDir, routeName);

        try {
            await mkdir(routeDir, { recursive: true });

            const requestDir = join(routeDir, baseName);
            await mkdir(requestDir, { recursive: true });

            const files: StoredRequest['files'] = uploads?.length
                ? await (async () => {
                      const filesDir = join(requestDir, 'files');
                      await mkdir(filesDir, { recursive: true });

                      const storedFiles: NonNullable<StoredRequest['files']> = [];
                      for (let i = 0; i < uploads.length; i++) {
                          const upload = uploads[i];
                          const safeOriginal = sanitizeFilename(upload.filename);
                          const savedName = `${i}_${safeOriginal}`;
                          const diskPath = join(filesDir, savedName);
                          await writeFile(diskPath, Buffer.from(upload.data));

                          storedFiles.push({
                              fieldName: upload.fieldName,
                              originalFilename: upload.filename,
                              filename: savedName,
                              contentType: upload.contentType,
                              size: upload.size,
                              path: join('files', savedName),
                          });
                      }

                      return storedFiles;
                  })()
                : undefined;

            const stored: StoredRequest = {
                timestamp,
                uuid,
                routeName,
                method,
                headers,
                body,
                files,
            };

            await writeFile(join(requestDir, 'request.json'), JSON.stringify(stored, null, 2));
            return Either.right(stored);
        } catch (err) {
            return Either.left(err instanceof Error ? err : new Error(String(err)));
        }
    }
}