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

[Feature] Better Error Logging #18

Merged
merged 1 commit into from
Oct 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions .changeset/strong-moose-applaud.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@journeyapps/powersync-sdk-react-native': patch
'@journeyapps/powersync-sdk-common': patch
---

Added better logging of streaming errors. Added warnings if Polyfills are not correctly configured.
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
import Logger, { ILogger } from 'js-logger';
import { PowerSyncCredentials } from '../../connection/PowerSyncCredentials';

export type RemoteOptions = {
export type RemoteConnector = {
fetchCredentials: () => Promise<PowerSyncCredentials>;
};

//Refresh at least 30 sec before it expires
const REFRESH_CREDENTIALS_SAFETY_PERIOD_MS = 30_000;

export const DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');

export abstract class AbstractRemote {
protected credentials?: PowerSyncCredentials;

constructor(protected options: RemoteOptions) {}
constructor(protected connector: RemoteConnector, protected logger: ILogger = DEFAULT_REMOTE_LOGGER) {}

async getCredentials(): Promise<PowerSyncCredentials> {
const { expiresAt } = this.credentials ?? {};
if (expiresAt && expiresAt > new Date(new Date().valueOf() + REFRESH_CREDENTIALS_SAFETY_PERIOD_MS)) {
return this.credentials!;
}
this.credentials = await this.options.fetchCredentials();
this.credentials = await this.connector.fetchCredentials();
return this.credentials;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ export abstract class AbstractStreamingSyncImplementation extends BaseObserver<S
await this.streamingSyncIteration(signal);
// Continue immediately
} catch (ex) {
this.logger.error(ex);
this.updateSyncStatus(false);
// On error, wait a little before retrying
await new Promise((resolve) => setTimeout(resolve, this.options.retryDelayMs));
Expand Down
9 changes: 9 additions & 0 deletions packages/powersync-sdk-react-native/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,15 @@ export const TodoListDisplay = () => {
}
```

### Logging
The default logger uses js-logger. Debug logs can be displayed with:

```JavaScript
import Logger from 'js-logger';
Logger.useDefaults();
Logger.setLevel(Logger.DEBUG);
```


# Known Issues

Expand Down
2 changes: 2 additions & 0 deletions packages/powersync-sdk-react-native/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@journeyapps/react-native-quick-sqlite": "0.0.2",
"base-64": "^1.0.0",
"react": "*",
"react-native": "*",
"react-native-fetch-api": "^3.0.0",
"react-native-get-random-values": "^1.9.0",
"react-native-polyfill-globals": "^3.1.0",
Expand All @@ -42,6 +43,7 @@
"devDependencies": {
"@journeyapps/react-native-quick-sqlite": "0.0.2",
"@types/async-lock": "^1.4.0",
"react-native": "0.72.4",
"react": "18.2.0",
"typescript": "^4.1.3"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { AbstractRemote } from '@journeyapps/powersync-sdk-common';
import { Platform } from 'react-native';

export const STREAMING_POST_TIMEOUT_MS = 30_000;

export class ReactNativeRemote extends AbstractRemote {
async post(path: string, data: any, headers: Record<string, string> = {}): Promise<any> {
Expand Down Expand Up @@ -43,8 +46,30 @@ export class ReactNativeRemote extends AbstractRemote {
headers: Record<string, string> = {},
signal?: AbortSignal
): Promise<any> {
// Ensure polyfills are present
if (
typeof ReadableStream == 'undefined' ||
typeof TextEncoder == 'undefined' ||
typeof TextDecoder == 'undefined'
) {
const errorMessage = `Polyfills are undefined. Please ensure React Native polyfills are installed and imported in the app entrypoint.
"import 'react-native-polyfill-globals/auto';"
`;
this.logger.error(errorMessage);
throw new Error(errorMessage);
}

const credentials = await this.getCredentials();

let timeout =
Platform.OS == 'android'
? setTimeout(() => {
this.logger.warn(
`HTTP Streaming POST is taking longer than 30 seconds to resolve. If using a debug build, please ensure Flipper Network plugin is disabled.`
Copy link
Contributor

Choose a reason for hiding this comment

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

The message should also use the STREAMING_POST_TIMEOUT_MS constant.

);
}, STREAMING_POST_TIMEOUT_MS)
: null;

const res = await fetch(credentials.endpoint + path, {
method: 'POST',
headers: { ...headers, ...(await this.getHeaders()) },
Expand All @@ -63,9 +88,11 @@ export class ReactNativeRemote extends AbstractRemote {
throw ex;
});

clearTimeout(timeout);

if (!res.ok) {
const text = await res.text();
console.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
const error: any = new Error(`HTTP ${res.statusText}: ${text}`);
error.status = res.status;
throw error;
Expand Down
Loading