aboutsummaryrefslogtreecommitdiffstats
path: root/language-web/src/main/js/editor/XtextClient.ts
blob: 1c6c0ae66450882396dc126c616cb5ca08b45793 (plain) (blame)
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import type { Diagnostic } from '@codemirror/lint';
import {
  ChangeDesc,
  ChangeSet,
  Transaction,
} from '@codemirror/state';
import { nanoid } from 'nanoid';

import type { EditorStore } from './EditorStore';
import { getLogger } from '../logging';
import {
  isDocumentStateResult,
  isServiceConflictResult,
  isValidationResult,
} from './xtextServiceResults';
import { XtextWebSocketClient } from './XtextWebSocketClient';

const UPDATE_TIMEOUT_MS = 300;

const log = getLogger('XtextClient');

enum UpdateAction {
  ForceReconnect,

  FullTextUpdate,
}

export class XtextClient {
  resourceName: string;

  webSocketClient: XtextWebSocketClient;

  xtextStateId: string | null = null;

  pendingUpdate: ChangeDesc | null;

  dirtyChanges: ChangeDesc;

  updateTimeout: NodeJS.Timeout | null = null;

  store: EditorStore;

  constructor(store: EditorStore) {
    this.resourceName = `${nanoid(7)}.problem`;
    this.pendingUpdate = null;
    this.store = store;
    this.dirtyChanges = this.newEmptyChangeDesc();
    this.webSocketClient = new XtextWebSocketClient(
      () => {
        this.updateFullText().catch((error) => {
          log.error('Unexpected error during initial update', error);
        });
      },
      (resource, stateId, service, push) => {
        this.onPush(resource, stateId, service, push).catch((error) => {
          log.error('Unexected error during push message handling', error);
        });
      },
    );
  }

  onTransaction(transaction: Transaction): void {
    const { changes } = transaction;
    if (!changes.empty) {
      this.webSocketClient.ensureOpen();
      this.dirtyChanges = this.dirtyChanges.composeDesc(changes.desc);
      this.scheduleUpdate();
    }
  }

  private async onPush(resource: string, stateId: string, service: string, push: unknown) {
    if (resource !== this.resourceName) {
      log.error('Unknown resource name: expected:', this.resourceName, 'got:', resource);
      return;
    }
    if (stateId !== this.xtextStateId) {
      log.error('Unexpected xtext state id: expected:', this.xtextStateId, 'got:', resource);
      await this.updateFullText();
    }
    switch (service) {
      case 'validate':
        this.onValidate(push);
        return;
      case 'highlight':
        // TODO
        return;
      default:
        log.error('Unknown push service:', service);
        break;
    }
  }

  private onValidate(push: unknown) {
    if (!isValidationResult(push)) {
      log.error('Invalid validation result', push);
      return;
    }
    const allChanges = this.computeChangesSinceLastUpdate();
    const diagnostics: Diagnostic[] = [];
    push.issues.forEach((issue) => {
      if (issue.severity === 'ignore') {
        return;
      }
      diagnostics.push({
        from: allChanges.mapPos(issue.offset),
        to: allChanges.mapPos(issue.offset + issue.length),
        severity: issue.severity,
        message: issue.description,
      });
    });
    this.store.updateDiagnostics(diagnostics);
  }

  private computeChangesSinceLastUpdate() {
    if (this.pendingUpdate === null) {
      return this.dirtyChanges;
    }
    return this.pendingUpdate.composeDesc(this.dirtyChanges);
  }

  private scheduleUpdate() {
    if (this.updateTimeout !== null) {
      clearTimeout(this.updateTimeout);
    }
    this.updateTimeout = setTimeout(() => {
      this.updateTimeout = null;
      if (!this.webSocketClient.isOpen || this.dirtyChanges.empty) {
        return;
      }
      if (!this.pendingUpdate) {
        this.updateDeltaText().catch((error) => {
          log.error('Unexpected error during scheduled update', error);
        });
      }
      this.scheduleUpdate();
    }, UPDATE_TIMEOUT_MS);
  }

  private newEmptyChangeDesc() {
    const changeSet = ChangeSet.of([], this.store.state.doc.length);
    return changeSet.desc;
  }

  private async updateFullText() {
    await this.withUpdate(async () => {
      const result = await this.webSocketClient.send({
        resource: this.resourceName,
        serviceType: 'update',
        fullText: this.store.state.doc.sliceString(0),
      });
      if (isDocumentStateResult(result)) {
        return result.stateId;
      }
      if (isServiceConflictResult(result)) {
        log.error('Full text update conflict:', result.conflict);
        if (result.conflict === 'canceled') {
          return UpdateAction.FullTextUpdate;
        }
        return UpdateAction.ForceReconnect;
      }
      log.error('Unexpected full text update result:', result);
      return UpdateAction.ForceReconnect;
    });
  }

  private async updateDeltaText() {
    if (this.xtextStateId === null) {
      await this.updateFullText();
      return;
    }
    const delta = this.computeDelta();
    log.debug('Editor delta', delta);
    await this.withUpdate(async () => {
      const result = await this.webSocketClient.send({
        resource: this.resourceName,
        serviceType: 'update',
        requiredStateId: this.xtextStateId,
        ...delta,
      });
      if (isDocumentStateResult(result)) {
        return result.stateId;
      }
      if (isServiceConflictResult(result)) {
        log.error('Delta text update conflict:', result.conflict);
        return UpdateAction.FullTextUpdate;
      }
      log.error('Unexpected delta text update result:', result);
      return UpdateAction.ForceReconnect;
    });
  }

  private computeDelta() {
    if (this.dirtyChanges.empty) {
      return {};
    }
    let minFromA = Number.MAX_SAFE_INTEGER;
    let maxToA = 0;
    let minFromB = Number.MAX_SAFE_INTEGER;
    let maxToB = 0;
    this.dirtyChanges.iterChangedRanges((fromA, toA, fromB, toB) => {
      minFromA = Math.min(minFromA, fromA);
      maxToA = Math.max(maxToA, toA);
      minFromB = Math.min(minFromB, fromB);
      maxToB = Math.max(maxToB, toB);
    });
    return {
      deltaOffset: minFromA,
      deltaReplaceLength: maxToA - minFromA,
      deltaText: this.store.state.doc.sliceString(minFromB, maxToB),
    };
  }

  private async withUpdate(callback: () => Promise<string | UpdateAction>) {
    if (this.pendingUpdate !== null) {
      log.error('Another update is pending, will not perform update');
      return;
    }
    this.pendingUpdate = this.dirtyChanges;
    this.dirtyChanges = this.newEmptyChangeDesc();
    let newStateId: string | UpdateAction = UpdateAction.ForceReconnect;
    try {
      newStateId = await callback();
    } catch (error) {
      log.error('Error while updating state', error);
    } finally {
      if (typeof newStateId === 'string') {
        this.xtextStateId = newStateId;
        this.pendingUpdate = null;
      } else {
        this.dirtyChanges = this.pendingUpdate.composeDesc(this.dirtyChanges);
        this.pendingUpdate = null;
        switch (newStateId) {
          case UpdateAction.ForceReconnect:
            this.webSocketClient.forceReconnectDueToError();
            break;
          case UpdateAction.FullTextUpdate:
            await this.updateFullText();
            break;
        }
      }
    }
  }
}