git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 21960d62467278cd5659e2eb5f80cc6ddd87e663

Files: 21960d62467278cd5659e2eb5f80cc6ddd87e663 / actor.js

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

Built with git-ssb-web