generated from magda-io/magda-function-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRegistryEventStream.ts
221 lines (193 loc) · 5.51 KB
/
RegistryEventStream.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
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
import fetch from "isomorphic-fetch";
import { Readable } from "stream";
import signJwtToken from "./signJwtToken";
export const DEFAULT_FETCH_ASPECTS = [
"dcat-dataset-strings",
"dcat-distribution-strings",
"dataset-distributions",
"temporal-coverage",
"usage",
"access",
"dataset-publisher",
"source",
"source-link-status",
"dataset-quality-rating",
"spatial-coverage",
"publishing",
"dataset-access-control",
"organization-details",
"provenance",
"information-security",
"currency",
"ckan-export",
"version"
];
export type Event = {
eventTime: string;
eventType: string;
tenantId: number;
userId: string;
id: number;
data: any;
};
async function getRecordHistory(
registryUrl: string,
recordId: string,
options: {
start: number;
limit: number;
pageToken: string;
jwtToken?: string;
}
) {
const queryParameters: string[] = [
"dereference=true",
typeof options.start === "undefined" ? "" : `start=${options.start}`,
typeof options.pageToken === "undefined"
? ""
: `pageToken=${options.pageToken}`,
typeof options.limit === "undefined" ? "" : `limit=${options.limit}`
]
.filter(item => !!item)
.concat(DEFAULT_FETCH_ASPECTS.map(aspect => "aspect=" + aspect));
const tenantId = process.env.tenantId;
const headers = {
"X-Magda-Tenant-Id": tenantId ? tenantId : "0"
} as any;
if (options.jwtToken) {
headers["X-Magda-Session"] = options.jwtToken;
}
const res = await fetch(
`${registryUrl}/records/${encodeURIComponent(
recordId
)}/history?${queryParameters.join("&")}`,
{
headers
}
);
if (!res.ok) {
throw new Error(
`Failed to fetch history from registry api. Error Code: ${
res.status
} Details: ${await res.text()}`
);
}
return (await res.json()) as {
hasMore: boolean;
nextPageToken: string;
events: Event[];
};
}
const DEFAULT_LIMIT = 50;
export default class RegistryEventStream extends Readable {
private hasMore: boolean;
private pageToken: string;
private limit: number;
private registryApiUrl: string;
private recordId: string;
private userId: string | null;
private dataCache: Event[];
private isPushing: boolean;
constructor(
registryApiUrl: string,
recordId: string,
options: {
userId: string | null;
limit?: number;
}
) {
const limit = options.limit > 0 ? options.limit : DEFAULT_LIMIT;
super({
objectMode: true,
highWaterMark: limit
});
this.limit = limit;
if (!registryApiUrl) {
throw new Error(
"RegistryEventStream: Invalid empty registryApiUrl"
);
}
if (!recordId) {
throw new Error("RegistryEventStream: Invalid empty recordId");
}
this.registryApiUrl = registryApiUrl;
this.recordId = recordId;
this.userId = options.userId;
this.dataCache = [];
this.isPushing = false;
this.hasMore = true;
}
async pushTillFull() {
if (this.isPushing) {
return;
}
try {
this.isPushing = true;
let pushMore = true;
while (pushMore) {
let event = this.dataCache.pop();
if (!event) {
const result = await this.fetchMore();
if (!result) {
// error happen or no more to read
// send EOF
this.push(null);
return;
}
event = this.dataCache.pop();
}
if (!event) {
// still empty --- no more data & send EOF
this.push(null);
return;
}
pushMore = this.push(event);
}
} catch (e) {
this.destroy(e as Error);
} finally {
this.isPushing = false;
}
}
async fetchMore() {
try {
if (!this.hasMore) {
return false;
}
const opts = {
limit: this.limit
} as any;
if (this.pageToken) {
opts.pageToken = this.pageToken;
}
if (this.userId) {
opts.jwtToken = await signJwtToken(this.userId);
}
const data = await getRecordHistory(
this.registryApiUrl,
this.recordId,
opts
);
this.hasMore = data?.hasMore ? true : false;
this.pageToken = data?.nextPageToken ? data.nextPageToken : "";
if (this.hasMore && !this.pageToken) {
throw new Error(
"RegistryEventStream: Invalid reponse from history API: " +
JSON.stringify(data)
);
}
if (data?.events?.length) {
this.dataCache = this.dataCache.concat(data.events);
return true;
} else {
return false;
}
} catch (e) {
this.destroy(e as Error);
return false;
}
}
_read() {
this.pushTillFull();
}
}