/
market.ts
executable file
·301 lines (260 loc) · 7.46 KB
/
market.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
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
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import { Model } from "../props";
import { logger, sleep } from "../utils";
import { RequestorApi } from "ya-ts-client/dist/ya-market/api";
import * as models from "ya-ts-client/dist/ya-market/src/models";
import { Configuration } from "ya-ts-client/dist/ya-activity";
dayjs.extend(utc);
type _ModelType = Pick<Model, "from_properties"> & Partial<Model>;
class View {
private _properties!: object;
constructor(properties: object) {
this._properties = properties;
}
extract(m: _ModelType): _ModelType {
return m.from_properties(this._properties);
}
}
class AgreementDetails extends Object {
raw_details!: models.Agreement;
constructor(_ref: models.Agreement) {
super();
this.raw_details = _ref;
}
provider_view(): View {
let offer: models.Offer = this.raw_details.offer;
return new View(offer.properties);
}
requestor_view(c: Model): View {
let demand: models.Demand = this.raw_details.demand;
return new View(demand.properties);
}
}
export class Agreement {
private _api;
private _subscription;
private _id;
constructor(
api: RequestorApi,
subscription: Subscription,
agreement_id: string
) {
this._api = api;
this._subscription = subscription;
this._id = agreement_id;
}
id(): string {
return this._id;
}
async details(): Promise<AgreementDetails> {
let { data } = await this._api.getAgreement(this._id, { timeout: 3000 });
return new AgreementDetails(data);
}
async confirm(): Promise<boolean> {
await this._api.confirmAgreement(this._id);
try {
let { data: msg } = await this._api.waitForApproval(this._id, 90, { timeout: 100000 });
return true;
} catch (error) {
logger.debug(`waitForApproval(${this._id}) raised ApiException ${error}`);
return false;
}
}
async terminate(reason: string = "Finished"): Promise<boolean> {
try {
await this._api.terminateAgreement(this._id, { message: reason }, { timeout: 5000 });
logger.debug(`terminateAgreement(${this._id}) returned successfully`);
return true;
} catch (error) {
if (error.response.status === 410) {
logger.debug(
`terminateAgreement(${this._id}) raised ApiException: status = 410, message = ${error.message}`
);
} else {
logger.debug(`terminateAgreement(${this._id}) raised ApiException`);
}
return false;
}
}
}
class mProposal implements models.Proposal {
properties!: object;
constraints!: string;
proposalId!: string;
issuerId!: string;
state!: models.ProposalAllOfStateEnum;
prevProposalId?: string;
timestamp!: string;
}
class mDemandOfferBase implements models.DemandOfferBase {
properties!: object;
constraints!: string;
}
class mAgreementProposal implements models.AgreementProposal {
proposalId!: string;
validTo!: string;
}
export class OfferProposal {
private _proposal!: models.ProposalEvent;
private _subscription!: Subscription;
constructor(subscription: Subscription, proposal: models.ProposalEvent) {
this._proposal = proposal;
this._subscription = subscription;
}
issuer(): string {
return this._proposal.proposal!.issuerId || "";
}
id(): string {
return this._proposal.proposal!.proposalId || "";
}
props() {
return this._proposal.proposal!.properties;
}
state() {
return this._proposal.proposal!.state;
}
is_draft(): boolean {
return (
this._proposal.proposal!.state == models.ProposalAllOfStateEnum.Draft
);
}
async reject(_reason: string | null = null) {
await this._subscription._api.rejectProposalOffer(
this._subscription.id(),
this.id()
);
}
async respond(props: object, constraints: string): Promise<string> {
let with_proposal: mDemandOfferBase = new mDemandOfferBase();
with_proposal.properties = props;
with_proposal.constraints = constraints;
let {
data: new_proposal,
} = await this._subscription._api.counterProposalDemand(
this._subscription.id(),
this.id(),
with_proposal,
{ timeout: 5000 }
);
return new_proposal;
}
// TODO: This timeout is for negotiation ?
async create_agreement(timeout = 3600): Promise<Agreement> {
let proposal: mAgreementProposal = new mAgreementProposal();
proposal.proposalId = this.id();
proposal.validTo = dayjs()
.add(timeout, "second")
.utc()
.format("YYYY-MM-DD HH:mm:ss.SSSSSSZ");
let api: RequestorApi = this._subscription._api;
let { data: agreement_id } = await api.createAgreement(proposal, { timeout: 3000 });
return new Agreement(api, this._subscription, agreement_id);
}
}
export class Subscription {
public _api: RequestorApi;
private _id: string;
private _open: boolean;
private _deleted: boolean;
private _details;
constructor(
api: RequestorApi,
subscription_id: string,
_details: models.Demand | null = null
) {
this._api = api;
this._id = subscription_id;
this._open = true;
this._deleted = false;
this._details = _details;
}
id() {
return this._id;
}
close() {
this._open = false;
}
async ready(): Promise<this> {
return this;
}
async done() {
await this.delete();
}
details(): models.Demand {
if (!this._details) throw "expected details on list object";
return this._details;
}
async delete() {
this._open = false;
if (!this._deleted) {
await this._api.unsubscribeDemand(this._id, { timeout: 3000 });
}
}
async *events(cancellationToken?): AsyncGenerator<OfferProposal> {
while (this._open) {
if (cancellationToken && cancellationToken.cancelled) break;
try {
let { data: proposals } = await this._api.collectOffers(
this._id,
3,
10,
{ timeout: 5000 }
);
for (let _proposal of proposals) {
if (_proposal.eventType === "ProposalEvent") {
yield new OfferProposal(this, _proposal as models.ProposalEvent);
}
}
if (cancellationToken && cancellationToken.cancelled) break;
if (!proposals || !proposals.length) {
await sleep(2);
}
} catch (error) {
logger.error(error);
throw Error(error);
}
}
return;
}
}
class mDemand implements models.Demand {
demandId: string = "";
requestorId: string = "";
properties!: object;
constraints!: string;
timestamp!: string;
}
export class Market {
private _api: RequestorApi;
constructor(cfg: Configuration) {
this._api = new RequestorApi(cfg);
}
subscribe(props: {}, constraints: string): Promise<Subscription> {
let request: models.DemandOfferBase = new mDemandOfferBase();
request.properties = props;
request.constraints = constraints;
let self = this;
async function create(): Promise<Subscription> {
try {
let { data: sub_id } = await self._api.subscribeDemand(request, { timeout: 5000 });
return new Subscription(self._api, sub_id);
} catch (error) {
logger.error(error);
throw new Error(error);
}
}
return create();
}
async *subscriptions(): AsyncGenerator<Subscription> {
try {
let { data: demands } = await this._api.getDemands({ timeout: 3000 });
for (let demand of demands) {
yield new Subscription(this._api, demand.demandId as string, demand);
}
} catch (error) {
logger.warn(`getDemands error: ${error}`);
}
return;
}
}