-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathrest.ts
More file actions
277 lines (233 loc) · 10.2 KB
/
rest.ts
File metadata and controls
277 lines (233 loc) · 10.2 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
import * as Utils from '../util/utils';
import Defaults from '../util/defaults';
import Push from './push';
import PaginatedResource, { HttpPaginatedResponse, PaginatedResult } from './paginatedresource';
import RestChannel from './restchannel';
import ErrorInfo from '../types/errorinfo';
import Stats from '../types/stats';
import HttpMethods from '../../constants/HttpMethods';
import { ChannelOptions } from '../../types/channel';
import { RequestBody, RequestParams } from '../../types/http';
import * as API from '../../../../ably';
import Resource from './resource';
import Platform from '../../platform';
import BaseClient from './baseclient';
import { useTokenAuth } from './auth';
import { RestChannelMixin } from './restchannelmixin';
import { RestPresenceMixin } from './restpresencemixin';
import DeviceDetails from '../types/devicedetails';
import PushChannelSubscription from '../types/pushchannelsubscription';
type BatchResult<T> = API.BatchResult<T>;
type BatchPublishSpec = API.BatchPublishSpec;
type BatchPublishSuccessResult = API.BatchPublishSuccessResult;
type BatchPublishFailureResult = API.BatchPublishFailureResult;
type BatchPublishResult = BatchResult<BatchPublishSuccessResult | BatchPublishFailureResult>;
type BatchPresenceSuccessResult = API.BatchPresenceSuccessResult;
type BatchPresenceFailureResult = API.BatchPresenceFailureResult;
type BatchPresenceResult = BatchResult<BatchPresenceSuccessResult | BatchPresenceFailureResult>;
type TokenRevocationTargetSpecifier = API.TokenRevocationTargetSpecifier;
type TokenRevocationOptions = API.TokenRevocationOptions;
type TokenRevocationSuccessResult = API.TokenRevocationSuccessResult;
type TokenRevocationFailureResult = API.TokenRevocationFailureResult;
type TokenRevocationResult = BatchResult<TokenRevocationSuccessResult | TokenRevocationFailureResult>;
export class Rest {
private readonly client: BaseClient;
readonly channels: Channels;
readonly push: Push;
readonly channelMixin = RestChannelMixin;
readonly presenceMixin = RestPresenceMixin;
// exposed for plugins but shouldn't be bundled with minimal realtime
Resource = Resource;
PaginatedResource = PaginatedResource;
DeviceDetails = DeviceDetails;
PushChannelSubscription = PushChannelSubscription;
constructor(client: BaseClient) {
this.client = client;
this.channels = new Channels(this.client);
this.push = new Push(this.client);
}
async stats(params: RequestParams): Promise<PaginatedResult<Stats>> {
const headers = Defaults.defaultGetHeaders(this.client.options),
format = this.client.options.useBinaryProtocol ? Utils.Format.msgpack : Utils.Format.json,
envelope = this.client.http.supportsLinkHeaders ? undefined : format;
Utils.mixin(headers, this.client.options.headers);
return new PaginatedResource(this.client, '/stats', headers, envelope, function (body, headers, unpacked) {
const statsValues = unpacked ? body : JSON.parse(body as string);
for (let i = 0; i < statsValues.length; i++) statsValues[i] = Stats.fromValues(statsValues[i]);
return statsValues;
}).get(params as Record<string, string>);
}
async time(params?: RequestParams): Promise<number> {
const headers = Defaults.defaultGetHeaders(this.client.options);
if (this.client.options.headers) Utils.mixin(headers, this.client.options.headers);
const timeUri = (host: string) => {
return this.client.baseUri(host) + '/time';
};
let { error, body, unpacked } = await this.client.http.do(
HttpMethods.Get,
timeUri,
headers,
null,
params as RequestParams,
);
if (error) {
throw error;
}
if (!unpacked) body = JSON.parse(body as string);
const time = (body as number[])[0];
if (!time) {
// ably-os:inline-error-update:50000:2025-08-22:e8u Original: "Internal error (unexpected result type from GET /time)"
throw new ErrorInfo(`Internal error (unexpected result from GET /time): expected number, got ${typeof time} with value: ${JSON.stringify(body)}`, 50000, 500);
}
/* calculate time offset only once for this device by adding to the prototype */
this.client.serverTimeOffset = time - Date.now();
return time;
}
async request(
method: string,
path: string,
version: number,
params: RequestParams,
body: unknown,
customHeaders: Record<string, string>,
): Promise<HttpPaginatedResponse<unknown>> {
const [encoder, decoder, format] = (() => {
if (this.client.options.useBinaryProtocol) {
if (!this.client._MsgPack) {
Utils.throwMissingPluginError('MsgPack');
}
return [this.client._MsgPack.encode, this.client._MsgPack.decode, Utils.Format.msgpack];
} else {
return [JSON.stringify, JSON.parse, Utils.Format.json];
}
})();
const envelope = this.client.http.supportsLinkHeaders ? undefined : format;
params = params || {};
const _method = method.toLowerCase() as HttpMethods;
const headers =
_method == 'get'
? Defaults.defaultGetHeaders(this.client.options, { format, protocolVersion: version })
: Defaults.defaultPostHeaders(this.client.options, { format, protocolVersion: version });
if (typeof body !== 'string') {
body = encoder(body) ?? null;
}
Utils.mixin(headers, this.client.options.headers);
if (customHeaders) {
Utils.mixin(headers, customHeaders);
}
const paginatedResource = new PaginatedResource(
this.client,
path,
headers,
envelope,
async function (resbody, headers, unpacked) {
return Utils.ensureArray(unpacked ? resbody : decoder(resbody as string & Buffer));
},
/* useHttpPaginatedResponse: */ true,
);
if (!Platform.Http.methods.includes(_method)) {
throw new ErrorInfo('Unsupported method ' + _method, 40500, 405);
}
if (Platform.Http.methodsWithBody.includes(_method)) {
return paginatedResource[_method as HttpMethods.Post](params, body as RequestBody) as Promise<
HttpPaginatedResponse<unknown>
>;
} else {
return paginatedResource[_method as HttpMethods.Get | HttpMethods.Delete](params) as Promise<
HttpPaginatedResponse<unknown>
>;
}
}
async batchPublish<T extends BatchPublishSpec | BatchPublishSpec[]>(
specOrSpecs: T,
): Promise<T extends BatchPublishSpec ? BatchPublishResult : BatchPublishResult[]> {
let requestBodyDTO: BatchPublishSpec[];
let singleSpecMode: boolean;
if (Array.isArray(specOrSpecs)) {
requestBodyDTO = specOrSpecs;
singleSpecMode = false;
} else {
requestBodyDTO = [specOrSpecs];
singleSpecMode = true;
}
const format = this.client.options.useBinaryProtocol ? Utils.Format.msgpack : Utils.Format.json,
headers = Defaults.defaultPostHeaders(this.client.options, { format });
if (this.client.options.headers) Utils.mixin(headers, this.client.options.headers);
const requestBody = Utils.encodeBody(requestBodyDTO, this.client._MsgPack, format);
const response = await Resource.post(this.client, '/messages', requestBody, headers, {}, null, true);
const batchResults = (
response.unpacked ? response.body : Utils.decodeBody(response.body, this.client._MsgPack, format)
) as BatchPublishResult[];
// I don't love the below type assertions but not sure how to avoid them
if (singleSpecMode) {
return batchResults[0] as T extends BatchPublishSpec ? BatchPublishResult : BatchPublishResult[];
} else {
return batchResults as T extends BatchPublishSpec ? BatchPublishResult : BatchPublishResult[];
}
}
async batchPresence(channels: string[]): Promise<BatchPresenceResult> {
const format = this.client.options.useBinaryProtocol ? Utils.Format.msgpack : Utils.Format.json,
headers = Defaults.defaultPostHeaders(this.client.options, { format });
if (this.client.options.headers) Utils.mixin(headers, this.client.options.headers);
const channelsParam = channels.join(',');
const response = await Resource.get(this.client, '/presence', headers, { channels: channelsParam }, null, true);
return (
response.unpacked ? response.body : Utils.decodeBody(response.body, this.client._MsgPack, format)
) as BatchPresenceResult;
}
async revokeTokens(
specifiers: TokenRevocationTargetSpecifier[],
options?: TokenRevocationOptions,
): Promise<TokenRevocationResult> {
if (useTokenAuth(this.client.options)) {
// ably-os:inline-error-update:40162:2025-08-22:e8u Original: "Cannot revoke tokens when using token auth"
throw new ErrorInfo('Cannot revoke tokens when using token auth. Token revocation requires API key authentication for security', 40162, 401);
}
const keyName = this.client.options.keyName!;
let resolvedOptions = options ?? {};
const requestBodyDTO = {
targets: specifiers.map((specifier) => `${specifier.type}:${specifier.value}`),
...resolvedOptions,
};
const format = this.client.options.useBinaryProtocol ? Utils.Format.msgpack : Utils.Format.json,
headers = Defaults.defaultPostHeaders(this.client.options, { format });
if (this.client.options.headers) Utils.mixin(headers, this.client.options.headers);
const requestBody = Utils.encodeBody(requestBodyDTO, this.client._MsgPack, format);
const response = await Resource.post(
this.client,
`/keys/${keyName}/revokeTokens`,
requestBody,
headers,
{},
null,
true,
);
return (
response.unpacked ? response.body : Utils.decodeBody(response.body, this.client._MsgPack, format)
) as TokenRevocationResult;
}
}
class Channels {
client: BaseClient;
// RSN2
all: Record<string, RestChannel>;
constructor(client: BaseClient) {
this.client = client;
this.all = Object.create(null);
}
get(name: string, channelOptions?: ChannelOptions) {
name = String(name);
let channel = this.all[name];
if (!channel) {
this.all[name] = channel = new RestChannel(this.client, name, channelOptions);
} else if (channelOptions) {
channel.setOptions(channelOptions);
}
return channel;
}
/* Included to support certain niche use-cases; most users should ignore this.
* Please do not use this unless you know what you're doing */
release(name: string) {
delete this.all[String(name)];
}
}