Skip to content

Commit eaaaa16

Browse files
author
msxfscyx
committed
3.9.3 新增缓存map
1 parent 9499794 commit eaaaa16

File tree

4 files changed

+93
-87
lines changed

4 files changed

+93
-87
lines changed

src/client/extension.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,10 @@ import { WorkspaceService } from './common/application/workspace';
4646
import { disposeAll } from './common/utils/resourceLifecycle';
4747
import { ProposedExtensionAPI } from './proposedApiTypes';
4848
import { buildProposedApi } from './proposedApi';
49-
import ContextManager from './pythonEnvironments/base/locators/composite/envsCollectionService';
5049
import { PySparkParam } from './browser/extension';
5150
import * as fs from 'fs';
5251
import * as path from 'path';
52+
import CacheMap from './pythonEnvironments/base/locators/composite/envsReducer';
5353

5454
durations.codeLoadingTime = stopWatch.elapsedTime;
5555

@@ -78,8 +78,6 @@ export async function activate(context: IExtensionContext): Promise<PythonExtens
7878
let ready: Promise<void>;
7979
let serviceContainer: IServiceContainer;
8080
try {
81-
// 设置 context
82-
ContextManager.getInstance().setContext(context);
8381
const workspaceService = new WorkspaceService();
8482
context.subscriptions.push(
8583
workspaceService.onDidGrantWorkspaceTrust(async () => {
@@ -97,12 +95,18 @@ export async function activate(context: IExtensionContext): Promise<PythonExtens
9795
} else {
9896
console.log('当前运行环境: 非 online');
9997
}
100-
context.globalState.update('gateway.addr', gatewayUri);
98+
CacheMap.getInstance().set('gatewayUri', gatewayUri);
10199

102100
context.subscriptions.push(
103101
commands.registerCommand('pyspark.paramRegister.copy', (pySparkParam: PySparkParam) => {
104102
console.log(`PySparkParam-python: ${JSON.stringify(pySparkParam)}`);
105103
context.globalState.update('pyspark.paramRegister.copy', pySparkParam);
104+
105+
// 设置缓存值
106+
const { projectId } = pySparkParam;
107+
const { projectCode } = pySparkParam;
108+
CacheMap.getInstance().set('projectId', projectId);
109+
CacheMap.getInstance().set('projectCode', projectCode);
106110
// 将项目信息写到本地
107111
const filePath = path.join('/tmp', 'pySparkParam.txt');
108112
// Write the pySparkParam to the file

src/client/pythonEnvironments/base/locators/composite/envsCollectionService.ts

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -260,30 +260,4 @@ export class EnvsCollectionService extends PythonEnvsWatcher<PythonEnvCollection
260260
}
261261
this.hasRefreshFinishedForQuery.set(query, true);
262262
}
263-
}
264-
265-
import { ExtensionContext } from 'vscode';
266-
267-
class ContextManager {
268-
private static instance: ContextManager;
269-
private context!: ExtensionContext;
270-
271-
private constructor() {}
272-
273-
static getInstance(): ContextManager {
274-
if (!ContextManager.instance) {
275-
ContextManager.instance = new ContextManager();
276-
}
277-
return ContextManager.instance;
278-
}
279-
280-
setContext(context: ExtensionContext) {
281-
this.context = context;
282-
}
283-
284-
getContext(): ExtensionContext {
285-
return this.context;
286-
}
287-
}
288-
289-
export default ContextManager;
263+
}

src/client/pythonEnvironments/base/locators/composite/envsReducer.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,47 @@ function sortEnvInfoByPriority(...envs: BasicEnvInfo[]): BasicEnvInfo[] {
152152
(a: BasicEnvInfo, b: BasicEnvInfo) => envKindByPriority.indexOf(a.kind) - envKindByPriority.indexOf(b.kind),
153153
);
154154
}
155+
156+
class CacheMap {
157+
private static instance: CacheMap;
158+
private cache: Map<string, any>;
159+
160+
// 私有构造函数,保证不能直接实例化
161+
private constructor() {
162+
this.cache = new Map();
163+
}
164+
165+
// 获取单例实例
166+
public static getInstance(): CacheMap {
167+
if (!CacheMap.instance) {
168+
CacheMap.instance = new CacheMap();
169+
}
170+
return CacheMap.instance;
171+
}
172+
173+
// 设置值
174+
public set(key: string, value: any): void {
175+
this.cache.set(key, value);
176+
}
177+
178+
// 获取值
179+
public get(key: string): any | undefined {
180+
return this.cache.get(key);
181+
}
182+
183+
// 检查缓存中是否有该 key
184+
public has(key: string): boolean {
185+
return this.cache.has(key);
186+
}
187+
188+
// 删除指定 key
189+
public delete(key: string): boolean {
190+
return this.cache.delete(key);
191+
}
192+
193+
// 清空缓存
194+
public clear(): void {
195+
this.cache.clear();
196+
}
197+
}
198+
export default CacheMap;

src/client/pythonEnvironments/base/locators/lowLevel/condaLocator.ts

Lines changed: 40 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,8 @@ import { FSWatchingLocator } from './fsWatchingLocator';
1010
import { pathExists } from 'fs-extra';
1111
import * as crypto from 'crypto';
1212

13-
1413
import { exec } from 'child_process';
15-
import ContextManager from '../composite/envsCollectionService';
16-
import { PySparkParam } from '../../../../browser/extension';
14+
import CacheMap from '../composite/envsReducer';
1715

1816
function exportCondaEnv(name: string): Promise<string> {
1917
return new Promise((resolve, reject) => {
@@ -36,16 +34,16 @@ function preprocessAndHashDependencies(value: string): string {
3634
const lines = value.split('\n');
3735

3836
// 找到 `dependencies:` 的起始行
39-
const dependenciesStartIndex = lines.findIndex(line => line.trim() === 'dependencies:');
37+
const dependenciesStartIndex = lines.findIndex((line) => line.trim() === 'dependencies:');
4038

4139
// 找到 `dependencies:` 之后的 `prefix:` 行,表示 dependencies 结束
42-
const prefixStartIndex = lines.findIndex(line => line.trim().startsWith('prefix:'));
40+
const prefixStartIndex = lines.findIndex((line) => line.trim().startsWith('prefix:'));
4341

4442
// 提取 dependencies 部分的内容(跳过 `dependencies:` 行)
45-
const dependencies = lines.slice(dependenciesStartIndex + 1, prefixStartIndex).map(line => line.trim());
43+
const dependencies = lines.slice(dependenciesStartIndex + 1, prefixStartIndex).map((line) => line.trim());
4644

4745
// 去除空行
48-
const filteredDependencies = dependencies.filter(line => line !== '');
46+
const filteredDependencies = dependencies.filter((line) => line !== '');
4947

5048
// 对 dependencies 内容进行排序
5149
const sortedDependencies = filteredDependencies.sort();
@@ -64,7 +62,7 @@ async function compareDetails(storeDetail: string, detail: string | undefined):
6462
try {
6563
const storeDetailHash = preprocessAndHashDependencies(storeDetail);
6664
const detailHash = preprocessAndHashDependencies(detail);
67-
65+
6866
return storeDetailHash === detailHash;
6967
} catch (error) {
7068
traceError('Error comparing details:', error);
@@ -86,34 +84,38 @@ interface PySparkEnvironmentMeta {
8684

8785
async function fetchEnvironments(): Promise<PySparkEnvironmentMeta[]> {
8886
try {
89-
// 获取存储的 PySparkParam 对象
90-
const pySparkParam = ContextManager.getInstance().getContext().globalState.get<PySparkParam>('pyspark.paramRegister.copy');
87+
const projectId = CacheMap.getInstance().get('projectId');
88+
const projectCode = CacheMap.getInstance().get('projectCode');
9189

92-
let proId = "0";
90+
let proId = '0';
9391
// 检查是否成功获取到数据
94-
if (pySparkParam) {
92+
// if (pySparkParam) {
93+
if (projectId && projectCode) {
9594
// 通过属性名获取 projectId 和 projectCode
96-
const { projectId } = pySparkParam;
97-
const { projectCode } = pySparkParam;
98-
99-
console.log(`Project ID: ${projectId}`);
100-
console.log(`Project Code: ${projectCode}`);
101-
102-
if (projectId) {
103-
proId = projectId;
104-
}
95+
// const { projectId } = pySparkParam;
96+
// const { projectCode } = pySparkParam;
97+
98+
console.log(`fetchEnvironments Project ID: ${projectId}`);
99+
console.log(`fetchEnvironments Project Code: ${projectCode}`);
100+
proId = projectId;
101+
// if (projectId) {
102+
// proId = projectId;
103+
// }
105104
} else {
106105
console.log('No PySparkParam found in global state.');
107106
}
108-
109-
const response = await fetch(`${ContextManager.getInstance().getContext().globalState.get<string>('gateway.addr')}/api/v1/env/pyspark/list?proId=${proId}`, {
110-
method: 'GET',
111-
headers: {
112-
Cookie: 'token=2345fc15-fe44-4e3b-afbc-24688c2f5f70;userId=idegw',
113-
'content-type': 'application/json',
114-
operator: 'hu.tan@msxf.com',
107+
108+
const response = await fetch(
109+
`${CacheMap.getInstance().get('gatewayUri')}/api/v1/env/pyspark/list?proId=${proId}`,
110+
{
111+
method: 'GET',
112+
headers: {
113+
Cookie: 'token=2345fc15-fe44-4e3b-afbc-24688c2f5f70;userId=idegw',
114+
'content-type': 'application/json',
115+
operator: 'hu.tan@msxf.com',
116+
},
115117
},
116-
});
118+
);
117119

118120
if (!response.ok) {
119121
throw new Error('Network response was not ok');
@@ -123,7 +125,7 @@ async function fetchEnvironments(): Promise<PySparkEnvironmentMeta[]> {
123125
return environments;
124126
} catch (error) {
125127
console.error('Error fetching environments:', error);
126-
traceError(`Error fetching environments: ${error}`)
128+
traceError(`Error fetching environments: ${error}`);
127129
return []; // 返回空数组作为错误处理
128130
}
129131
}
@@ -162,21 +164,6 @@ export class CondaEnvironmentLocator extends FSWatchingLocator {
162164

163165
// eslint-disable-next-line class-methods-use-this
164166
public async *doIterEnvs(): IPythonEnvsIterator<BasicEnvInfo> {
165-
166-
// // 测试用:获取存储的 PySparkParam 对象
167-
// const pySparkParam = ContextManager.getInstance().getContext().globalState.get<PySparkParam>('pyspark.paramRegister.copy');
168-
169-
// // 检查是否成功获取到数据
170-
// if (pySparkParam) {
171-
// // 通过属性名获取 projectId 和 projectCode
172-
// const { projectId } = pySparkParam;
173-
// const { projectCode } = pySparkParam;
174-
175-
// console.log(`Project ID: ${projectId}`);
176-
// console.log(`Project Code: ${projectCode}`);
177-
// } else {
178-
// console.log('No PySparkParam found in global state.');
179-
// }
180167

181168
const conda = await Conda.getConda();
182169
if (conda === undefined) {
@@ -240,7 +227,7 @@ export class CondaEnvironmentLocator extends FSWatchingLocator {
240227
name: `${environment.name}`, // 动态生成 name
241228
status: 0,
242229
detail: environment.detail,
243-
level: environment.level
230+
level: environment.level,
244231
};
245232

246233
// 创建目录,本地目录存在则表示该环境也存在,不做拉取
@@ -253,11 +240,8 @@ export class CondaEnvironmentLocator extends FSWatchingLocator {
253240
.then(async (output) => {
254241
traceInfo('Exported environment:');
255242
traceInfo(output);
256-
isSync = await compareDetails(
257-
environment.detail,
258-
output,
259-
);
260-
traceError(`aaaaa: ${isSync}`)
243+
isSync = await compareDetails(environment.detail, output);
244+
traceError(`aaaaa: ${isSync}`);
261245
})
262246
.catch((error) => {
263247
console.error(error);
@@ -279,7 +263,7 @@ export class CondaEnvironmentLocator extends FSWatchingLocator {
279263
// (env) => (env.prefix === expectedBasicEnv.prefix || env.name === expectedBasicEnv.name) && env.status === expectedBasicEnv.status,
280264
// );
281265

282-
const exists = checkAndReplaceEnv(envs, expectedBasicEnv)
266+
const exists = checkAndReplaceEnv(envs, expectedBasicEnv);
283267

284268
// 如果不存在,则将 expectedBasicEnv 添加到 envs 数组中
285269
if (!exists) {
@@ -293,7 +277,7 @@ export class CondaEnvironmentLocator extends FSWatchingLocator {
293277
}
294278
} else {
295279
console.log('envs_dirs 不存在或为空');
296-
traceError(`envs_dirs 不存在或为空`)
280+
traceError(`envs_dirs 不存在或为空`);
297281
}
298282

299283
// 继续处理本地 conda 环境
@@ -302,9 +286,9 @@ export class CondaEnvironmentLocator extends FSWatchingLocator {
302286
traceVerbose(`Looking into conda env for executable: ${JSON.stringify(env)}`);
303287
const executablePath = await conda.getInterpreterPathForEnvironment(env);
304288
traceVerbose(`Found conda executable: ${executablePath}`);
305-
yield {
306-
kind: PythonEnvKind.Conda,
307-
executablePath,
289+
yield {
290+
kind: PythonEnvKind.Conda,
291+
executablePath,
308292
envPath: env.prefix,
309293
status: env.status ?? 1,
310294
detail: env.detail,

0 commit comments

Comments
 (0)