git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 1f8affb407f9413e9af400e3cc7408ece8274347

Files: 1f8affb407f9413e9af400e3cc7408ece8274347 / actor.js

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

Built with git-ssb-web