示例#1
0
 dispose() {
   this._providerToFileToMessages.clear();
   this._fileToProviders.clear();
   this._providerToProjectDiagnostics.clear();
   this._fileChanges.complete();
   this._projectChanges.complete();
   this._allChanges.complete();
 }
示例#2
0
  _start(trackCall: boolean, options?: StartOptions): void {
    atom.commands.dispatch(atom.views.getView(atom.workspace), 'nuclide-console:show');

    const shouldRun = this._statuses.getValue() === 'stopped';

    if (shouldRun) {
      if (trackCall) {
        track(this._eventNames.start);
      }

      // If the LogTailer was created with a way of detecting when the source was ready, the initial
      // status is "starting." Otherwise, assume that it's started immediately.
      const initialStatus = this._ready == null ? 'running' : 'starting';
      this._statuses.next(initialStatus);
    }

    // If the user provided an `onRunning` callback, hook it up.
    if (options != null) {
      const {onRunning} = options;
      Observable.merge(
        this._statuses,
        this._messages.ignoreElements(), // For the errors
      )
        .takeWhile(status => status !== 'stopped')
        .first(status => status === 'running')
        .catch(err => {
          // If it's stopped before it starts running, emit a special error.
          if (err.name === 'EmptyError') { throw new ProcessCancelledError(this._name); }
          throw err;
        })
        .mapTo(undefined)
        .subscribe(
          () => { onRunning(); },
          err => { onRunning(err); },
        );
    }

    if (!shouldRun) {
      return;
    }

    if (this._subscription != null) {
      this._subscription.unsubscribe();
    }

    const sub = new Subscription();

    if (this._ready != null) {
      sub.add(
        this._ready
          .takeUntil(this._statuses.filter(status => status !== 'starting'))
          .subscribe(() => { this._statuses.next('running'); })
      );
    }

    sub.add(this._messages.connect());
    this._subscription = sub;
  }
  it('reflects the state of all connections', () => {
    const connectionSubject = new BehaviorSubject([]);
    const propStream = [];
    _observeConnectionState(connectionSubject).subscribe(props =>
      propStream.push(props),
    );

    const heartbeat1 = new MockHeartbeat();
    const connection1: any = {
      getRemoteHostname: () => 'host1',
      getHeartbeat: () => heartbeat1,
    };
    connectionSubject.next([connection1]);

    const heartbeat2 = new MockHeartbeat();
    const connection2: any = {
      getRemoteHostname: () => 'host2',
      getHeartbeat: () => heartbeat2,
    };
    connectionSubject.next([connection1, connection2]);

    heartbeat1.away.next(true);
    heartbeat2.away.next(true);
    heartbeat2.away.next(false);

    connectionSubject.next([]);

    expect(propStream).toEqual([
      {connectionStates: new Map()},
      {connectionStates: new Map([['host1', ConnectionState.CONNECTED]])},
      {
        connectionStates: new Map([
          ['host1', ConnectionState.CONNECTED],
          ['host2', ConnectionState.CONNECTED],
        ]),
      },
      {
        connectionStates: new Map([
          ['host1', ConnectionState.DISCONNECTED],
          ['host2', ConnectionState.CONNECTED],
        ]),
      },
      {
        connectionStates: new Map([
          ['host1', ConnectionState.DISCONNECTED],
          ['host2', ConnectionState.DISCONNECTED],
        ]),
      },
      {
        connectionStates: new Map([
          ['host1', ConnectionState.DISCONNECTED],
          ['host2', ConnectionState.CONNECTED],
        ]),
      },
      {connectionStates: new Map()},
    ]);
  });
示例#4
0
 setHomeFragments(homeFragments: HomeFragments): UniversalDisposable {
   this._allHomeFragmentsStream.next(
     this._allHomeFragmentsStream.getValue().add(homeFragments),
   );
   return new UniversalDisposable(() => {
     this._allHomeFragmentsStream.next(
       this._allHomeFragmentsStream.getValue().remove(homeFragments),
     );
   });
 }
示例#5
0
 /**
  * Returns an observable of evaluation results for a given expression.
  * Resources are automatically cleaned up once all subscribers of an expression have unsubscribed.
  */
 evaluateWatchExpression(expression: Expression): Rx.Observable<?EvaluationResult> {
   if (this._watchExpressions.has(expression)) {
     const cachedResult = this._watchExpressions.get(expression);
     invariant(cachedResult);
     return cachedResult;
   }
   const subject = new Rx.BehaviorSubject();
   this._requestExpressionEvaluation(expression, subject);
   this._watchExpressions.set(expression, subject);
   // Expose an observable rather than the raw subject.
   return subject.asObservable();
 }
示例#6
0
 /** Ping the server until it leaves the current state */
 async _pingServer(tries?: number = 5): Promise<void> {
   const fromState = this._serverStatus.getValue();
   let stateChanged = false;
   this._serverStatus.filter(newState => newState !== fromState).first().subscribe(() => {
     stateChanged = true;
   });
   for (let i = 0; !stateChanged && i < tries; i++) {
     /* eslint-disable babel/no-await-in-loop */
     await this._rawExecFlow(['status']).catch(() => null);
     // Wait 1 second
     await Observable.of(null).delay(1000).toPromise();
     /* eslint-enable babel/no-await-in-loop */
   }
 }
示例#7
0
  _stop(trackCall: boolean = true): void {
    if (this._subscription != null) {
      this._subscription.unsubscribe();
    }

    if (this._statuses.getValue() === 'stopped') {
      return;
    }
    if (trackCall) {
      track(this._eventNames.stop);
    }

    this._statuses.next('stopped');
  }
示例#8
0
const createStore = (reducer, preloadedState)=>{
    const eventSource = new Rx.BehaviorSubject(preloadedState);

    const scanned = eventSource
        .scan(reducer)
        .distinctUntilChanged();

    return {
        dispatch(action) {
            eventSource.next(action);
        },
        subscribe(listener) {
            scanned.subscribe(listener);
        }
    }
};
示例#9
0
 return new Observable(function PluginObservable(observer) {
     let firstTime = true;
     return subject.subscribe(plugins => {
         let result = plugins.filter(plugin => {
             let {name, filter, enabled, targetType} = plugin,
                 matchesName = overSome(
                     isUndefined,
                     partial(isEqual, name)
                 ),
                 matchesEnabled = overSome(
                     isUndefined,
                     partial(isEqual, enabled)
                 );
             return matchesName(criteria.name) &&
                 matchesEnabled(criteria.enabled) &&
                 is(criteria.baseType)(plugin) &&
                 is(targetType)(criteria.targetType) &&
                 isFilterMatch(filter, criteria.filter);
         });
         if (firstTime && isEmpty(result)) {
             return; // don't publish the initial empty array
         }
         firstTime = false;
         result.sort((a, b) => a.index - b.index);
         result.toDAG = () => new DAG(...plugins);
         observer.next(result);
     });
 }).distinctUntilChanged(identity, isEqualWith);
示例#10
0
 getItems(): Array<Viewable> {
   const items = [];
   for (const pane of this._panes.getValue()) {
     items.push(...pane.getItems());
   }
   return items;
 }
示例#11
0
 dispose(): void {
   this._serverStatus.complete();
   if (this._startedServer && getStopFlowOnExit()) {
     // The default, SIGTERM, does not reliably kill the flow servers.
     this._startedServer.kill('SIGKILL');
   }
 }
示例#12
0
  constructor() {
    this._emitter = new Emitter();
    this._currentFilePath = '';
    this._projectRoot = new BehaviorSubject();
    this._isHHVMProject = null;
    this._debugMode = 'webserver';
    this._filePathsToScriptCommand = new Map();

    const onDidChange = this._onDidChangeActivePaneItem.bind(this);
    this._disposables = new UniversalDisposable(
      this._projectRoot
        .do(() => {
          // Set the project type to a "loading" state.
          this._isHHVMProject = null;
          this._emitter.emit('change');
        })
        .switchMap(root => this._isFileHHVMProject(root))
        .subscribe(isHHVM => {
          this._isHHVMProject = isHHVM;
          this._emitter.emit('change');
        }),
      atom.workspace.onDidStopChangingActivePaneItem(onDidChange),
    );
    onDidChange();
  }
示例#13
0
 return new _rxjs.Observable(function PluginObservable(observer) {
     var firstTime = true;
     return subject.subscribe(function (plugins) {
         var result = plugins.filter(function (plugin) {
             var name = plugin.name;
             var filter = plugin.filter;
             var enabled = plugin.enabled;
             var targetType = plugin.targetType;
             var matchesName = (0, _overSome3.default)(_isUndefined3.default, (0, _partial3.default)(_isEqual3.default, name));
             var matchesEnabled = (0, _overSome3.default)(_isUndefined3.default, (0, _partial3.default)(_isEqual3.default, enabled));
             return matchesName(criteria.name) && matchesEnabled(criteria.enabled) && (0, _common.is)(criteria.baseType)(plugin) && (0, _common.is)(targetType)(criteria.targetType) && (0, _common.isFilterMatch)(filter, criteria.filter);
         });
         if (firstTime && (0, _isEmpty3.default)(result)) {
             return; // don't publish the initial empty array
         }
         firstTime = false;
         result.sort(function (a, b) {
             return a.index - b.index;
         });
         result.toDAG = function () {
             return new (Function.prototype.bind.apply(_DAG.DAG, [null].concat(_toConsumableArray(plugins))))();
         };
         observer.next(result);
     });
 }).distinctUntilChanged(_identity3.default, _isEqualWith3.default);
    onChange(value){

      this._refreshSubunsub();
      this.querySubject.next(value); // må gjøre så category funker, eget parameter eller objek
      this.setState({
            searchValue: value
      })
    }
示例#15
0
 serialize(): ?SerializedBookShelfState {
   try {
     return serializeBookShelfState(this._states.getValue());
   } catch (error) {
     getLogger().error('failed to serialize nuclide-bookshelf state', error);
     return null;
   }
 }
 this.refreshSub = this.refreshTimer.subscribe((a) => {
   console.log(a);
   this.props.imService.search({name: this.querySubject.getValue()}).subscribe((services) => {
     this.setState({
       services: services
     });
   });
 });
示例#17
0
 const waitForPhase = (phaseType: string) => {
   return currentState
     .filter(s => {
       return s.type === 'open' && s.phase.type === phaseType;
     })
     .first()
     .toPromise();
 };
示例#18
0
 /**
  * @return The current Hg bookmark.
  */
 getShortHead(filePath?: NuclideUri): string {
   return (
     this._bookmarks
       .getValue()
       .bookmarks.filter(bookmark => bookmark.active)
       .map(bookmark => bookmark.bookmark)[0] || ''
   );
 }
示例#19
0
 destroyItem(item: Object): void {
   for (const pane of this._panes.getValue()) {
     for (const it of pane.getItems()) {
       if (it === item) {
         pane.destroyItem(it);
       }
     }
   }
 }
  constructor(
    diagnostics: Observable<Array<DiagnosticMessage>>,
    showTracesStream: Observable<boolean>,
    onShowTracesChange: (showTraces: boolean) => void,
    disableLinter: () => void,
    warnAboutLinterStream: Observable<boolean>,
    initialfilterByActiveTextEditor: boolean,
    onFilterByActiveTextEditorChange: (
      filterByActiveTextEditor: boolean,
    ) => void,
  ) {
    // TODO(T17495163)
    this._visibilitySubscription = observePaneItemVisibility(
      this,
    ).subscribe(visible => {
      this.didChangeVisibility(visible);
    });
    this._visibility = new BehaviorSubject(true);

    this._visibilitySubscription = this._visibility
      .debounceTime(1000)
      .distinctUntilChanged()
      .filter(Boolean)
      .subscribe(() => {
        analytics.track('diagnostics-show-table');
      });

    // A stream that contains the props, but is "muted" when the panel's not visible.
    this._props = toggle(
      getPropsStream(
        diagnostics,
        warnAboutLinterStream,
        showTracesStream,
        onShowTracesChange,
        disableLinter,
        initialfilterByActiveTextEditor,
        onFilterByActiveTextEditorChange,
      )
        .publishReplay(1)
        .refCount(),
      this._visibility.distinctUntilChanged(),
    );
  }
示例#21
0
 dispose(): void {
   for (const [filePath, buffer] of this._buffers.entries()) {
     this._emitClose(filePath, buffer);
     buffer.destroy();
   }
   this._buffers.clear();
   this._resources.dispose();
   this._fileEvents.complete();
   this._directoryEvents.complete();
 }
示例#22
0
  constructor(root: string) {
    this._serverStatus = new BehaviorSubject(ServerStatus.UNKNOWN);
    this._root = root;

    this._serverStatus.filter(x => x === ServerStatus.NOT_RUNNING).subscribe(() => {
      this._startFlowServer();
      this._pingServer();
    });
    function isBusyOrInit(status: ServerStatusType): boolean {
      return status === ServerStatus.BUSY || status === ServerStatus.INIT;
    }
    this._serverStatus.filter(isBusyOrInit).subscribe(() => {
      this._pingServer();
    });

    this._serverStatus.filter(status => status === ServerStatus.FAILED).subscribe(() => {
      track('flow-server-failed');
    });
  }
示例#23
0
 /**
  * Resolves when the server is ready or the request times out, as indicated by the result of the
  * returned Promise.
  */
 _serverIsReady(): Promise<boolean> {
   return this._serverStatus
     .filter(x => x === ServerStatus.READY)
     .map(() => true)
     .race(Observable.of(false).delay(SERVER_READY_TIMEOUT_MS))
     // If the stream is completed timeout will not return its default value and we will see an
     // EmptyError. So, provide a defaultValue here so the promise resolves.
     .first(null, null, false)
     .toPromise();
 }
示例#24
0
 _updateServerStatus(result: ?process$asyncExecuteRet): void {
   let status;
   if (result == null) {
     status = ServerStatus.NOT_INSTALLED;
   } else {
     switch (result.exitCode) {
       case FLOW_RETURN_CODES.ok:
         // falls through
       case FLOW_RETURN_CODES.typeError:
         status = ServerStatus.READY;
         break;
       case FLOW_RETURN_CODES.serverInitializing:
         status = ServerStatus.INIT;
         break;
       case FLOW_RETURN_CODES.noServerRunning:
         status = ServerStatus.NOT_RUNNING;
         break;
       case FLOW_RETURN_CODES.outOfRetries:
         status = ServerStatus.BUSY;
         break;
       case FLOW_RETURN_CODES.buildIdMismatch:
         // If the version doesn't match, the server is automatically killed and the client
         // returns 9.
         logger.info('Killed flow server with incorrect version in', this._root);
         status = ServerStatus.NOT_RUNNING;
         break;
       case FLOW_RETURN_CODES.unexpectedArgument:
         // If we issued an unexpected argument we have learned nothing about the state of the Flow
         // server. So, don't update.
         return;
       default:
         logger.error(`Unknown return code from Flow: ${result.exitCode}`);
         status = ServerStatus.UNKNOWN;
     }
   }
   invariant(status != null);
   const currentStatus = this._serverStatus.getValue();
   // Avoid duplicate updates and avoid moving the status away from FAILED, to let any existing
   // work die out when the server fails.
   if (status !== currentStatus && currentStatus !== ServerStatus.FAILED) {
     this._serverStatus.next(status);
   }
 }
示例#25
0
 Endpoint.prototype.query = function (query) {
     var _this = this;
     var result = new rxjs_1.BehaviorSubject([]);
     switch (this.endpointType.method) {
         case EndpointType_1.HTTPMethod.GET:
             var qs = this.url + '?';
             for (var _i = 0, _a = this.endpointType.parameters; _i < _a.length; _i++) {
                 var p = _a[_i];
                 qs += encodeURIComponent(p.name) + '=' + encodeURIComponent(p.value) + '&';
             }
             var headers = new http_1.Headers({});
             qs += encodeURIComponent(this.endpointType.queryParameter) + '=' + encodeURIComponent(query);
             var options = new http_1.RequestOptions({
                 headers: headers
             });
             console.log('HTTP GET ' + qs);
             Endpoint.http
                 .get(qs, options)
                 .map(function (res) {
                 console.log('Res: ', res);
                 if (_this.endpointType.contentType === EndpointType_1.ContentTypes.JSON ||
                     _this.endpointType.contentType === EndpointType_1.ContentTypes.sparqlJSON ||
                     _this.endpointType.contentType === EndpointType_1.ContentTypes.sparqlJSONP) {
                     return _this.endpointType.adapter(res.json());
                 }
                 return _this.endpointType.adapter(res);
             })
                 .subscribe(function (res) {
                 console.log('endpoint query results', res);
                 result.next(res);
             }, function (err) {
                 console.log(err);
             });
             break;
         case EndpointType_1.HTTPMethod.POST:
             this.logger.error('POST is not implemented yet');
             break;
         default:
             this.logger.error(this.endpointType.method + ' is not implemented yet');
     }
     return result.asObservable();
 };
示例#26
0
 itemIsVisible(item: Viewable): boolean {
   if (!this.state.active) {
     return false;
   }
   for (const pane of this._panes.getValue()) {
     if (item === pane.getActiveItem()) {
       return true;
     }
   }
   return false;
 }
示例#27
0
        const toggleClusterState = () => {
            this._inProgressSubject.next(true);

            return this.agentMgr.toggleClusterState()
                .then(() => this._inProgressSubject.next(false))
                .catch((err) => {
                    this._inProgressSubject.next(false);

                    this.Messages.showError('Failed to toggle cluster state: ', err);
                });
        };
示例#28
0
            (function () {
                var changes = new _rxjs.BehaviorSubject(_this);
                var onChangesCompleted = _root.onChangesCompleted;

                _root.onChangesCompleted = function () {
                    if (onChangesCompleted) {
                        onChangesCompleted.call(this);
                    }
                    changes.next(this);
                };
                _root.changes = changes;
            })();
示例#29
0
 /**
  * Returns null if Flow cannot be found.
  */
 async execFlow(
   args: Array<any>,
   options: Object,
   waitForServer?: boolean = false,
   suppressErrors?: boolean = false,
 ): Promise<?process$asyncExecuteRet> {
   const maxRetries = waitForServer ? EXEC_FLOW_RETRIES : 0;
   if (this._serverStatus.getValue() === ServerStatus.FAILED) {
     return null;
   }
   for (let i = 0; ; i++) {
     try {
       const result = await this._rawExecFlow( // eslint-disable-line babel/no-await-in-loop
         args,
         options,
       );
       return result;
     } catch (e) {
       const couldRetry = [ServerStatus.NOT_RUNNING, ServerStatus.INIT, ServerStatus.BUSY]
         .indexOf(this._serverStatus.getValue()) !== -1;
       if (i < maxRetries && couldRetry) {
         await this._serverIsReady(); // eslint-disable-line babel/no-await-in-loop
         // Then try again.
       } else {
         // If it couldn't retry, it means there was a legitimate error. If it could retry, we
         // don't want to log because it just means the server is busy and we don't want to wait.
         if (!couldRetry && !suppressErrors) {
           // not sure what happened, but we'll let the caller deal with it
           logger.error(`Flow failed: flow ${args.join(' ')}. Error: ${JSON.stringify(e)}`);
         }
         throw e;
       }
       // try again
     }
   }
   // otherwise flow complains
   // eslint-disable-next-line no-unreachable
   return null;
 }
示例#30
0
 serverProcess.on('exit', (code, signal) => {
   // We only want to blacklist this root if the Flow processes
   // actually failed, rather than being killed manually. It seems that
   // if they are killed, the code is null and the signal is 'SIGTERM'.
   // In the Flow crashes I have observed, the code is 2 and the signal
   // is null. So, let's blacklist conservatively for now and we can
   // add cases later if we observe Flow crashes that do not fit this
   // pattern.
   if (code === 2 && signal === null) {
     logger.error('Flow server unexpectedly exited', this._root);
     this._serverStatus.next(ServerStatus.FAILED);
   }
 });