git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: b9423af2cd45a86722df9ab973b4db265a8fcaa3

Files: b9423af2cd45a86722df9ab973b4db265a8fcaa3 / actor.js

2399 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 /**
21 * Runs the shutdown routine for the actor
22 */
23 async shutdown () {
24 await this.tree.set(this.id.id, [this.type, this.nonce])
25 const state = await this.tree.get(this.id.id)
26 return this.tree.graph.set(state.root, '2', this.storage)
27 }
28
29 /**
30 * Runs the startup routine for the actor
31 */
32 startup () {
33 return this.container.onStartup()
34 }
35
36 /**
37 * run the Actor with a given message
38 * @param {object} message - the message to run
39 * @param {String} method - which method to run
40 * @returns {Promise}
41 */
42 async runMessage (message) {
43 if (message._fromTicks > this.ticks) {
44 this.ticks = message._fromTicks
45 }
46 try {
47 this.currentMessage = message
48 await this.container.onMessage(message)
49 } catch (e) {
50 message.emit('execution:error', e)
51 }
52 message.emit('done', this)
53 }
54
55 /**
56 * updates the number of ticks that the actor has run
57 * @param {Number} count - the number of ticks to add
58 */
59 incrementTicks (count) {
60 this.ticks += count
61 }
62
63 /**
64 * creates an actor
65 * @param {Integer} type - the type id for the container
66 * @param {Object} message - an intial [message](https://github.com/primea/js-primea-message) to send newly created actor
67 */
68 createActor (type, code) {
69 const id = this._generateNextId()
70 return this.hypervisor.createActor(type, code, id)
71 }
72
73 _generateNextId () {
74 const id = {
75 nonce: this.nonce,
76 parent: this.id
77 }
78
79 this.nonce++
80 return id
81 }
82
83 /**
84 * sends a message to a given port
85 * @param {Object} portRef - the port
86 * @param {Message} message - the message
87 */
88 send (message) {
89 message._fromTicks = this.ticks
90 message._fromId = this.id
91
92 this.hypervisor.scheduler.queue([message])
93 }
94}
95

Built with git-ssb-web