-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcos.js
189 lines (162 loc) · 4.45 KB
/
cos.js
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
// npm install fetch-event-stream
import { events } from 'fetch-event-stream';
// npm install yargs
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
class Channel {
constructor(baseUrl, auth = '') {
this.baseUrl = baseUrl;
this.headers = {
'Content-Type': 'application/json',
};
if (auth) {
this.headers.Authorization = `Bearer ${auth}`;
}
}
publish = async (addr, msg) => {
const resp = await fetch(`${this.baseUrl}/runtime/channel/publish`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
addr: addr,
msg: msg,
})
});
if (!resp.ok) {
throw new Error(`HTTP error: ${resp.status}`);
}
}
publishMulti = async (addr, msg) => {
}
subscribe = async (path, data, handler) => {
const url = `${this.baseUrl}${path}`;
let controller = new AbortController();
let resp = await fetch(url, {
signal: controller.signal,
method: 'POST',
headers: this.headers,
body: JSON.stringify(data)
});
if (resp.ok) {
let stream = events(resp, controller.signal);
for await (let event of stream) {
const data = JSON.parse(event.data);
await handler(data);
}
}
}
}
class Runtime {
constructor(baseUrl, auth = '') {
this.channel = new Channel(baseUrl, auth);
this.factories = {};
this.promises = {};
}
register = async (name, constructor, description = '') => {
if (this.factories[name]) {
throw new Error(`Agent with name ${name} already registered`);
}
this.factories[name] = constructor;
this.channel.subscribe(
'/runtime/register',
{
name: name,
description: description
},
this.handle,
);
}
handle = async (data) => {
switch (data.header.type) {
case 'AgentCreated':
this.createAgent(data);
break;
case 'AgentDeleted':
this.deleteAgent(data);
break;
default:
console.log(`Unknown message type: ${data.header.type}`);
}
}
createAgent = async (data) => {
const content = JSON.parse(data.content);
const addr = content.addr;
console.log(`Creating agent with addr: ${JSON.stringify(addr)}`)
let constructor = this.factories[addr.name];
const agent = new constructor(this.channel, addr);
this.promises[addr.name] = this.channel.subscribe(
'/runtime/channel/subscribe',
{addr: addr},
agent.receive,
);
}
deleteAgent = async (data) => {
}
}
class Agent {
constructor(channel, addr) {
this.channel = channel;
this.addr = addr;
}
receive = async (msg) => {
console.log(`Received a message: ${JSON.stringify(msg)}`);
let result = this.handle(msg);
if (!msg.reply) {
return
}
if (isAsyncIterator(result)) {
for await (let r of result) {
console.log(`partial result: ${JSON.stringify(r)}`);
await this.channel.publish(msg.reply, r);
}
// End of the iteration, send an extra StopIteration message.
const stop = {header: {type: 'StopIteration'}}
await this.channel.publish(msg.reply, stop);
} else {
result = await result;
console.log(`result: ${JSON.stringify(result)}`);
await this.channel.publish(msg.reply, result);
}
}
}
function isAsyncIterator(obj) {
return obj && typeof obj === 'object' && Symbol.asyncIterator in obj;
}
class Server extends Agent {
handle = async (msg) => {
if (msg.header.type === 'Ping') {
return {header: {type: 'Pong'}};
}
}
}
class StreamServer extends Agent {
async * handle(msg) {
if (msg.header.type === 'Ping') {
const words = ['Hi ', 'there, ', 'this ', 'is ', 'the ', 'Pong ', 'server.'];
for (const word of words) {
await new Promise(resolve => setTimeout(resolve, 600)); // sleep 0.6s
yield {
header: {type: 'PartialPong'},
content: JSON.stringify({"content": word}),
};
}
}
}
}
const argv = yargs(hideBin(process.argv))
.option('server', {
type: 'string',
description: 'The base URL.',
default: 'http://127.0.0.1:8000',
})
.option('auth', {
type: 'string',
description: 'Authorization token.',
default: '',
})
.parse();
const runtime = new Runtime(argv.server, argv.auth);
Promise.all([
runtime.register('server', Server, 'The Pong Server.'),
runtime.register('stream_server', StreamServer, 'The Stream Pong Server.'),
]).catch(console.error)