-
Notifications
You must be signed in to change notification settings - Fork 39.3k
Expand file tree
/
Copy pathspeculativeRequestManager.ts
More file actions
194 lines (168 loc) · 7.05 KB
/
speculativeRequestManager.ts
File metadata and controls
194 lines (168 loc) · 7.05 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DocumentId } from '../../../platform/inlineEdits/common/dataTypes/documentId';
import { StatelessNextEditRequest } from '../../../platform/inlineEdits/common/statelessNextEditProvider';
import { ILogger } from '../../../platform/log/common/logService';
import { Disposable } from '../../../util/vs/base/common/lifecycle';
import { CachedOrRebasedEdit } from './nextEditCache';
import { NextEditResult } from './nextEditResult';
/**
* Reasons why a speculative request was cancelled. Recorded on the request's
* log context so each cancellation has an attributable cause.
*/
export const enum SpeculativeCancelReason {
/** The originating suggestion was rejected by the user. */
Rejected = 'rejected',
/** The originating suggestion was dismissed without being superseded. */
IgnoredDismissed = 'ignoredDismissed',
/** A new fetch is starting whose `(docId, postEditContent)` doesn't match. */
Superseded = 'superseded',
/** A newer speculative is being installed in this slot. */
Replaced = 'replaced',
/** The user's edits moved off the type-through trajectory toward `postEditContent`. */
DivergedFromTrajectoryForm = 'divergedFromTrajectoryForm',
DivergedFromTrajectoryPrefix = 'divergedFromTrajectoryPrefix',
DivergedFromTrajectoryMiddle = 'divergedFromTrajectoryMiddle',
DivergedFromTrajectorySuffix = 'divergedFromTrajectorySuffix',
/** `clearCache()` was invoked. */
CacheCleared = 'cacheCleared',
/** The target document was removed from the workspace. */
DocumentClosed = 'documentClosed',
/** The provider was disposed. */
Disposed = 'disposed',
}
export interface SpeculativePendingRequest {
readonly request: StatelessNextEditRequest<CachedOrRebasedEdit>;
readonly docId: DocumentId;
readonly postEditContent: string;
/** preEditDocument[0..editStart] — the doc text before the edit window. */
readonly trajectoryPrefix: string;
/** preEditDocument[editEnd..] — the doc text after the edit window. */
readonly trajectorySuffix: string;
/** The replacement text the user would type to reach `postEditContent`. */
readonly trajectoryNewText: string;
}
export interface ScheduledSpeculativeRequest {
readonly suggestion: NextEditResult;
readonly headerRequestId: string;
}
/**
* Owns the lifecycle of NES speculative requests:
*
* - the in-flight `pending` speculative (the bet on a specific post-accept document state)
* - the `scheduled` speculative deferred until its originating stream completes
*
* Centralizes cancellation with typed reasons so every triggered cancellation
* (reject, supersede, doc-close, trajectory divergence, dispose, ...) goes through
* one path and is logged on the request's log context.
*/
export class SpeculativeRequestManager extends Disposable {
private _pending: SpeculativePendingRequest | null = null;
private _scheduled: ScheduledSpeculativeRequest | null = null;
constructor(private readonly _logger: ILogger) {
super();
}
get pending(): SpeculativePendingRequest | null {
return this._pending;
}
/** Replaces the current pending speculative; cancels the prior one as `Replaced`. */
setPending(req: SpeculativePendingRequest): void {
if (this._pending && this._pending.request !== req.request) {
this._cancelPending(SpeculativeCancelReason.Replaced);
}
this._pending = req;
}
schedule(s: ScheduledSpeculativeRequest): void {
this._scheduled = s;
}
clearScheduled(): void {
this._scheduled = null;
}
/**
* Removes and returns the scheduled entry iff its `headerRequestId` matches.
* Used by the streaming path so that each stream only ever consumes its own
* schedule, never another stream's.
*/
consumeScheduled(headerRequestId: string): ScheduledSpeculativeRequest | null {
if (this._scheduled?.headerRequestId !== headerRequestId) {
return null;
}
const s = this._scheduled;
this._scheduled = null;
return s;
}
cancelAll(reason: SpeculativeCancelReason): void {
this._scheduled = null;
this._cancelPending(reason);
}
/** Cancels the pending speculative iff `(docId, postEditContent)` doesn't match. */
cancelIfMismatch(docId: DocumentId, postEditContent: string, reason: SpeculativeCancelReason): void {
if (this._pending && (this._pending.docId !== docId || this._pending.postEditContent !== postEditContent)) {
this._cancelPending(reason);
}
}
/** Cancels the pending and clears any scheduled targeting this document. */
onDocumentClosed(docId: DocumentId): void {
if (this._scheduled?.suggestion.result?.targetDocumentId === docId) {
this._scheduled = null;
}
if (this._pending?.docId === docId) {
this._cancelPending(SpeculativeCancelReason.DocumentClosed);
}
}
/**
* Trajectory check. The pending speculative is alive iff the current document
* value is a *type-through prefix* toward the speculative's `postEditContent`:
*
* cur === trajectoryPrefix + middle + trajectorySuffix
* where middle is some prefix of trajectoryNewText
*
* If not, the user's edits cannot reach `postEditContent` via continued typing
* and the speculative will never be consumed — cancel now.
*/
onActiveDocumentChanged(docId: DocumentId, currentDocValue: string): void {
const p = this._pending;
if (!p || p.docId !== docId) {
return;
}
// Cheap structural failure: doc shorter than the unedited frame.
if (currentDocValue.length < p.trajectoryPrefix.length + p.trajectorySuffix.length) {
this._cancelPending(SpeculativeCancelReason.DivergedFromTrajectoryForm);
return;
}
if (!currentDocValue.startsWith(p.trajectoryPrefix)) {
this._cancelPending(SpeculativeCancelReason.DivergedFromTrajectoryPrefix);
return;
}
if (!currentDocValue.endsWith(p.trajectorySuffix)) {
this._cancelPending(SpeculativeCancelReason.DivergedFromTrajectorySuffix);
return;
}
const middle = currentDocValue.slice(p.trajectoryPrefix.length, currentDocValue.length - p.trajectorySuffix.length);
if (!p.trajectoryNewText.startsWith(middle)) {
this._cancelPending(SpeculativeCancelReason.DivergedFromTrajectoryMiddle);
}
}
private _cancelPending(reason: SpeculativeCancelReason): void {
const p = this._pending;
if (!p) {
return;
}
this._pending = null;
const headerRequestId = p.request.headerRequestId;
this._logger.trace(`cancelling speculative request: ${reason} (headerRequestId=${headerRequestId})`);
p.request.logContext.addLog(`speculative request cancelled: ${reason}`);
const cts = p.request.cancellationTokenSource;
cts.cancel();
// Dispose to release the cancel-event listeners that the in-flight
// provider call hooked onto the token. Safe even though the runner may
// observe cancellation asynchronously — `cancel()` already fired the event.
cts.dispose();
}
override dispose(): void {
this.cancelAll(SpeculativeCancelReason.Disposed);
super.dispose();
}
}