-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathoffline.ts
180 lines (157 loc) · 5.7 KB
/
offline.ts
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
import type { BaseTransportOptions, Envelope, OfflineStore, OfflineTransportOptions, Transport } from '@sentry/core';
import { makeOfflineTransport, parseEnvelope, serializeEnvelope } from '@sentry/core';
import { WINDOW } from '../helpers';
import { makeFetchTransport } from './fetch';
// 'Store', 'promisifyRequest' and 'createStore' were originally copied from the 'idb-keyval' package before being
// modified and simplified: https://github.com/jakearchibald/idb-keyval
//
// At commit: 0420a704fd6cbb4225429c536b1f61112d012fca
// Original license:
// Copyright 2016, Jake Archibald
//
// Licensed 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.
type Store = <T>(callback: (store: IDBObjectStore) => T | PromiseLike<T>) => Promise<T>;
function promisifyRequest<T = undefined>(request: IDBRequest<T> | IDBTransaction): Promise<T> {
return new Promise<T>((resolve, reject) => {
// @ts-expect-error - file size hacks
request.oncomplete = request.onsuccess = () => resolve(request.result);
// @ts-expect-error - file size hacks
request.onabort = request.onerror = () => reject(request.error);
});
}
/** Create or open an IndexedDb store */
export function createStore(dbName: string, storeName: string): Store {
const request = indexedDB.open(dbName);
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
const dbp = promisifyRequest(request);
return callback => dbp.then(db => callback(db.transaction(storeName, 'readwrite').objectStore(storeName)));
}
function keys(store: IDBObjectStore): Promise<number[]> {
return promisifyRequest(store.getAllKeys() as IDBRequest<number[]>);
}
/** Insert into the end of the store */
export function push(store: Store, value: Uint8Array | string, maxQueueSize: number): Promise<void> {
return store(store => {
return keys(store).then(keys => {
if (keys.length >= maxQueueSize) {
return;
}
// We insert with an incremented key so that the entries are popped in order
store.put(value, Math.max(...keys, 0) + 1);
return promisifyRequest(store.transaction);
});
});
}
/** Insert into the front of the store */
export function unshift(store: Store, value: Uint8Array | string, maxQueueSize: number): Promise<void> {
return store(store => {
return keys(store).then(keys => {
if (keys.length >= maxQueueSize) {
return;
}
// We insert with an decremented key so that the entries are popped in order
store.put(value, Math.min(...keys, 0) - 1);
return promisifyRequest(store.transaction);
});
});
}
/** Pop the oldest value from the store */
export function shift(store: Store): Promise<Uint8Array | string | undefined> {
return store(store => {
return keys(store).then(keys => {
const firstKey = keys[0];
if (firstKey == null) {
return undefined;
}
return promisifyRequest(store.get(firstKey)).then(value => {
store.delete(firstKey);
return promisifyRequest(store.transaction).then(() => value);
});
});
});
}
export interface BrowserOfflineTransportOptions extends Omit<OfflineTransportOptions, 'createStore'> {
/**
* Name of indexedDb database to store envelopes in
* Default: 'sentry-offline'
*/
dbName?: string;
/**
* Name of indexedDb object store to store envelopes in
* Default: 'queue'
*/
storeName?: string;
/**
* Maximum number of envelopes to store
* Default: 30
*/
maxQueueSize?: number;
}
function createIndexedDbStore(options: BrowserOfflineTransportOptions): OfflineStore {
let store: Store | undefined;
// Lazily create the store only when it's needed
function getStore(): Store {
if (store == undefined) {
store = createStore(options.dbName || 'sentry-offline', options.storeName || 'queue');
}
return store;
}
return {
push: async (env: Envelope) => {
try {
const serialized = await serializeEnvelope(env);
await push(getStore(), serialized, options.maxQueueSize || 30);
} catch (_) {
//
}
},
unshift: async (env: Envelope) => {
try {
const serialized = await serializeEnvelope(env);
await unshift(getStore(), serialized, options.maxQueueSize || 30);
} catch (_) {
//
}
},
shift: async () => {
try {
const deserialized = await shift(getStore());
if (deserialized) {
return parseEnvelope(deserialized);
}
} catch (_) {
//
}
return undefined;
},
};
}
function makeIndexedDbOfflineTransport<T>(
createTransport: (options: T) => Transport,
): (options: T & BrowserOfflineTransportOptions) => Transport {
return options => {
const transport = createTransport({ ...options, createStore: createIndexedDbStore });
WINDOW.addEventListener('online', async _ => {
await transport.flush();
});
return transport;
};
}
/**
* Creates a transport that uses IndexedDb to store events when offline.
*/
export function makeBrowserOfflineTransport<T extends BaseTransportOptions>(
createTransport: (options: T) => Transport = makeFetchTransport,
): (options: T & BrowserOfflineTransportOptions) => Transport {
return makeIndexedDbOfflineTransport<T>(makeOfflineTransport(createTransport));
}