-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathprocess-data.service.ts
More file actions
305 lines (277 loc) · 13.4 KB
/
Copy pathprocess-data.service.ts
File metadata and controls
305 lines (277 loc) · 13.4 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import {
Inject,
Injectable,
InjectionToken,
NgZone,
} from '@angular/core';
import { PROCESS } from '@dspace/core/shared/process.resource-type';
import { hasValue } from '@dspace/shared/utils/empty.util';
import {
Observable,
Subscription,
} from 'rxjs';
import {
distinctUntilChanged,
filter,
find,
switchMap,
} from 'rxjs/operators';
import { dataService } from '../../cache/builders/build-decorators';
import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service';
import { ObjectCacheService } from '../../cache/object-cache.service';
import { NotificationsService } from '../../notification-system/notifications.service';
import { Process } from '../../processes/process.model';
import { ProcessStatus } from '../../processes/process-status.model';
import { Bitstream } from '../../shared/bitstream.model';
import { FollowLinkConfig } from '../../shared/follow-link-config.model';
import { HALEndpointService } from '../../shared/hal-endpoint.service';
import { NoContent } from '../../shared/NoContent.model';
import { getAllCompletedRemoteData } from '../../shared/operators';
import {
DeleteData,
DeleteDataImpl,
} from '../base/delete-data';
import {
FindAllData,
FindAllDataImpl,
} from '../base/find-all-data';
import { IdentifiableDataService } from '../base/identifiable-data.service';
import {
SearchData,
SearchDataImpl,
} from '../base/search-data';
import { BitstreamDataService } from '../bitstream-data.service';
import { FindListOptions } from '../find-list-options.model';
import { PaginatedList } from '../paginated-list.model';
import { RemoteData } from '../remote-data';
import { RequestService } from '../request.service';
/**
* Create an InjectionToken for the default JS setTimeout function, purely so we can mock it during
* testing. (fakeAsync isn't working for this case)
*/
export const TIMER_FACTORY = new InjectionToken<(callback: (...args: any[]) => void, ms?: number, ...args: any[]) => NodeJS.Timeout>('timer', {
providedIn: 'root',
factory: () => setTimeout,
});
@Injectable({ providedIn: 'root' })
@dataService(PROCESS)
export class ProcessDataService extends IdentifiableDataService<Process> implements FindAllData<Process>, DeleteData<Process>, SearchData<Process> {
private findAllData: FindAllData<Process>;
private deleteData: DeleteData<Process>;
private searchData: SearchData<Process>;
protected activelyBeingPolled: Map<string, NodeJS.Timeout> = new Map();
protected subs: Map<string, Subscription> = new Map();
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected bitstreamDataService: BitstreamDataService,
protected notificationsService: NotificationsService,
protected zone: NgZone,
@Inject(TIMER_FACTORY) protected timer: (callback: (...args: any[]) => void, ms?: number, ...args: any[]) => NodeJS.Timeout,
) {
super('processes', requestService, rdbService, objectCache, halService);
this.findAllData = new FindAllDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive);
this.deleteData = new DeleteDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive, this.constructIdEndpoint);
this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive);
}
/**
* Return true if the given process has the given status
* @protected
*/
protected static statusIs(process: Process, status: ProcessStatus): boolean {
return hasValue(process) && process.processStatus === status;
}
/**
* Return true if the given process has the status COMPLETED or FAILED
*/
public static hasCompletedOrFailed(process: Process): boolean {
return ProcessDataService.statusIs(process, ProcessStatus.COMPLETED) ||
ProcessDataService.statusIs(process, ProcessStatus.FAILED);
}
/**
* Get the endpoint for the files of the process
* @param processId The ID of the process
*/
getFilesEndpoint(processId: string): Observable<string> {
return this.getBrowseEndpoint().pipe(
switchMap((href) => this.halService.getEndpoint('files', `${href}/${processId}`)),
);
}
/**
* Get a process' output files
* @param processId The ID of the process
*/
getFiles(processId: string): Observable<RemoteData<PaginatedList<Bitstream>>> {
const href$ = this.getFilesEndpoint(processId);
return this.bitstreamDataService.findListByHref(href$);
}
/**
* Returns {@link RemoteData} of all object with a list of {@link FollowLinkConfig}, to indicate which embedded
* info should be added to the objects
*
* @param options Find list options object
* @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's
* no valid cached version. Defaults to true
* @param reRequestOnStale Whether or not the request should automatically be re-
* requested after the response becomes stale
* @param linksToFollow List of {@link FollowLinkConfig} that indicate which
* {@link HALLink}s should be automatically resolved
* @return {Observable<RemoteData<PaginatedList<T>>>}
* Return an observable that emits object list
*/
findAll(options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig<Process>[]): Observable<RemoteData<PaginatedList<Process>>> {
return this.findAllData.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
}
/**
* @param searchMethod The search method for the Process
* @param options The FindListOptions object
* @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's
* no valid cached version. Defaults to true.
* @param reRequestOnStale Whether the request should automatically be re-
* requested after the response becomes stale.
* @param linksToFollow List of {@link FollowLinkConfig} that indicate which
* {@link HALLink}s should automatically be resolved.
* @return {Observable<RemoteData<PaginatedList<Process>>>}
* Return an observable that emits a paginated list of processes
*/
searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig<Process>[]): Observable<RemoteData<PaginatedList<Process>>> {
return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
}
/**
* @param id The id for this auto-refreshing search. Used to stop
* auto-refreshing afterwards, and ensure we're not
* auto-refreshing the same thing multiple times.
* @param searchMethod The search method for the Process
* @param options The FindListOptions object
* @param pollingIntervalInMs The interval by which the search will be repeated
* @param linksToFollow List of {@link FollowLinkConfig} that indicate which
* {@link HALLink}s should automatically be resolved.
* @return {Observable<RemoteData<PaginatedList<Process>>>}
* Return an observable that emits a paginated list of processes every interval
*/
autoRefreshingSearchBy(id: string, searchMethod: string, options?: FindListOptions, pollingIntervalInMs: number = 5000, ...linksToFollow: FollowLinkConfig<Process>[]): Observable<RemoteData<PaginatedList<Process>>> {
const result$ = this.searchBy(searchMethod, options, true, true, ...linksToFollow).pipe(
getAllCompletedRemoteData(),
);
const sub = result$.pipe(
filter(() =>
!this.activelyBeingPolled.has(id),
),
).subscribe((processListRd: RemoteData<PaginatedList<Process>>) => {
this.clearCurrentTimeout(id);
const nextTimeout = this.timer(() => {
this.activelyBeingPolled.delete(id);
this.requestService.setStaleByHrefSubstring(processListRd.payload._links.self.href);
}, pollingIntervalInMs);
this.activelyBeingPolled.set(id, nextTimeout);
});
this.subs.set(id, sub);
return result$;
}
/**
* Stop auto-refreshing the request with the given id
* @param id the id of the request to stop automatically refreshing
*/
stopAutoRefreshing(id: string) {
this.clearCurrentTimeout(id);
if (hasValue(this.subs.get(id))) {
this.subs.get(id).unsubscribe();
this.subs.delete(id);
}
}
/**
* Delete an existing object on the server
* @param objectId The id of the object to be removed
* @param copyVirtualMetadata (optional parameter) the identifiers of the relationship types for which the virtual
* metadata should be saved as real metadata
* @return A RemoteData observable with an empty payload, but still representing the state of the request: statusCode,
* errorMessage, timeCompleted, etc
*/
public delete(objectId: string, copyVirtualMetadata?: string[]): Observable<RemoteData<NoContent>> {
return this.deleteData.delete(objectId, copyVirtualMetadata);
}
/**
* Delete an existing object on the server
* @param href The self link of the object to be removed
* @param copyVirtualMetadata (optional parameter) the identifiers of the relationship types for which the virtual
* metadata should be saved as real metadata
* @return A RemoteData observable with an empty payload, but still representing the state of the request: statusCode,
* errorMessage, timeCompleted, etc
* Only emits once all request related to the DSO has been invalidated.
*/
public deleteByHref(href: string, copyVirtualMetadata?: string[]): Observable<RemoteData<NoContent>> {
return this.deleteData.deleteByHref(href, copyVirtualMetadata);
}
/**
* Clear the timeout for the given id, if that timeout exists
* @protected
*/
protected clearCurrentTimeout(id: string): void {
const timeout = this.activelyBeingPolled.get(id);
if (hasValue(timeout)) {
clearTimeout(timeout);
}
this.activelyBeingPolled.delete(id);
}
/**
* Poll the process with the given ID, using the given interval, until that process either
* completes successfully or fails
*
* Return an Observable<RemoteData> for the Process. Note that this will also emit while the
* process is still running. It will only emit again when the process (not the RemoteData!) changes
* status. That makes it more convenient to retrieve that process for a component: you can replace
* a findByID call with this method, rather than having to do a separate findById, and then call
* this method
*
* @param processId The ID of the {@link Process} to poll
* @param pollingIntervalInMs The interval for how often the request needs to be polled
* @param linksToFollow List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be
* automatically resolved
*/
public autoRefreshUntilCompletion(processId: string, pollingIntervalInMs = 5000, ...linksToFollow: FollowLinkConfig<Process>[]): Observable<RemoteData<Process>> {
const process$: Observable<RemoteData<Process>> = this.findById(processId, true, true, ...linksToFollow)
.pipe(
getAllCompletedRemoteData(),
);
// Create a subscription that marks the data as stale if the process hasn't been completed and
// the polling interval time has been exceeded.
const sub = process$.pipe(
filter((processRD: RemoteData<Process>) =>
!ProcessDataService.hasCompletedOrFailed(processRD.payload) &&
!this.activelyBeingPolled.has(processId),
),
).subscribe((processRD: RemoteData<Process>) => {
this.clearCurrentTimeout(processId);
if (processRD.hasSucceeded) {
const nextTimeout = this.timer(() => {
this.activelyBeingPolled.delete(processId);
this.invalidateByHref(processRD.payload._links.self.href);
}, pollingIntervalInMs);
this.activelyBeingPolled.set(processId, nextTimeout);
}
});
this.subs.set(processId, sub);
// When the process completes create a one off subscription (the `find` completes the
// observable) that unsubscribes the previous one, removes the processId from the list of
// processes being polled and clears any running timeouts
process$.pipe(
find((processRD: RemoteData<Process>) => ProcessDataService.hasCompletedOrFailed(processRD.payload)),
).subscribe(() => {
this.stopAutoRefreshing(processId);
});
return process$.pipe(
distinctUntilChanged((previous: RemoteData<Process>, current: RemoteData<Process>) =>
previous.payload?.processStatus === current.payload?.processStatus,
),
);
}
/**
* Get process' details
* @param processId The ID of the process
*/
getProcess(processId: string): Observable<RemoteData<Process>> {
return this.findById(processId, false);
}
}