File size: 5,762 Bytes
84c1942
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io from 'socket.io-client';
import { dispatch } from 'codesandbox-api';
import _debug from 'debug';
import axios from 'axios';

import { IExecutor, IFiles, ISetupParams } from './executor';

const debug = _debug('executors:server');

function sseTerminalMessage(msg: string) {
  dispatch({
    type: 'terminal:message',
    data: `> Sandbox Container: ${msg}\n\r`,
  });
}

/**
 * Find the changes from the last run, we only work with saved code here.
 */
const getDiff = (oldFiles: IFiles, newFiles: IFiles) => {
  const diff: IFiles = {};

  Object.keys(newFiles)
    .filter(p => {
      const newSavedCode = newFiles[p].savedCode || newFiles[p].code;
      if (oldFiles[p]) {
        const oldSavedCode = oldFiles[p].savedCode || oldFiles[p].code;
        if (oldSavedCode !== newSavedCode) {
          return true;
        }
      } else {
        return true;
      }

      return false;
    })
    .forEach(p => {
      diff[p] = {
        code: newFiles[p].code,
        path: newFiles[p].path,
        savedCode: newFiles[p].savedCode,
        isBinary: newFiles[p].isBinary,
      };
    });

  Object.keys(oldFiles).forEach(p => {
    if (!newFiles[p]) {
      diff[p] = {
        path: oldFiles[p].path,
        isBinary: false,
        code: null,
        savedCode: null,
      };
    }
  });

  return diff;
};

const MAX_SSE_AGE = 24 * 60 * 60 * 1000; // 1 day
const tick = () => new Promise<void>(r => setTimeout(() => r(), 0));

export class ServerExecutor implements IExecutor {
  socket?: SocketIOClient.Socket;
  connectTimeout: number | null = null;
  token: Promise<string | undefined>;
  host?: string;
  sandboxId?: string;
  lastSent?: IFiles;

  constructor() {
    this.token = this.retrieveSSEToken();
  }

  private async initializeSocket() {
    if (!this.sandboxId) {
      throw new Error('initializeSocket: sandboxId is not defined');
    }
    const usedHost = this.host || 'https://codesandbox.io';
    const sseLbHost = usedHost.replace('https://', 'https://sse-lb.');
    const res = await axios.get(`${sseLbHost}/api/cluster/${this.sandboxId}`);
    const sseHost = res.data.hostname;

    this.socket = io(sseHost, {
      autoConnect: false,
      transports: ['websocket', 'polling'],
    });
  }

  async initialize({ sandboxId, files, host }: ISetupParams) {
    if (this.sandboxId === sandboxId && this.socket?.connected) {
      return;
    }

    this.host = host;
    this.sandboxId = sandboxId;
    this.lastSent = files;

    await this.dispose();
    await tick();

    await this.initializeSocket();
  }

  public async setup() {
    debug('Setting up server executor...');

    return this.openSocket();
  }

  public async dispose() {
    if (this.socket) {
      this.socket.removeAllListeners();
      this.socket.close();
    }
  }

  public updateFiles(newFiles: IFiles) {
    const changedFiles = this.lastSent
      ? getDiff(this.lastSent, newFiles)
      : newFiles;

    this.lastSent = newFiles;

    if (Object.keys(changedFiles).length > 0 && this.socket) {
      debug(
        Object.keys(changedFiles).length + ' files changed, sending to SSE.'
      );
      debug(changedFiles);
      this.socket.emit('sandbox:update', changedFiles);
    }
  }

  public emit(event: string, data?: any) {
    if (this.socket) {
      this.socket.emit(event, data);
    }
  }

  public on(event: string, listener: (data: any) => void) {
    if (this.socket) {
      this.socket.on(event, listener);
    }
  }

  private openSocket() {
    if (this.socket?.connected) {
      return Promise.resolve();
    }

    return new Promise<void>((resolve, reject) => {
      this.socket!.on('connect', async () => {
        try {
          if (this.connectTimeout) {
            clearTimeout(this.connectTimeout);
            this.connectTimeout = null;
          }

          await this.startSandbox();

          resolve();
        } catch (e) {
          debug('Error connecting to SSE manager: ', e);
          reject(e);
        }
      });

      this.socket!.on('sandbox:start', () => {
        sseTerminalMessage(`Sandbox ${this.sandboxId} started`);
      });

      if (this.socket) {
        this.socket.open();
      }
    });
  }

  private async startSandbox() {
    const token = await this.token;
    if (this.socket) {
      this.socket.emit('sandbox', { id: this.sandboxId, token });
    }

    debug('Connected to sse manager, sending start signal...');
    sseTerminalMessage(`Starting sandbox ${this.sandboxId}...`);
    if (this.socket) {
      this.socket.emit('sandbox:start');
    }
  }

  private async retrieveSSEToken() {
    debug('Retrieving SSE token...');

    const existingKey = localStorage.getItem('sse');
    const currentTime = new Date().getTime();

    if (existingKey) {
      const parsedKey = JSON.parse(existingKey);
      if (parsedKey.key && currentTime - parsedKey.timestamp < MAX_SSE_AGE) {
        debug('Retrieved SSE token from cache');
        return parsedKey.key as string;
      }
    }

    const devJwt = localStorage.getItem('devJwt');

    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
    };
    if (devJwt) {
      headers.Authorization = `Bearer ${devJwt}`;
    }

    return fetch('/api/v1/users/current_user/sse', {
      method: 'POST',
      headers,
    })
      .then(x => x.json())
      .then(result => result.jwt)
      .then((token: string) => {
        debug('Retrieved SSE token from API');
        localStorage.setItem(
          'sse',
          JSON.stringify({
            key: token,
            timestamp: currentTime,
          })
        );

        return token;
      })
      .catch(() => {
        debug('Not signed in, returning undefined');
        return undefined;
      });
  }
}