Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ui/utils] share sync subscribe logic #23341

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions src/ui/public/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import angular from 'angular';
import chrome from '../chrome';
import { isPlainObject } from 'lodash';
import { uiModules } from '../modules';
import { subscribe } from '../utils/subscribe';

const module = uiModules.get('kibana/config');

Expand Down Expand Up @@ -59,20 +60,11 @@ module.service(`config`, function ($rootScope, Promise) {
//* angular specific methods *
//////////////////////////////

const subscription = uiSettings.getUpdate$().subscribe(({ key, newValue, oldValue }) => {
const emit = () => {
const subscription = subscribe($rootScope, uiSettings.getUpdate$(), {
next: ({ key, newValue, oldValue }) => {
$rootScope.$broadcast('change:config', newValue, oldValue, key, this);
$rootScope.$broadcast(`change:config.${key}`, newValue, oldValue, key, this);
};

// this is terrible, but necessary to emulate the same API
// that the `config` service had before where changes were
// emitted to scopes synchronously. All methods that don't
// require knowing if we are currently in a digest cycle are
// async and would deliver events too late for several usecases
//
// If you copy this code elsewhere you better have a good reason :)
$rootScope.$$phase ? emit() : $rootScope.$apply(emit);
}
});
$rootScope.$on('$destroy', () => subscription.unsubscribe());

Expand Down
143 changes: 143 additions & 0 deletions src/ui/public/utils/subscribe.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

const mockFatalError = jest.fn();
jest.mock('ui/notify/fatal_error', () => ({
fatalError: mockFatalError,
}));

import * as Rx from 'rxjs';
import { subscribe } from './subscribe';

let $rootScope: Scope;

class Scope {
public $$phase?: string;
public $root = $rootScope;
public $apply = jest.fn((fn: () => void) => fn());
}

$rootScope = new Scope();

afterEach(() => {
jest.clearAllMocks();
});

it('subscribes to the passed observable, returns subscription', () => {
const $scope = new Scope();

const unsubSpy = jest.fn();
const subSpy = jest.fn(() => unsubSpy);
const observable = new Rx.Observable(subSpy);

const subscription = subscribe($scope as any, observable);
expect(subSpy).toHaveBeenCalledTimes(1);
expect(unsubSpy).not.toHaveBeenCalled();

subscription.unsubscribe();

expect(subSpy).toHaveBeenCalledTimes(1);
expect(unsubSpy).toHaveBeenCalledTimes(1);
});

it('calls observer.next() if already in a digest cycle, wraps in $scope.$apply if not', () => {
const subject = new Rx.Subject();
const nextSpy = jest.fn();
const $scope = new Scope();

subscribe($scope as any, subject, { next: nextSpy });

subject.next();
expect($scope.$apply).toHaveBeenCalledTimes(1);
expect(nextSpy).toHaveBeenCalledTimes(1);

jest.clearAllMocks();

$rootScope.$$phase = '$digest';
subject.next();
expect($scope.$apply).not.toHaveBeenCalled();
expect(nextSpy).toHaveBeenCalledTimes(1);
});

it('reports fatalError if observer.next() throws', () => {
const $scope = new Scope();
subscribe($scope as any, Rx.of(undefined), {
next() {
throw new Error('foo bar');
},
});

expect(mockFatalError.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
[Error: foo bar],
],
]
`);
});

it('reports fatal error if observer.error is not defined and observable errors', () => {
const $scope = new Scope();
const error = new Error('foo');
error.stack = `${error.message}\n---stack trace ---`;
subscribe($scope as any, Rx.throwError(error));

expect(mockFatalError.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
[Error: Uncaught error in $scope.$subscribe: foo
---stack trace ---],
],
]
`);
});

it('reports fatal error if observer.error throws', () => {
spalger marked this conversation as resolved.
Show resolved Hide resolved
const $scope = new Scope();
subscribe($scope as any, Rx.throwError(new Error('foo')), {
error: () => {
throw new Error('foo');
},
});

expect(mockFatalError.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
[Error: foo],
],
]
`);
});

it('reports fatal error if observer.complete throws', () => {
const $scope = new Scope();
subscribe($scope as any, Rx.EMPTY, {
complete: () => {
throw new Error('foo');
},
});

expect(mockFatalError.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
[Error: foo],
],
]
`);
});
74 changes: 74 additions & 0 deletions src/ui/public/utils/subscribe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { IScope } from 'angular';
import * as Rx from 'rxjs';
import { fatalError } from 'ui/notify/fatal_error';

function callInDigest<T extends any[]>($scope: IScope, fn: (...args: T) => void, ...args: T) {
try {
// this is terrible, but necessary to synchronously deliver subscription values
// to angular scopes. This is required by some APIs, like the `config` service,
// and beneficial for root level directives where additional digest cycles make
// kibana sluggish to load.
//
// If you copy this code elsewhere you better have a good reason :)
if ($scope.$root.$$phase) {
fn(...args);
} else {
$scope.$apply(() => fn(...args));
}
} catch (error) {
fatalError(error);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: not sure if it's a big deal, but shouldn't we unsubscribe from original observable if we call fatalError when next fails?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rxjs takes care of that because fatalError() rethrows the error and when a next() handler throws the parent is unsubscribed.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, right, I forgot that fatalError always throws.

}
}

/**
* Subscribe to an observable at a $scope, ensuring that the digest cycle
* is run for subscriber hooks and routing errors to fatalError if not handled.
*/
export function subscribe<T>(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: subscribe is a bit too generic, but I don't know a better name either, the only thing that comes to my mind is subscribeWithScope, but it's arguable. So feel free to keep it as is, just wanted to note.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking subscribeAtScope(), but then I kept misremembering it as subscribeWithScope(), so I figured we can try it out. Shouldn't be a problem to rename it if we desire down the road.

$scope: IScope,
observable: Rx.Observable<T>,
observer?: Rx.PartialObserver<T>
) {
return observable.subscribe({
next(value) {
if (observer && observer.next) {
callInDigest($scope, observer.next, value);
}
},
error(error) {
callInDigest($scope, () => {
if (observer && observer.error) {
observer.error(error);
} else {
throw new Error(
`Uncaught error in $scope.$subscribe: ${error ? error.stack || error.message : error}`
);
}
});
},
complete() {
if (observer && observer.complete) {
callInDigest($scope, observer.complete);
}
},
});
}