dsh-data-window 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +111 -0
- package/CHANGELOG.md +267 -0
- package/LICENSE +21 -0
- package/README.md +151 -2
- package/client.js +8271 -0
- package/cordis.patch.yml +4 -0
- package/docs/BRIDGE.md +106 -0
- package/docs/DESIGN.md +417 -0
- package/docs/DETAIL.md +242 -0
- package/docs/screenshots/ddl.png +0 -0
- package/docs/screenshots/workbench.png +0 -0
- package/icon.svg +30 -0
- package/index.js +180 -0
- package/locale/en.json +304 -0
- package/locale/zh.json +304 -0
- package/package.json +68 -4
- package/src/client/00-css.js +1110 -0
- package/src/client/05-icons.js +156 -0
- package/src/client/05-theme.js +107 -0
- package/src/client/06-shortcuts.js +89 -0
- package/src/client/07-bridge.js +202 -0
- package/src/client/10-core.js +1320 -0
- package/src/client/20-tree.js +293 -0
- package/src/client/25-sql.js +631 -0
- package/src/client/30-editor.js +742 -0
- package/src/client/40-results.js +556 -0
- package/src/client/45-export.js +219 -0
- package/src/client/50-panel.js +768 -0
- package/src/client/60-settings.js +180 -0
- package/src/client/63-schema.js +186 -0
- package/src/client/64-manual.js +350 -0
- package/src/client/65-ai.js +320 -0
- package/src/client/66-optimize.js +217 -0
- package/src/client/90-apply.js +183 -0
- package/src/host/ai.js +721 -0
- package/src/host/cache.js +157 -0
- package/src/host/catalog.js +161 -0
- package/src/host/consoles.js +116 -0
- package/src/host/discovery.js +603 -0
- package/src/host/manual.js +276 -0
- package/src/host/mysql.js +650 -0
- package/src/host/remembered.js +225 -0
- package/src/host/rpc.js +487 -0
- package/src/host/shared.js +180 -0
- package/src/host/yaml.js +335 -0
package/src/host/rpc.js
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The RPC surface the browser talks to.
|
|
3
|
+
*
|
|
4
|
+
* One route, one action per request. The Client never learns a password: it names
|
|
5
|
+
* an opaque target id (`d:…` for a database, `i:…` for an instance) that discovery
|
|
6
|
+
* registered in the Host, and only this module holds the credential map.
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, statSync } from 'node:fs'
|
|
9
|
+
import { isAbsolute, join } from 'node:path'
|
|
10
|
+
import { AiDiscovery } from './ai.js'
|
|
11
|
+
import { ConnectionCatalog } from './catalog.js'
|
|
12
|
+
import { DiscoveryCache, fingerprint } from './cache.js'
|
|
13
|
+
import { ConsoleStore } from './consoles.js'
|
|
14
|
+
import { discoverProject } from './discovery.js'
|
|
15
|
+
import { ManualStore, manualEnvironments, normalizeManualEntry } from './manual.js'
|
|
16
|
+
import { stableId } from './discovery.js'
|
|
17
|
+
import { RememberedStore } from './remembered.js'
|
|
18
|
+
import { buildSharedTree } from './shared.js'
|
|
19
|
+
import { DataGateway, ReadOnlyViolation } from './mysql.js'
|
|
20
|
+
|
|
21
|
+
/** Payload ceiling for one request. */
|
|
22
|
+
export const MAX_BODY_BYTES = 4 * 1024 * 1024
|
|
23
|
+
|
|
24
|
+
/** Resolved plugin configuration with the defaults this build ships. */
|
|
25
|
+
export function resolveConfig(config = {}) {
|
|
26
|
+
const number = (value, fallback, minimum, maximum) => {
|
|
27
|
+
const parsed = Number(value)
|
|
28
|
+
if (!Number.isFinite(parsed)) return fallback
|
|
29
|
+
return Math.min(maximum, Math.max(minimum, parsed))
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
nacosHome: typeof config.nacosHome === 'string' ? config.nacosHome : '',
|
|
33
|
+
groups: Array.isArray(config.groups) ? config.groups.filter((group) => typeof group === 'string') : [],
|
|
34
|
+
envOrder: Array.isArray(config.envOrder) ? config.envOrder.filter((env) => typeof env === 'string') : [],
|
|
35
|
+
connectTimeoutMs: number(config.connectTimeoutMs, 8000, 2000, 60000),
|
|
36
|
+
statementTimeoutMs: number(config.statementTimeoutMs, 60000, 0, 600000),
|
|
37
|
+
connectionLimit: number(config.connectionLimit, 4, 1, 16),
|
|
38
|
+
defaultLimit: number(config.defaultLimit, 200, 1, 5000),
|
|
39
|
+
cache: config.cache === false ? false : true,
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createGateway(config) {
|
|
44
|
+
return new DataGateway({ ...config })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** One Host-side controller shared by every request the browser makes. */
|
|
48
|
+
export class DataController {
|
|
49
|
+
constructor(options = {}) {
|
|
50
|
+
this.config = resolveConfig(options.config ?? {})
|
|
51
|
+
this.gateway = options.gateway ?? createGateway(this.config)
|
|
52
|
+
this.cache = options.cache ?? new DiscoveryCache(options.cacheDirectory ?? '', options.pluginVersion ?? '')
|
|
53
|
+
this.consoles = options.consoles ?? new ConsoleStore(options.cacheDirectory === undefined || options.cacheDirectory === '' ? '' : join(options.cacheDirectory, 'workspaces'))
|
|
54
|
+
// Manual connections and picked databases are shared by every workspace: the
|
|
55
|
+
// resource tree is one tree, so its user-owned parts cannot be per workspace.
|
|
56
|
+
this.manual = options.manual ?? new ManualStore(options.cacheDirectory === undefined || options.cacheDirectory === '' ? '' : join(options.cacheDirectory, 'manual'), { shared: true })
|
|
57
|
+
this.remembered = options.remembered ?? new RememberedStore(options.cacheDirectory === undefined || options.cacheDirectory === '' ? '' : join(options.cacheDirectory, 'remembered'), { shared: true })
|
|
58
|
+
this.catalog = options.catalog ?? new ConnectionCatalog(options.cacheDirectory ?? '')
|
|
59
|
+
// `llm` is a getter: the Host may provide the LLM service after this plugin
|
|
60
|
+
// activates, and the fallback must not pin a service that is still arriving.
|
|
61
|
+
this.ai = options.ai ?? new AiDiscovery({
|
|
62
|
+
llm: options.llm,
|
|
63
|
+
defaultModel: options.defaultModel,
|
|
64
|
+
gateway: this.gateway,
|
|
65
|
+
config: this.config,
|
|
66
|
+
})
|
|
67
|
+
this.pending = new Map()
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Which configured databases contain a table.
|
|
72
|
+
*
|
|
73
|
+
* The code workspace only knows the table name from `@TableName`; resolving it
|
|
74
|
+
* here keeps the browser from guessing. Only the project's own databases are
|
|
75
|
+
* searched, one `information_schema` probe each.
|
|
76
|
+
*/
|
|
77
|
+
async findTable(payload = {}) {
|
|
78
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
79
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
80
|
+
const table = typeof payload.table === 'string' ? payload.table.trim() : ''
|
|
81
|
+
if (table === '') throw new RouteFailure(400, 'invalid-table', 'table name is required')
|
|
82
|
+
const schema = typeof payload.schema === 'string' ? payload.schema.trim() : ''
|
|
83
|
+
const discovered = await this.discover({ root })
|
|
84
|
+
const candidates = []
|
|
85
|
+
for (const environment of Array.isArray(discovered.environments) ? discovered.environments : []) {
|
|
86
|
+
for (const instance of Array.isArray(environment.instances) ? environment.instances : []) {
|
|
87
|
+
for (const database of Array.isArray(instance.databases) ? instance.databases : []) {
|
|
88
|
+
const name = String(database.name ?? '')
|
|
89
|
+
if (name === '') continue
|
|
90
|
+
if (schema !== '' && name !== schema) continue
|
|
91
|
+
try {
|
|
92
|
+
if (await this.gateway.hasTable(database.id, name, table)) {
|
|
93
|
+
candidates.push({
|
|
94
|
+
dbId: database.id,
|
|
95
|
+
database: name,
|
|
96
|
+
env: environment.env,
|
|
97
|
+
envLabel: environment.label ?? environment.env,
|
|
98
|
+
instanceLabel: instance.label ?? '',
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
} catch (error) {
|
|
102
|
+
void error
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return { root, table, schema, candidates }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Re-read the workspace configuration, or serve it from the cache. */
|
|
111
|
+
async discover(payload = {}) {
|
|
112
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
113
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
114
|
+
if (!existsSync(root) || !statSync(root).isDirectory()) throw new RouteFailure(404, 'missing-root', `workspace not found: ${root}`)
|
|
115
|
+
|
|
116
|
+
const refresh = payload.refresh === true
|
|
117
|
+
if (!refresh) {
|
|
118
|
+
const cached = this.cache.get(root)
|
|
119
|
+
if (cached !== undefined && cached.payload !== undefined) {
|
|
120
|
+
const paths = Array.isArray(cached.fingerprintPaths) ? cached.fingerprintPaths : []
|
|
121
|
+
if (this.config.cache && fingerprint(paths) === cached.fingerprint) {
|
|
122
|
+
const targets = new Map(Array.isArray(cached.targets) ? cached.targets : [])
|
|
123
|
+
return this.withSharedTree(root, { ...cached.payload, cached: true, generatedAt: cached.at }, targets)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Two panels opening the same workspace at once must not scan twice.
|
|
129
|
+
const running = this.pending.get(root)
|
|
130
|
+
if (running !== undefined) return running
|
|
131
|
+
const startedAt = Date.now()
|
|
132
|
+
const task = (async () => {
|
|
133
|
+
const discovery = discoverProject(root, {
|
|
134
|
+
home: this.config.nacosHome,
|
|
135
|
+
groups: this.config.groups,
|
|
136
|
+
envOrder: this.config.envOrder,
|
|
137
|
+
})
|
|
138
|
+
const { targets, ...rest } = discovery
|
|
139
|
+
this.gateway.setTargets(targets)
|
|
140
|
+
const fingerprintPaths = []
|
|
141
|
+
for (const environment of rest.environments) {
|
|
142
|
+
for (const file of environment.variableFiles ?? []) fingerprintPaths.push(file)
|
|
143
|
+
for (const source of environment.sources) fingerprintPaths.push(source)
|
|
144
|
+
}
|
|
145
|
+
for (const file of rest.project?.configFiles ?? []) fingerprintPaths.push(file)
|
|
146
|
+
const value = {
|
|
147
|
+
...rest,
|
|
148
|
+
cached: false,
|
|
149
|
+
generatedAt: Date.now(),
|
|
150
|
+
elapsedMs: Date.now() - startedAt,
|
|
151
|
+
}
|
|
152
|
+
// An empty result is deliberately not cached: a service that starts after the
|
|
153
|
+
// first open, or a datasource added to a workspace that had none, must show up
|
|
154
|
+
// without the user having to press "reload". Scanning an empty workspace is
|
|
155
|
+
// cheap; a stale empty tree is not.
|
|
156
|
+
if (this.config.cache && rest.environments.length > 0) {
|
|
157
|
+
this.cache.put(root, {
|
|
158
|
+
payload: rest,
|
|
159
|
+
targets: [...(targets instanceof Map ? targets : new Map())],
|
|
160
|
+
fingerprintPaths,
|
|
161
|
+
fingerprint: fingerprint(fingerprintPaths),
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
return this.withSharedTree(root, value, targets)
|
|
165
|
+
})()
|
|
166
|
+
this.pending.set(root, task)
|
|
167
|
+
try {
|
|
168
|
+
return await task
|
|
169
|
+
} finally {
|
|
170
|
+
this.pending.delete(root)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Merge this workspace into the machine-wide resource tree.
|
|
176
|
+
*
|
|
177
|
+
* The tree is the union of every workspace's discovery cache, the shared manual
|
|
178
|
+
* connections and the shared database picks; the workspace being opened only
|
|
179
|
+
* contributes its own part and names it in `focus` so the panel can expand it.
|
|
180
|
+
* Ids are unchanged, so saved consoles keep resolving their targets.
|
|
181
|
+
*
|
|
182
|
+
* @param root the workspace being opened
|
|
183
|
+
* @param payload its own discovery payload
|
|
184
|
+
* @param targets its own connection targets (the union's credentials come from
|
|
185
|
+
* every cache, so this is the most recent word on this workspace's hosts)
|
|
186
|
+
*/
|
|
187
|
+
withSharedTree(root, payload, targets) {
|
|
188
|
+
const tree = buildSharedTree({
|
|
189
|
+
caches: this.cache.list().filter((document) => document.root !== root),
|
|
190
|
+
current: payload,
|
|
191
|
+
currentTargets: targets instanceof Map ? targets : new Map(),
|
|
192
|
+
manualEntries: this.manual.load(root).entries,
|
|
193
|
+
remembered: this.remembered.load(root).databases,
|
|
194
|
+
envOrder: this.config.envOrder,
|
|
195
|
+
})
|
|
196
|
+
this.gateway.setTargets(tree.targets)
|
|
197
|
+
return {
|
|
198
|
+
...payload,
|
|
199
|
+
environments: tree.environments,
|
|
200
|
+
focus: tree.focus,
|
|
201
|
+
shared: true,
|
|
202
|
+
defaultEnv: payload.defaultEnv ?? tree.focus.envs[0],
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Remember one database the user opened from an instance's full list. */
|
|
207
|
+
rememberDatabase(payload = {}) {
|
|
208
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
209
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
210
|
+
const entry = { instanceId: String(payload.instanceId ?? '').trim(), database: String(payload.database ?? '').trim() }
|
|
211
|
+
if (!/^i:[\w-]+$/.test(entry.instanceId) || entry.database === '') {
|
|
212
|
+
throw new RouteFailure(400, 'invalid-database', 'an instance id and a database name are required')
|
|
213
|
+
}
|
|
214
|
+
return { remembered: this.remembered.add(root, entry) }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Connections already resolved or added on this machine, without passwords. */
|
|
218
|
+
savedConnections() {
|
|
219
|
+
return { connections: this.catalog.list() }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Replace the databases shown for one instance (the picker's Apply). */
|
|
223
|
+
selectDatabases(payload = {}) {
|
|
224
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
225
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
226
|
+
const instanceId = String(payload.instanceId ?? '').trim()
|
|
227
|
+
if (!/^i:[\w-]+$/.test(instanceId)) throw new RouteFailure(400, 'invalid-database', 'an instance id is required')
|
|
228
|
+
const names = Array.isArray(payload.databases) ? payload.databases : []
|
|
229
|
+
if (names.length > 200) throw new RouteFailure(400, 'invalid-database', 'too many databases selected')
|
|
230
|
+
const value = this.remembered.replaceInstance(root, instanceId, names)
|
|
231
|
+
return { databases: value.databases }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Forget one remembered database. */
|
|
235
|
+
forgetDatabase(payload = {}) {
|
|
236
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
237
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
238
|
+
const entry = { instanceId: String(payload.instanceId ?? '').trim(), database: String(payload.database ?? '').trim() }
|
|
239
|
+
if (!/^i:[\w-]+$/.test(entry.instanceId) || entry.database === '') {
|
|
240
|
+
throw new RouteFailure(400, 'invalid-database', 'an instance id and a database name are required')
|
|
241
|
+
}
|
|
242
|
+
return { forgotten: this.remembered.remove(root, entry) }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Save one manually entered connection after proving it.
|
|
247
|
+
*
|
|
248
|
+
* The connection test uses the same read-only gateway as everything else, so a
|
|
249
|
+
* mistyped host or account fails here with the server's message instead of
|
|
250
|
+
* becoming a row that never opens.
|
|
251
|
+
*/
|
|
252
|
+
async manualSave(payload = {}) {
|
|
253
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
254
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
255
|
+
const submitted = payload.entry !== null && typeof payload.entry === 'object' ? { ...payload.entry } : undefined
|
|
256
|
+
// The picker sends `sourceId` instead of a password: the credential stays on the
|
|
257
|
+
// Host, which is also what lets another workspace's connection be reused without
|
|
258
|
+
// the browser ever seeing its secret.
|
|
259
|
+
const sourceId = typeof payload.sourceId === 'string' ? payload.sourceId.trim() : ''
|
|
260
|
+
if (sourceId !== '' && String(submitted?.password ?? '') === '') {
|
|
261
|
+
const stored = this.catalog.passwordFor(sourceId)
|
|
262
|
+
if (stored === undefined) throw new RouteFailure(400, 'saved-connection-missing', 'the imported connection is no longer available')
|
|
263
|
+
submitted.password = stored
|
|
264
|
+
}
|
|
265
|
+
const entry = normalizeManualEntry(submitted)
|
|
266
|
+
if (entry === undefined) throw new RouteFailure(400, 'invalid-connection', 'host, port and user are required')
|
|
267
|
+
const probeId = `m:${entry.id.slice(2)}:probe`
|
|
268
|
+
try {
|
|
269
|
+
this.gateway.addTargets(new Map([[probeId, {
|
|
270
|
+
id: probeId,
|
|
271
|
+
env: 'manual',
|
|
272
|
+
host: entry.host,
|
|
273
|
+
port: entry.port,
|
|
274
|
+
user: entry.user,
|
|
275
|
+
password: entry.password,
|
|
276
|
+
database: entry.database === '' ? undefined : entry.database,
|
|
277
|
+
manual: true,
|
|
278
|
+
}]]))
|
|
279
|
+
await this.gateway.ping(probeId)
|
|
280
|
+
} catch (error) {
|
|
281
|
+
await this.gateway.forget(probeId).catch(() => undefined)
|
|
282
|
+
throw new RouteFailure(400, 'manual-connect-failed', error?.message ?? String(error))
|
|
283
|
+
}
|
|
284
|
+
await this.gateway.forget(probeId).catch(() => undefined)
|
|
285
|
+
this.manual.upsert(root, entry)
|
|
286
|
+
return { entry: { ...entry, password: undefined }, environments: manualEnvironments(this.manual.load(root).entries).environments }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Rename one manually added environment.
|
|
291
|
+
*
|
|
292
|
+
* The environment name is part of every derived id (entry, instance, remembered
|
|
293
|
+
* schemas), so a rename moves all three together — otherwise the user's picked
|
|
294
|
+
* databases would be stranded under an id nothing renders any more.
|
|
295
|
+
*/
|
|
296
|
+
renameManualEnvironment(payload = {}) {
|
|
297
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
298
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
299
|
+
const from = String(payload.from ?? '').trim()
|
|
300
|
+
const to = String(payload.to ?? '').trim().slice(0, 40)
|
|
301
|
+
if (from === '' || to === '') throw new RouteFailure(400, 'invalid-connection', 'both names are required')
|
|
302
|
+
const { entries } = this.manual.load(root)
|
|
303
|
+
const affected = entries.filter((entry) => entry.label === from)
|
|
304
|
+
if (affected.length === 0) throw new RouteFailure(404, 'unknown-environment', 'no manual connection uses that environment name')
|
|
305
|
+
if (from === to) return { renamed: 0 }
|
|
306
|
+
const untouched = entries.filter((entry) => entry.label !== from)
|
|
307
|
+
const renamed = []
|
|
308
|
+
for (const entry of affected) {
|
|
309
|
+
const next = normalizeManualEntry({ ...entry, label: to })
|
|
310
|
+
if (next === undefined) continue
|
|
311
|
+
if (untouched.some((existing) => existing.id === next.id)) {
|
|
312
|
+
throw new RouteFailure(400, 'duplicate-connection', 'another connection already uses that name for this host and account')
|
|
313
|
+
}
|
|
314
|
+
renamed.push(next)
|
|
315
|
+
}
|
|
316
|
+
const mapping = new Map()
|
|
317
|
+
for (const entry of affected) {
|
|
318
|
+
const next = renamed.find((candidate) => candidate.host === entry.host && candidate.port === entry.port && candidate.user === entry.user)
|
|
319
|
+
if (next === undefined) continue
|
|
320
|
+
mapping.set(
|
|
321
|
+
`i:${stableId('manual', `manual:${stableId('manual-env', from)}`, entry.host, String(entry.port), entry.user)}`,
|
|
322
|
+
`i:${stableId('manual', `manual:${stableId('manual-env', to)}`, entry.host, String(entry.port), entry.user)}`,
|
|
323
|
+
)
|
|
324
|
+
}
|
|
325
|
+
this.manual.save(root, [...untouched, ...renamed])
|
|
326
|
+
this.remembered.remap(root, mapping)
|
|
327
|
+
return { renamed: renamed.length }
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Delete one manually added environment: every connection under it, the schemas
|
|
332
|
+
* picked for them, and the pools those schemas used.
|
|
333
|
+
*
|
|
334
|
+
* The connection stays re-importable: its catalog entry comes from other
|
|
335
|
+
* workspaces' data, not from this one, so "unless imported again" is exactly how
|
|
336
|
+
* it behaves.
|
|
337
|
+
*/
|
|
338
|
+
removeManualEnvironment(payload = {}) {
|
|
339
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
340
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
341
|
+
const from = String(payload.from ?? '').trim()
|
|
342
|
+
if (from === '') throw new RouteFailure(400, 'invalid-connection', 'an environment name is required')
|
|
343
|
+
const { entries } = this.manual.load(root)
|
|
344
|
+
const affected = entries.filter((entry) => entry.label === from)
|
|
345
|
+
if (affected.length === 0) throw new RouteFailure(404, 'unknown-environment', 'no manual connection uses that environment name')
|
|
346
|
+
const { targets } = manualEnvironments(affected)
|
|
347
|
+
const instanceIds = [...targets.values()].filter((target) => target.database === undefined).map((target) => target.id)
|
|
348
|
+
this.manual.save(root, entries.filter((entry) => entry.label !== from))
|
|
349
|
+
this.remembered.forgetInstances(root, instanceIds)
|
|
350
|
+
if (typeof this.gateway.removeTargets === 'function') this.gateway.removeTargets([...targets.keys()])
|
|
351
|
+
return { removed: affected.length }
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Drop one manually added connection. */
|
|
355
|
+
async manualRemove(payload = {}) {
|
|
356
|
+
const root = typeof payload.root === 'string' ? payload.root.trim() : ''
|
|
357
|
+
const id = typeof payload.id === 'string' ? payload.id.trim() : ''
|
|
358
|
+
if (root === '' || !isAbsolute(root)) throw new RouteFailure(400, 'invalid-root', 'workspace root must be an absolute path')
|
|
359
|
+
if (id === '') throw new RouteFailure(400, 'invalid-connection', 'a connection id is required')
|
|
360
|
+
const before = manualEnvironments(this.manual.load(root).entries).targets
|
|
361
|
+
const removed = this.manual.remove(root, id)
|
|
362
|
+
const after = manualEnvironments(this.manual.load(root).entries).targets
|
|
363
|
+
if (removed && typeof this.gateway.removeTargets === 'function') {
|
|
364
|
+
// The tree no longer names these ids, so their pools must not stay open.
|
|
365
|
+
const stale = [...before.keys()].filter((key) => !after.has(key))
|
|
366
|
+
this.gateway.removeTargets(stale)
|
|
367
|
+
}
|
|
368
|
+
return { removed, environments: manualEnvironments(this.manual.load(root).entries).environments }
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Analyze the workspace with one model. Model text is only a proposal: the
|
|
373
|
+
* answer is parsed, its cited paths are confined to the workspace, and every
|
|
374
|
+
* candidate is proven with a real connection before it reaches the tree.
|
|
375
|
+
*/
|
|
376
|
+
async aiDiscover(payload = {}) {
|
|
377
|
+
try {
|
|
378
|
+
return await this.ai.run(payload)
|
|
379
|
+
} catch (error) {
|
|
380
|
+
const code = typeof error?.code === 'string' ? error.code : 'ai-failed'
|
|
381
|
+
if (code === 'llm-unavailable') throw new RouteFailure(503, code, error?.message ?? String(error))
|
|
382
|
+
if (code === 'invalid-ai-request') throw new RouteFailure(400, code, error?.message ?? String(error))
|
|
383
|
+
throw new RouteFailure(502, 'ai-failed', error?.message ?? String(error))
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Ask the configured model to optimize one statement (advisory, never executed). */
|
|
388
|
+
async optimizeSql(payload = {}) {
|
|
389
|
+
try {
|
|
390
|
+
return await this.ai.optimize(payload)
|
|
391
|
+
} catch (error) {
|
|
392
|
+
const code = typeof error?.code === 'string' ? error.code : 'ai-failed'
|
|
393
|
+
if (code === 'llm-unavailable') throw new RouteFailure(503, code, error?.message ?? String(error))
|
|
394
|
+
if (code === 'invalid-ai-request' || code === 'invalid-ai-answer') throw new RouteFailure(400, code, error?.message ?? String(error))
|
|
395
|
+
throw new RouteFailure(502, 'ai-failed', error?.message ?? String(error))
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Dispatch one action. */
|
|
400
|
+
async handle(action, payload = {}) {
|
|
401
|
+
switch (String(action ?? '')) {
|
|
402
|
+
case 'discover':
|
|
403
|
+
return this.discover(payload)
|
|
404
|
+
case 'models':
|
|
405
|
+
return this.ai.models()
|
|
406
|
+
case 'aiDiscover':
|
|
407
|
+
return this.aiDiscover(payload)
|
|
408
|
+
case 'optimizeSql':
|
|
409
|
+
return this.optimizeSql(payload)
|
|
410
|
+
case 'manualSave':
|
|
411
|
+
return this.manualSave(payload)
|
|
412
|
+
case 'savedConnections':
|
|
413
|
+
return this.savedConnections()
|
|
414
|
+
case 'manualRemove':
|
|
415
|
+
return this.manualRemove(payload)
|
|
416
|
+
case 'renameManualEnvironment':
|
|
417
|
+
return this.renameManualEnvironment(payload)
|
|
418
|
+
case 'removeManualEnvironment':
|
|
419
|
+
return this.removeManualEnvironment(payload)
|
|
420
|
+
case 'rememberDatabase':
|
|
421
|
+
return this.rememberDatabase(payload)
|
|
422
|
+
case 'forgetDatabase':
|
|
423
|
+
return this.forgetDatabase(payload)
|
|
424
|
+
case 'selectDatabases':
|
|
425
|
+
return this.selectDatabases(payload)
|
|
426
|
+
case 'ping':
|
|
427
|
+
return this.gateway.ping(payload.id)
|
|
428
|
+
case 'databases':
|
|
429
|
+
return this.gateway.listDatabases(payload.id)
|
|
430
|
+
case 'tables':
|
|
431
|
+
return this.gateway.listTables(payload.id)
|
|
432
|
+
case 'columns':
|
|
433
|
+
return this.gateway.listColumns(payload.id, payload.table)
|
|
434
|
+
case 'schema':
|
|
435
|
+
return this.gateway.schemaMap(payload.id)
|
|
436
|
+
case 'findTable':
|
|
437
|
+
return this.findTable(payload)
|
|
438
|
+
case 'consoles':
|
|
439
|
+
return this.consoles.load(payload.root)
|
|
440
|
+
case 'saveConsoles':
|
|
441
|
+
return this.consoles.save(payload.root, payload.value)
|
|
442
|
+
case 'ddl':
|
|
443
|
+
return this.gateway.showCreate(payload.id, payload.table)
|
|
444
|
+
case 'count':
|
|
445
|
+
return this.gateway.countRows(payload.id, payload.sql)
|
|
446
|
+
case 'query':
|
|
447
|
+
return this.gateway.run(payload.id, payload.sql, { limit: payload.limit ?? this.config.defaultLimit })
|
|
448
|
+
case 'forget':
|
|
449
|
+
return { forgotten: await this.gateway.forget(payload.id) }
|
|
450
|
+
case 'config':
|
|
451
|
+
return {
|
|
452
|
+
nacosHome: this.config.nacosHome,
|
|
453
|
+
groups: this.config.groups,
|
|
454
|
+
defaultLimit: this.config.defaultLimit,
|
|
455
|
+
statementTimeoutMs: this.config.statementTimeoutMs,
|
|
456
|
+
}
|
|
457
|
+
default:
|
|
458
|
+
throw new RouteFailure(404, 'unknown-action', `unknown action: ${String(action ?? '')}`)
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
async close() {
|
|
463
|
+
await this.gateway.close()
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** A failure with an HTTP status the route maps directly. */
|
|
468
|
+
export class RouteFailure extends Error {
|
|
469
|
+
constructor(status, code, message) {
|
|
470
|
+
super(message)
|
|
471
|
+
this.status = status
|
|
472
|
+
this.code = code
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** Map any thrown value into the shape the route writes. */
|
|
477
|
+
export function toRouteError(error) {
|
|
478
|
+
if (error instanceof RouteFailure) return { status: error.status, code: error.code, message: error.message }
|
|
479
|
+
if (error instanceof ReadOnlyViolation) {
|
|
480
|
+
return { status: 400, code: error.code, message: error.message }
|
|
481
|
+
}
|
|
482
|
+
const code = typeof error?.code === 'string' ? error.code : 'internal'
|
|
483
|
+
// A target that discovery dropped (a Host restart, a workspace switch) is not a
|
|
484
|
+
// bug in the query, so it gets its own code for the Client to recover from.
|
|
485
|
+
const status = code === 'unknown-target' ? 409 : code === 'database-required' ? 400 : 500
|
|
486
|
+
return { status, code, message: error?.message ?? String(error) }
|
|
487
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shared resource tree.
|
|
3
|
+
*
|
|
4
|
+
* A project's configuration says *how to find* its databases; it is not the list a
|
|
5
|
+
* user wants to browse. Teams open several workspaces that all point at the same
|
|
6
|
+
* few RDS instances, so a per-workspace tree shows the same hosts again and again
|
|
7
|
+
* and forgets everything the moment the workspace changes.
|
|
8
|
+
*
|
|
9
|
+
* This module builds one tree out of every fact the machine already has:
|
|
10
|
+
*
|
|
11
|
+
* - every workspace's discovery cache (what its own configuration resolved),
|
|
12
|
+
* - the shared manual connections,
|
|
13
|
+
* - the shared set of extra databases a user picked.
|
|
14
|
+
*
|
|
15
|
+
* Opening a workspace therefore *adds* its instances to the tree and reports which
|
|
16
|
+
* environment belongs to it (`focus`), instead of replacing the tree with its own.
|
|
17
|
+
* Ids are unchanged from the per-workspace era, so saved consoles keep pointing at
|
|
18
|
+
* the same targets.
|
|
19
|
+
*/
|
|
20
|
+
import { manualEnvironments } from './manual.js'
|
|
21
|
+
|
|
22
|
+
/** The environment order a project configured, then anything else alphabetically. */
|
|
23
|
+
function envRank(order, env) {
|
|
24
|
+
const index = Array.isArray(order) ? order.indexOf(env) : -1
|
|
25
|
+
return index >= 0 ? index : order.length
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Clone one payload database into the shared shape (no credential is involved). */
|
|
29
|
+
function databaseEntry(database, instance) {
|
|
30
|
+
return {
|
|
31
|
+
id: String(database?.id ?? ''),
|
|
32
|
+
name: String(database?.name ?? ''),
|
|
33
|
+
user: String(database?.user ?? instance?.user ?? ''),
|
|
34
|
+
alias: String(database?.alias ?? ''),
|
|
35
|
+
configured: database?.configured !== false,
|
|
36
|
+
...(database?.remembered === true ? { remembered: true } : {}),
|
|
37
|
+
...(database?.manual === true ? { manual: true } : {}),
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Merge every source into one tree.
|
|
43
|
+
*
|
|
44
|
+
* @param options `{ caches, current, currentTargets, manualEntries, remembered, envOrder }`
|
|
45
|
+
* where `caches` are the *other* workspaces' discovery documents
|
|
46
|
+
* @returns `{ environments, targets, focus }`; `targets` still carries passwords
|
|
47
|
+
*/
|
|
48
|
+
export function buildSharedTree(options) {
|
|
49
|
+
const envOrder = Array.isArray(options?.envOrder) ? options.envOrder : []
|
|
50
|
+
const environments = new Map()
|
|
51
|
+
const targets = new Map()
|
|
52
|
+
|
|
53
|
+
const envOf = (env, label) => {
|
|
54
|
+
const key = String(env ?? label ?? '').trim()
|
|
55
|
+
if (key === '') return undefined
|
|
56
|
+
let entry = environments.get(key)
|
|
57
|
+
if (entry === undefined) {
|
|
58
|
+
entry = { env: key, label: String(label ?? key), instances: [], databaseCount: 0, manual: false, rule: false }
|
|
59
|
+
environments.set(key, entry)
|
|
60
|
+
}
|
|
61
|
+
return entry
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const mergePayload = (payload, targetMap, isCurrent) => {
|
|
65
|
+
for (const environment of Array.isArray(payload?.environments) ? payload.environments : []) {
|
|
66
|
+
const entry = envOf(environment?.env, environment?.label)
|
|
67
|
+
if (entry === undefined) continue
|
|
68
|
+
entry.rule = true
|
|
69
|
+
for (const instance of Array.isArray(environment?.instances) ? environment.instances : []) {
|
|
70
|
+
if (instance === null || typeof instance !== 'object' || typeof instance?.id !== 'string') continue
|
|
71
|
+
let current = entry.instances.find((candidate) => candidate.id === instance.id)
|
|
72
|
+
if (current === undefined) {
|
|
73
|
+
current = {
|
|
74
|
+
id: instance.id,
|
|
75
|
+
host: String(instance.host ?? ''),
|
|
76
|
+
port: Number(instance.port ?? 3306),
|
|
77
|
+
label: String(instance.label ?? `${instance.host}:${instance.port}`),
|
|
78
|
+
aliases: Array.isArray(instance.aliases) ? [...instance.aliases] : [],
|
|
79
|
+
user: String(instance.user ?? ''),
|
|
80
|
+
manual: instance.manual === true,
|
|
81
|
+
...(typeof instance.entryId === 'string' ? { entryId: instance.entryId } : {}),
|
|
82
|
+
databases: [],
|
|
83
|
+
inWorkspace: isCurrent === true,
|
|
84
|
+
}
|
|
85
|
+
entry.instances.push(current)
|
|
86
|
+
} else if (isCurrent === true) {
|
|
87
|
+
current.inWorkspace = true
|
|
88
|
+
}
|
|
89
|
+
for (const database of Array.isArray(instance.databases) ? instance.databases : []) {
|
|
90
|
+
const name = String(database?.name ?? '')
|
|
91
|
+
if (name === '') continue
|
|
92
|
+
const existing = current.databases.find((candidate) => candidate.name === name)
|
|
93
|
+
if (existing !== undefined) {
|
|
94
|
+
// 同一个库可能先被别的项目带进来:本项目的发现仍然要盖一个「属于本项目」
|
|
95
|
+
// 的戳,打开 SQL 时才知道该选哪个库。
|
|
96
|
+
if (isCurrent === true) existing.inWorkspace = true
|
|
97
|
+
continue
|
|
98
|
+
}
|
|
99
|
+
const entry = databaseEntry(database, current)
|
|
100
|
+
if (isCurrent === true) entry.inWorkspace = true
|
|
101
|
+
current.databases.push(entry)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const [id, target] of targetMap instanceof Map ? targetMap : []) {
|
|
106
|
+
if (target === null || typeof target !== 'object') continue
|
|
107
|
+
targets.set(id, target)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
for (const document of Array.isArray(options?.caches) ? options.caches : []) {
|
|
112
|
+
mergePayload(document?.payload, new Map(Array.isArray(document?.targets) ? document.targets : []), false)
|
|
113
|
+
}
|
|
114
|
+
// The workspace being opened merges last: its labels and databases win ties.
|
|
115
|
+
mergePayload(options?.current, options?.currentTargets, true)
|
|
116
|
+
|
|
117
|
+
const manual = manualEnvironments(options?.manualEntries ?? [])
|
|
118
|
+
for (const [id, target] of manual.targets) targets.set(id, target)
|
|
119
|
+
for (const environment of manual.environments) {
|
|
120
|
+
const entry = envOf(environment.env, environment.label)
|
|
121
|
+
if (entry === undefined) continue
|
|
122
|
+
entry.manual = true
|
|
123
|
+
entry.label = environment.label
|
|
124
|
+
for (const instance of environment.instances) {
|
|
125
|
+
if (entry.instances.some((candidate) => candidate.id === instance.id)) continue
|
|
126
|
+
entry.instances.push({ ...instance, databases: [...instance.databases], inWorkspace: false })
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
for (const remembered of Array.isArray(options?.remembered) ? options.remembered : []) {
|
|
131
|
+
const instanceId = String(remembered?.instanceId ?? '')
|
|
132
|
+
const database = String(remembered?.database ?? '')
|
|
133
|
+
if (instanceId === '' || database === '') continue
|
|
134
|
+
for (const environment of environments.values()) {
|
|
135
|
+
const instance = environment.instances.find((candidate) => candidate.id === instanceId)
|
|
136
|
+
if (instance === undefined) continue
|
|
137
|
+
if (instance.databases.some((candidate) => candidate.name === database)) break
|
|
138
|
+
instance.databases.push({
|
|
139
|
+
id: `${instanceId}~${database}`,
|
|
140
|
+
name: database,
|
|
141
|
+
user: instance.user,
|
|
142
|
+
alias: database,
|
|
143
|
+
configured: true,
|
|
144
|
+
remembered: true,
|
|
145
|
+
})
|
|
146
|
+
break
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const focusEnvs = []
|
|
151
|
+
const focusInstances = []
|
|
152
|
+
for (const environment of environments.values()) {
|
|
153
|
+
let count = 0
|
|
154
|
+
for (const instance of environment.instances) {
|
|
155
|
+
count += instance.databases.length
|
|
156
|
+
if (instance.inWorkspace === true) {
|
|
157
|
+
focusInstances.push(instance.id)
|
|
158
|
+
if (!focusEnvs.includes(environment.env)) focusEnvs.push(environment.env)
|
|
159
|
+
}
|
|
160
|
+
delete instance.inWorkspace
|
|
161
|
+
}
|
|
162
|
+
environment.databaseCount = count
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const ordered = [...environments.values()].sort((left, right) => {
|
|
166
|
+
if (left.manual !== right.manual) return left.manual ? 1 : -1
|
|
167
|
+
const rank = envRank(envOrder, left.env) - envRank(envOrder, right.env)
|
|
168
|
+
if (rank !== 0) return rank
|
|
169
|
+
return left.env < right.env ? -1 : left.env > right.env ? 1 : 0
|
|
170
|
+
})
|
|
171
|
+
for (const environment of ordered) {
|
|
172
|
+
delete environment.rule
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
environments: ordered,
|
|
177
|
+
targets,
|
|
178
|
+
focus: { envs: focusEnvs, instances: focusInstances },
|
|
179
|
+
}
|
|
180
|
+
}
|