-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathmanager.js
More file actions
219 lines (195 loc) · 7.43 KB
/
Copy pathmanager.js
File metadata and controls
219 lines (195 loc) · 7.43 KB
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
const fs = require('node:fs');
const path = require('node:path');
const { JobType, getPool, destroyPool } = require('../pool');
const { FileIndex } = require('./file-index');
const { buildTree } = require('./tree-builder');
const { defaultClassify, uidForSeed } = require('../../utils/mount');
const { getWsClient } = require('../../ipc/network/ws-event-handlers');
// cold start only — collection-watcher handles live changes and writes through to the cache
let _envSecretsStore = null;
const getEnvSecretsStore = () => {
if (!_envSecretsStore) {
const EnvironmentSecretsStore = require('../../store/env-secrets');
_envSecretsStore = new EnvironmentSecretsStore();
}
return _envSecretsStore;
};
const envHasSecrets = (env) => Array.isArray(env?.variables) && env.variables.some((v) => v.secret);
const hydrateEnvironments = (collectionPath, environments) => {
if (!Array.isArray(environments)) return;
const { decryptStringSafe } = require('../../utils/encryption');
for (const env of environments) {
if (!Array.isArray(env.variables)) continue;
env.variables.forEach((variable, i) => {
variable.uid = uidForSeed(`${env.uid}#var#${i}#${variable.name || ''}`);
});
if (!envHasSecrets(env)) continue;
try {
const envSecrets = getEnvSecretsStore().getEnvSecrets(collectionPath, env);
for (const secret of envSecrets || []) {
const variable = env.variables.find((v) => v.name === secret.name && v.secret);
if (variable && secret.value) {
const decrypted = decryptStringSafe(secret.value);
variable.value = decrypted.value;
}
}
} catch (err) {
console.error('[mount] env secret hydration failed', err);
}
}
};
const sendTree = async (collectionUid, collectionPath, tree, emit) => {
if (tree.brunoConfig) {
try {
const { transformBrunoConfigAfterRead } = require('../../utils/transformBrunoConfig');
const { setBrunoConfig } = require('../../store/bruno-config');
const transformed = await transformBrunoConfigAfterRead(tree.brunoConfig, collectionPath);
tree.brunoConfig = transformed;
setBrunoConfig(collectionUid, transformed);
emit.config(transformed);
} catch (err) {
console.error(`[mount:${collectionUid}] brunoConfig transform failed:`, err);
}
}
hydrateEnvironments(collectionPath, tree.environments);
emit.tree(tree);
};
const ensureTransientDirectory = () => {
const base = path.join(require('electron').app.getPath('userData'), 'tmp', 'transient');
if (!fs.existsSync(base)) fs.mkdirSync(base, { recursive: true });
return fs.mkdtempSync(path.join(base, 'bruno-'));
};
class MountManager {
#index = null;
#mounts = new Map();
async mount({ win, collectionPath, collectionUid, brunoConfig, emit }) {
collectionPath = path.resolve(collectionPath);
if (this.#mounts.has(collectionUid)) {
// renderer reload — pull fresh state from cache and re-emit
const existing = this.#mounts.get(collectionUid);
existing.win = win;
existing.emit = emit;
existing.brunoConfig = brunoConfig || existing.brunoConfig;
existing.state = this.#getIndex().entries(existing.collectionPath);
await this.#emitTree(collectionUid, existing);
return existing.tempDirectoryPath;
}
const tempDirectoryPath = ensureTransientDirectory();
fs.writeFileSync(path.join(tempDirectoryPath, 'metadata.json'), JSON.stringify({ collectionPath }));
const entry = {
state: new Map(),
collectionPath,
tempDirectoryPath,
brunoConfig,
win,
emit
};
this.#mounts.set(collectionUid, entry);
entry.emit.loading(true);
try {
entry.state = this.#getIndex().entries(collectionPath);
await this.#reconcile(entry);
await this.#emitTree(collectionUid, entry);
// skip the startup walk (already done) and stage live edits into the cache
const collectionWatcher = require('../../app/collection-watcher');
collectionWatcher.addWatcher(entry.win, collectionPath, collectionUid, brunoConfig, false, false, {
ignoreInitial: true,
fileIndex: this.#getIndex()
});
collectionWatcher.addTempDirectoryWatcher(entry.win, tempDirectoryPath, collectionUid, collectionPath);
} catch (err) {
this.#mounts.delete(collectionUid);
throw err;
} finally {
entry.emit.loading(false);
}
return tempDirectoryPath;
}
async unmount(collectionUid) {
try {
getWsClient()?.closeForCollection(collectionUid);
} catch (_) {}
const entry = this.#mounts.get(collectionUid);
if (!entry) return;
this.#mounts.delete(collectionUid);
const collectionWatcher = require('../../app/collection-watcher');
try {
collectionWatcher.removeWatcher(entry.collectionPath, entry.win, collectionUid);
} catch (_) {}
}
async shutdown() {
await Promise.all(
Array.from(this.#mounts.keys()).map((uid) => this.unmount(uid).catch(() => {}))
);
await destroyPool().catch(() => {});
this.#index = null;
}
clearCollectionIndex(collectionPath) {
this.#getIndex().clearCollection(path.resolve(collectionPath));
}
async #reconcile(entry) {
const denylist = entry.brunoConfig?.ignore || [];
const { added, updated, removed } = await this.#getIndex().status(entry.collectionPath, { denylist });
const toParse = [];
for (const e of [...added, ...updated]) {
const cls = defaultClassify(e.relativePath);
if (!cls) continue;
toParse.push({ relativePath: e.relativePath, format: cls.format, type: cls.type });
}
const parsed = new Map();
if (toParse.length > 0) {
const pool = getPool();
await Promise.allSettled(
toParse.map(async (e) => {
try {
const result = await pool.run(JobType.ParseFile, {
collectionPath: entry.collectionPath,
relativePath: e.relativePath,
format: e.format,
type: e.type
});
parsed.set(e.relativePath, result);
} catch (err) {
parsed.set(e.relativePath, {
relativePath: e.relativePath,
error: { message: err.message, stack: err.stack }
});
}
})
);
}
this.#getIndex().transaction(() => {
for (const e of toParse) {
const result = parsed.get(e.relativePath);
if (!result) continue;
if (result.error) {
entry.state.set(e.relativePath, { data: result.data, error: result.error, raw: result.raw });
continue;
}
entry.state.set(e.relativePath, { data: result.data, raw: result.raw });
this.#getIndex().stage(entry.collectionPath, {
op: 'add',
relativePath: e.relativePath,
mtime: result.mtime,
hash: result.hash,
data: result.data,
raw: result.raw
});
}
for (const e of removed) {
entry.state.delete(e.relativePath);
this.#getIndex().stage(entry.collectionPath, { op: 'remove', relativePath: e.relativePath });
}
});
}
async #emitTree(collectionUid, entry) {
const { getRequestUid } = require('../../cache/requestUids');
const tree = buildTree(entry.collectionPath, entry.state, { uidFor: getRequestUid });
await sendTree(collectionUid, entry.collectionPath, tree, entry.emit);
}
#getIndex() {
if (!this.#index) this.#index = new FileIndex();
return this.#index;
}
}
module.exports = { MountManager };