Skip to content

Commit 9099e95

Browse files
LUAFDN-1706 Add support for devtools (#84)
Co-authored-by: Paul Doyle <[email protected]>
1 parent 7664c16 commit 9099e95

File tree

7 files changed

+151
-17
lines changed

7 files changed

+151
-17
lines changed

.github/workflows/ci.yml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,8 @@ jobs:
6464
selene src
6565
stylua -c src/
6666
67-
- name: install and run darklua
67+
- name: run darklua
6868
run: |
69-
cargo install --git https://gitlab.com/seaofvoices/darklua.git#v0.6.0
7069
darklua process src/ src/ --format retain-lines
7170
7271
- name: Test

docs/advanced/devtools.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
The fifth argument to [`Store.new`](../api-reference.md#storenew) takes a devtools object that you can optionally provide. A devtools object has only two requirements: `devtools.__className` must be `"Devtools"` and `devtools:_hookIntoStore(store)` must be a valid function call. Beyond that, your devtools can be anything you need it to be.
2+
3+
Devtools can be very useful during development in gathering performance data, providing introspection, debugging, etc. We leave the devtools implementation up to the user in order to support any and all use cases, such as store modification in unit testing, live state inspection plugins, and whatever else you come up with.
4+
5+
A simple example of a devtools that profiles and logs:
6+
7+
```Lua
8+
local Devtools = {}
9+
Devtools.__className = "Devtools"
10+
Devtools.__index = Devtools
11+
12+
-- Creates a new Devtools object
13+
function Devtools.new()
14+
local self = setmetatable({
15+
_events = table.create(100),
16+
_eventsIndex = 0,
17+
}, Devtools)
18+
19+
return self
20+
end
21+
22+
-- Overwrites the store's reducer and flushHandler with wrapped versions that contain logging and profiling
23+
function Devtools:_hookIntoStore(store)
24+
self._store = store
25+
self._source = store._source
26+
27+
self._originalReducer = store._reducer
28+
store._reducer = function(state: any, action: any): any
29+
local startClock = os.clock()
30+
local result = self._originalReducer(state, action)
31+
local stopClock = os.clock()
32+
33+
self:_addEvent("Reduce", {
34+
name = action.type or tostring(action),
35+
elapsedMs = (stopClock - startClock) * 1000,
36+
action = action,
37+
state = result,
38+
})
39+
return result
40+
end
41+
42+
self._originalFlushHandler = store._flushHandler
43+
store._flushHandler = function(...)
44+
local startClock = os.clock()
45+
self._originalFlushHandler(...)
46+
local stopClock = os.clock()
47+
48+
self:_addEvent("Flush", {
49+
name = "@@FLUSH",
50+
elapsedMs = (stopClock - startClock) * 1000,
51+
listeners = table.clone(store.changed._listeners),
52+
})
53+
end
54+
end
55+
56+
-- Adds an event to the log
57+
-- Automatically adds event.timestamp and event.source
58+
function Devtools:_addEvent(eventType: "Reduce" | "Flush", props: { [any]: any })
59+
self._eventsIndex = (self._eventsIndex or 0) + 1
60+
self._events[self._eventsIndex] = {
61+
eventType = eventType,
62+
source = self._source,
63+
timestamp = DateTime.now().UnixTimestampMillis,
64+
props = props,
65+
}
66+
end
67+
68+
-- Returns a shallow copy of the event log
69+
function Devtools:GetLoggedEvents()
70+
return table.clone(self._events)
71+
end
72+
```

docs/api-reference.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ The Store class is the core piece of Rodux. It is the state container that you c
55

66
### Store.new
77
```
8-
Store.new(reducer, [initialState, [middlewares, [errorReporter]]]) -> Store
8+
Store.new(reducer, [initialState, [middlewares, [errorReporter, [devtools]]]]) -> Store
99
```
1010

1111
Creates and returns a new Store.
@@ -14,6 +14,7 @@ Creates and returns a new Store.
1414
* `initialState` is the store's initial state. This should be used to load a saved state from storage.
1515
* `middlewares` is a list of [middleware functions](#middleware) to apply each time an action is dispatched to the store.
1616
* `errorReporter` is a [error reporter object](advanced/error-reporters.md) that allows custom handling of errors that occur during different phases of the store's updates
17+
* `devtools` is a [custom object](advanced/devtools.md) that you can provide in order to profile, log, or control the store for testing and debugging purposes
1718

1819
The store will automatically dispatch an initialization action with a `type` of `@@INIT`.
1920

foreman.toml

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
[tools]
2-
rojo = { source = "rojo-rbx/rojo", version = "=7.2.1" }
3-
selene = { source = "Kampfkarren/selene", version = "=0.21.1" }
4-
stylua = { source = "JohnnyMorganz/StyLua", version = "=0.15.1" }
5-
luau-lsp = { source = "JohnnyMorganz/luau-lsp", version = "=1.8.1" }
6-
wally = { source = "UpliftGames/wally", version = "=0.3.1" }
2+
rojo = { source = "rojo-rbx/rojo", version = "=7.3.0" }
3+
selene = { source = "Kampfkarren/selene", version = "=0.25.0" }
4+
stylua = { source = "JohnnyMorganz/StyLua", version = "=0.18.1" }
5+
luau-lsp = { source = "JohnnyMorganz/luau-lsp", version = "=1.23.0" }
6+
wally = { source = "UpliftGames/wally", version = "=0.3.2" }
7+
darklua = { source = "seaofvoices/darklua", version = "=0.10.2"}

src/Store.lua

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,14 @@ Store.__index = Store
3838
Reducers do not mutate the state object, so the original state is still
3939
valid.
4040
]]
41-
function Store.new(reducer, initialState, middlewares, errorReporter)
41+
function Store.new(reducer, initialState, middlewares, errorReporter, devtools)
4242
assert(typeof(reducer) == "function", "Bad argument #1 to Store.new, expected function.")
4343
assert(middlewares == nil or typeof(middlewares) == "table", "Bad argument #3 to Store.new, expected nil or table.")
44+
assert(
45+
devtools == nil or (typeof(devtools) == "table" and devtools.__className == "Devtools"),
46+
"Bad argument #5 to Store.new, expected nil or Devtools object."
47+
)
48+
4449
if middlewares ~= nil then
4550
for i = 1, #middlewares, 1 do
4651
assert(
@@ -51,16 +56,31 @@ function Store.new(reducer, initialState, middlewares, errorReporter)
5156
end
5257

5358
local self = {}
54-
59+
self._source = string.match(debug.traceback(), "^.-\n(.-)\n")
5560
self._errorReporter = errorReporter or rethrowErrorReporter
5661
self._isDispatching = false
62+
self._lastState = nil
63+
self.changed = Signal.new(self)
64+
5765
self._reducer = reducer
66+
self._flushHandler = function(state)
67+
self.changed:fire(state, self._lastState)
68+
end
69+
70+
if devtools then
71+
self._devtools = devtools
72+
73+
-- Devtools can wrap & overwrite self._reducer and self._flushHandler
74+
-- to log and profile the store
75+
devtools:_hookIntoStore(self)
76+
end
77+
5878
local initAction = {
5979
type = "@@INIT",
6080
}
6181
self._actionLog = { initAction }
6282
local ok, result = xpcall(function()
63-
self._state = reducer(initialState, initAction)
83+
self._state = self._reducer(initialState, initAction)
6484
end, tracebackReporter)
6585
if not ok then
6686
self._errorReporter.reportReducerError(initialState, initAction, {
@@ -74,8 +94,6 @@ function Store.new(reducer, initialState, middlewares, errorReporter)
7494
self._mutatedSinceFlush = false
7595
self._connections = {}
7696

77-
self.changed = Signal.new(self)
78-
7997
setmetatable(self, Store)
8098

8199
local connection = self._flushEvent:Connect(function()
@@ -194,9 +212,7 @@ function Store:flush()
194212
local ok, errorResult = xpcall(function()
195213
-- If a changed listener yields, *very* surprising bugs can ensue.
196214
-- Because of that, changed listeners cannot yield.
197-
NoYield(function()
198-
self.changed:fire(state, self._lastState)
199-
end)
215+
NoYield(self._flushHandler, state)
200216
end, tracebackReporter)
201217

202218
if not ok then

src/Store.spec.lua

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,51 @@ return function()
3535
store:destruct()
3636
end)
3737

38+
it("should instantiate with a reducer, initial state, middlewares, and devtools", function()
39+
local devtools = {}
40+
devtools.__className = "Devtools"
41+
function devtools:_hookIntoStore(store) end
42+
43+
local store = Store.new(function(state, action)
44+
return state
45+
end, "initial state", {}, nil, devtools)
46+
47+
expect(store).to.be.ok()
48+
expect(store:getState()).to.equal("initial state")
49+
50+
store:destruct()
51+
end)
52+
53+
it("should validate devtools argument", function()
54+
local success, err = pcall(function()
55+
Store.new(function(state, action)
56+
return state
57+
end, "initial state", {}, nil, "INVALID_DEVTOOLS")
58+
end)
59+
60+
expect(success).to.equal(false)
61+
expect(string.match(err, "Bad argument #5 to Store.new, expected nil or Devtools object.")).to.be.ok()
62+
end)
63+
64+
it("should call devtools:_hookIntoStore", function()
65+
local hooked = nil
66+
local devtools = {}
67+
devtools.__className = "Devtools"
68+
function devtools:_hookIntoStore(store)
69+
hooked = store
70+
end
71+
72+
local store = Store.new(function(state, action)
73+
return state
74+
end, "initial state", {}, nil, devtools)
75+
76+
expect(store).to.be.ok()
77+
expect(store:getState()).to.equal("initial state")
78+
expect(hooked).to.equal(store)
79+
80+
store:destruct()
81+
end)
82+
3883
it("should modify the dispatch method when middlewares are passed", function()
3984
local middlewareInstantiateCount = 0
4085
local middlewareInvokeCount = 0

src/types/actions.lua

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export type AnyAction = {
99

1010
export type ActionCreator<Type, Payload, Args...> = typeof(setmetatable(
1111
{} :: { name: Type },
12-
{} :: { __call: (any, Args...) -> (Payload & Action<Type>) }
12+
{} :: { __call: (any, Args...) -> Payload & Action<Type> }
1313
))
1414

1515
return nil

0 commit comments

Comments
 (0)