代码编辑器:代码补全、悬停提示、参数提示、边写边检查
- 运行器新增 language-server 模式:常驻语言服务,和编译服务分开;用 Roslyn 的
CompletionService、QuickInfoService(和 VS 的 IntelliSense 同一套引擎),参数提示用语义模型实现;
每个浏览器标签页一份工程,只更新有变化的文件;去掉仿真类库的可空注解(string? → string)
- 编译和语言服务共用同一套编译选项和引用;检查结果带上禁止 API 的报错和中文提示
- 服务端 POST /api/language 转发请求(按用户区分会话,10 秒超时)
- 编辑器:补全("." 触发,选中时取说明)、悬停、参数提示("(" "," 触发);停止输入 1 秒后检查整个工程,
和"运行"时的编译结果以较新的为准
- 实测(2 核):50 个标签页同时检查 1.2 秒内完成,同时补全 0.7 秒;内存约 260 MB
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
89e9956a22
commit
302eae4f13
12 files changed
+667
-20
No files matched your search
@@ -16,6 +16,7 @@ import {
|
||||
updateAssignment,
|
||||
} from './assignments'
|
||||
import { parseChecks } from './grading/checks'
|
||||
import { languageService } from './language-service'
|
||||
import { getReview, gradebook, manualScore, saveReview, studentDetail, submissionFiles } from './reviews'
|
||||
import type { GradingQueue } from './grading/queue'
|
||||
import { listSamples, loadChecks, loadSample } from './samples'
|
||||
@@ -83,6 +84,17 @@ export function createApp(db: Database, gradingQueue: GradingQueue) {
|
||||
return files ? c.json(files) : c.notFound()
|
||||
})
|
||||
|
||||
// 代码编辑器的语言服务:补全、悬停提示、参数提示、边写边检查
|
||||
const LANGUAGE_REQUESTS = new Set(['complete', 'completionDetail', 'hover', 'signature', 'diagnostics'])
|
||||
app.post('/api/language', async (c) => {
|
||||
const r = await body<{ type: string; session: string; files: unknown; file: string; line: number; column: number; index: number }>(c)
|
||||
if (!LANGUAGE_REQUESTS.has(String(r.type)) || typeof r.session !== 'string') return c.json({ message: '请求格式不对' }, 400)
|
||||
if (r.files !== undefined && !validFiles(r.files)) return c.json({ message: '作品格式不对或太大' }, 400)
|
||||
// 会话按用户区分,不同学生的工程不会混在一起
|
||||
const reply = await languageService.request({ ...r, session: `${c.get('user').id}:${r.session.slice(0, 64)}` })
|
||||
return c.json(reply ?? { type: 'empty' })
|
||||
})
|
||||
|
||||
// 自己的作品:key 如 "sample:p2-t1-LED显示屏"
|
||||
app.get('/api/works/:key', (c) => c.json(getWork(db, c.get('user').id, c.req.param('key'))))
|
||||
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@ import type { ClientMessage, ServerMessage } from '@iot/shared'
|
||||
import { createApp } from './app'
|
||||
import { ensureTeacher, tokenUser } from './auth'
|
||||
import { compileService } from './compile-service'
|
||||
import { languageService } from './language-service'
|
||||
import { config } from './config'
|
||||
import { openDatabase } from './db'
|
||||
import { createGradingQueue } from './grading/queue'
|
||||
@@ -69,5 +70,5 @@ const server = Bun.serve({
|
||||
})
|
||||
|
||||
console.log(`服务器已启动:http://localhost:${server.port}`)
|
||||
await compileService.start()
|
||||
await Promise.all([compileService.start(), languageService.start()])
|
||||
console.log('C# 编译服务已就绪')
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { Subprocess } from 'bun'
|
||||
import { config } from './config'
|
||||
import { readLines } from './runner-process'
|
||||
|
||||
/** 一个请求最多等多久;语言服务忙或卡住时,编辑器不弹补全也不影响写代码 */
|
||||
const TIMEOUT_MS = 10_000
|
||||
|
||||
/**
|
||||
* 常驻语言服务:代码补全、悬停提示、参数提示、边写边检查。全服务器共用一个进程(和编译服务分开),
|
||||
* 请求按编号对应回复。进程意外退出时,挂起的请求失败,下一次请求自动重启。
|
||||
*/
|
||||
class LanguageService {
|
||||
private proc?: Subprocess<'pipe', 'pipe', 'inherit'>
|
||||
private ready?: Promise<void>
|
||||
private nextId = 1
|
||||
private readonly pending = new Map<number, (reply: Record<string, unknown> | null) => void>()
|
||||
|
||||
/** 发一个请求(type、session、files、file、line、column 等原样转给语言服务);超时或出错返回 null */
|
||||
async request(body: Record<string, unknown>): Promise<Record<string, unknown> | null> {
|
||||
await this.start()
|
||||
const id = this.nextId++
|
||||
const reply = new Promise<Record<string, unknown> | null>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id)
|
||||
resolve(null)
|
||||
}, TIMEOUT_MS)
|
||||
this.pending.set(id, (r) => {
|
||||
clearTimeout(timer)
|
||||
resolve(r)
|
||||
})
|
||||
})
|
||||
this.proc!.stdin.write(`${JSON.stringify({ ...body, id })}\n`)
|
||||
this.proc!.stdin.flush()
|
||||
return reply
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.proc?.kill()
|
||||
}
|
||||
|
||||
/** 服务器启动时调用,提前完成加载和预热 */
|
||||
start() {
|
||||
if (this.ready) return this.ready
|
||||
const proc = Bun.spawn(['dotnet', config.runnerDll, 'language-server'], {
|
||||
stdin: 'pipe',
|
||||
stdout: 'pipe',
|
||||
stderr: 'inherit',
|
||||
env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: process.env.HOME ?? '/tmp', DOTNET_CLI_TELEMETRY_OPTOUT: '1', DOTNET_NOLOGO: '1' },
|
||||
})
|
||||
this.proc = proc
|
||||
this.ready = new Promise<void>((resolveReady) => {
|
||||
void readLines(proc.stdout, (line) => {
|
||||
const message = JSON.parse(line) as { type: string; id?: number }
|
||||
if (message.type === 'ready') {
|
||||
resolveReady()
|
||||
return
|
||||
}
|
||||
const resolve = this.pending.get(message.id!)
|
||||
if (!resolve) return
|
||||
this.pending.delete(message.id!)
|
||||
resolve(message.type === 'error' ? null : message)
|
||||
})
|
||||
})
|
||||
proc.exited.then(() => {
|
||||
if (this.proc !== proc) return
|
||||
this.proc = undefined
|
||||
this.ready = undefined
|
||||
for (const resolve of this.pending.values()) resolve(null)
|
||||
this.pending.clear()
|
||||
})
|
||||
return this.ready
|
||||
}
|
||||
}
|
||||
|
||||
export const languageService = new LanguageService()
|
||||
+19
-1
@@ -1,10 +1,11 @@
|
||||
// HTTP 接口测试:内存数据库,直接调用 app.fetch。
|
||||
import { beforeEach, describe, expect, test } from 'bun:test'
|
||||
import { afterAll, beforeEach, describe, expect, test } from 'bun:test'
|
||||
import { createApp } from '../src/app'
|
||||
import { ensureTeacher } from '../src/auth'
|
||||
import { config } from '../src/config'
|
||||
import { openDatabase } from '../src/db'
|
||||
import { createGradingQueue, type GradingQueue } from '../src/grading/queue'
|
||||
import { languageService } from '../src/language-service'
|
||||
import { loadSample } from '../src/samples'
|
||||
|
||||
let app: ReturnType<typeof createApp>
|
||||
@@ -405,3 +406,20 @@ describe('评阅与成绩', () => {
|
||||
expect((await student.get(`/api/teacher/submissions/${submission.id}`)).status).toBe(403)
|
||||
}, 60000)
|
||||
})
|
||||
|
||||
describe('语言服务', () => {
|
||||
afterAll(() => languageService.stop())
|
||||
|
||||
test('代码补全、边写边检查(中文提示);请求格式不对拒绝;没登录不能用', async () => {
|
||||
const t = await teacher()
|
||||
const files = [{ path: 'Program.cs', content: 'using System.Windows.Forms;\nstatic class P\n{\n static void Main()\n {\n var b = new Button();\n b.\n }\n}\n' }]
|
||||
const completions = await t.post('/api/language', { type: 'complete', session: 'tab1', files, file: 'Program.cs', line: 7, column: 11 })
|
||||
expect(completions.body.items.map((i: any) => i.label)).toEqual(expect.arrayContaining(['Text', 'Click', 'Enabled']))
|
||||
|
||||
const check = await t.post('/api/language', { type: 'diagnostics', session: 'tab1', files })
|
||||
expect(check.body.diagnostics).toEqual(expect.arrayContaining([expect.objectContaining({ code: 'CS1002', hint: 'C# 每条语句末尾要有英文分号 ;' })]))
|
||||
|
||||
expect((await t.post('/api/language', { type: 'run', session: 'tab1' })).status).toBe(400)
|
||||
expect((await new Browser().post('/api/language', { type: 'complete', session: 'tab1', files })).status).toBe(401)
|
||||
}, 60000)
|
||||
})
|
||||
Reference in new issue
Block a user