git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 1ee5f08dcf25af27f0dce6fdc1eab39b185d202f

Files: 1ee5f08dcf25af27f0dce6fdc1eab39b185d202f / actor.js

2781 bytesRaw
1module.exports = class Actor {
2 /**
3 * the Actor manages the varous message passing functions and provides
4 * an interface for the containers to use
5 * @param {Object} opts
6 * @param {Object} opts.id - the UUID of the Actor
7 * @param {Object} opts.state - the state of the container
8 * @param {Object} opts.hypervisor - the instance of the hypervisor
9 * @param {Object} opts.container - the container constuctor and argments
10 */
11 constructor (opts) {
12 Object.assign(this, opts)
13
14 this.inbox = []
15 this.ticks = 0
16 this.running = false
17 this.container = new this.Container(this)
18 }
19
20 serializeMetaData () {
21 return Actor.serializeMetaData(this.type, this.nonce)
22 }
23
24 getFuncRef (name) {
25 return {
26 name,
27 destId: this.id
28 }
29 }
30
31 /**
32 * Runs the shutdown routine for the actor
33 */
34 async shutdown () {
35 await this.tree.set(this.id.id, this.serializeMetaData())
36 if (this.storage.length) {
37 const state = await this.tree.get(this.id.id)
38 return this.tree.graph.set(state.root, '2', this.storage)
39 }
40 }
41
42 /**
43 * Runs the startup routine for the actor
44 */
45 startup () {
46 return this.container.onStartup()
47 }
48
49 /**
50 * run the Actor with a given message
51 * @param {object} message - the message to run
52 * @param {String} method - which method to run
53 * @returns {Promise}
54 */
55 async runMessage (message) {
56 if (message._fromTicks > this.ticks) {
57 this.ticks = message._fromTicks
58 }
59 try {
60 this.currentMessage = message
61 await this.container.onMessage(message)
62 } catch (e) {
63 message.emit('execution:error', e)
64 }
65 message.emit('done', this)
66 }
67
68 /**
69 * updates the number of ticks that the actor has run
70 * @param {Number} count - the number of ticks to add
71 */
72 incrementTicks (count) {
73 this.ticks += count
74 }
75
76 /**
77 * creates an actor
78 * @param {Integer} type - the type id for the container
79 * @param {Object} message - an intial [message](https://github.com/primea/js-primea-message) to send newly created actor
80 */
81 createActor (type, code) {
82 const id = this._generateNextId()
83 return this.hypervisor.createActor(type, code, id)
84 }
85
86 _generateNextId () {
87 const id = {
88 nonce: this.nonce,
89 parent: this.id
90 }
91
92 this.nonce++
93 return id
94 }
95
96 /**
97 * sends a message to a given port
98 * @param {Object} portRef - the port
99 * @param {Message} message - the message
100 */
101 send (message) {
102 message._fromTicks = this.ticks
103 message._fromId = this.id
104
105 this.hypervisor.scheduler.queue([message])
106 }
107
108 static serializeMetaData (type, nonce = 0) {
109 return [type, nonce]
110 }
111
112 static deserializeMetaData ([type, nonce]) {
113 return {
114 nonce,
115 type
116 }
117 }
118}
119

Built with git-ssb-web