@eduardo191labs/watcher 0.0.0-stage → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CMakeLists.txt +82 -0
  2. package/LICENSE +21 -0
  3. package/README.md +135 -2
  4. package/binding.gyp +125 -0
  5. package/index.d.ts +49 -0
  6. package/index.js +55 -0
  7. package/index.js.flow +45 -0
  8. package/package.json +61 -3
  9. package/scripts/build-from-source.js +16 -0
  10. package/src/Backend.cc +186 -0
  11. package/src/Backend.hh +37 -0
  12. package/src/Debounce.cc +113 -0
  13. package/src/Debounce.hh +49 -0
  14. package/src/DirTree.cc +164 -0
  15. package/src/DirTree.hh +50 -0
  16. package/src/Event.hh +109 -0
  17. package/src/Glob.cc +22 -0
  18. package/src/Glob.hh +34 -0
  19. package/src/PromiseRunner.hh +101 -0
  20. package/src/Signal.hh +46 -0
  21. package/src/Watcher.cc +241 -0
  22. package/src/Watcher.hh +73 -0
  23. package/src/binding.cc +268 -0
  24. package/src/kqueue/KqueueBackend.cc +306 -0
  25. package/src/kqueue/KqueueBackend.hh +35 -0
  26. package/src/linux/InotifyBackend.cc +236 -0
  27. package/src/linux/InotifyBackend.hh +34 -0
  28. package/src/macos/FSEventsBackend.cc +338 -0
  29. package/src/macos/FSEventsBackend.hh +20 -0
  30. package/src/shared/BruteForceBackend.cc +41 -0
  31. package/src/shared/BruteForceBackend.hh +25 -0
  32. package/src/unix/fts.cc +50 -0
  33. package/src/unix/legacy.cc +77 -0
  34. package/src/wasm/WasmBackend.cc +132 -0
  35. package/src/wasm/WasmBackend.hh +34 -0
  36. package/src/wasm/include.h +74 -0
  37. package/src/watchman/BSER.cc +302 -0
  38. package/src/watchman/BSER.hh +69 -0
  39. package/src/watchman/IPC.hh +175 -0
  40. package/src/watchman/WatchmanBackend.cc +342 -0
  41. package/src/watchman/WatchmanBackend.hh +35 -0
  42. package/src/windows/WindowsBackend.cc +282 -0
  43. package/src/windows/WindowsBackend.hh +18 -0
  44. package/src/windows/win_utils.cc +44 -0
  45. package/src/windows/win_utils.hh +11 -0
  46. package/wrapper.js +88 -0
@@ -0,0 +1,69 @@
1
+ #ifndef BSER_H
2
+ #define BSER_H
3
+
4
+ #include <string>
5
+ #include <sstream>
6
+ #include <vector>
7
+ #include <unordered_map>
8
+ #include <memory>
9
+
10
+ enum BSERType {
11
+ BSER_ARRAY = 0x00,
12
+ BSER_OBJECT = 0x01,
13
+ BSER_STRING = 0x02,
14
+ BSER_INT8 = 0x03,
15
+ BSER_INT16 = 0x04,
16
+ BSER_INT32 = 0x05,
17
+ BSER_INT64 = 0x06,
18
+ BSER_REAL = 0x07,
19
+ BSER_BOOL_TRUE = 0x08,
20
+ BSER_BOOL_FALSE = 0x09,
21
+ BSER_NULL = 0x0a,
22
+ BSER_TEMPLATE = 0x0b
23
+ };
24
+
25
+ class BSERValue;
26
+
27
+ class BSER {
28
+ public:
29
+ typedef std::vector<BSER> Array;
30
+ typedef std::unordered_map<std::string, BSER> Object;
31
+
32
+ BSER();
33
+ BSER(BSER::Array value);
34
+ BSER(BSER::Object value);
35
+ BSER(std::string value);
36
+ BSER(const char *value);
37
+ BSER(int64_t value);
38
+ BSER(double value);
39
+ BSER(bool value);
40
+ BSER(std::istream &iss);
41
+
42
+ BSER::Array arrayValue();
43
+ BSER::Object objectValue();
44
+ std::string stringValue();
45
+ int64_t intValue();
46
+ double doubleValue();
47
+ bool boolValue();
48
+ void encode(std::ostream &oss);
49
+
50
+ static int64_t decodeLength(std::istream &iss);
51
+ std::string encode();
52
+ private:
53
+ std::shared_ptr<BSERValue> m_ptr;
54
+ };
55
+
56
+ class BSERValue {
57
+ protected:
58
+ friend class BSER;
59
+ virtual BSER::Array arrayValue() { return BSER::Array(); }
60
+ virtual BSER::Object objectValue() { return BSER::Object(); }
61
+ virtual std::string stringValue() { return std::string(); }
62
+ virtual int64_t intValue() { return 0; }
63
+ virtual double doubleValue() { return 0; }
64
+ virtual bool boolValue() { return false; }
65
+ virtual void encode(std::ostream &oss) {}
66
+ virtual ~BSERValue() {}
67
+ };
68
+
69
+ #endif
@@ -0,0 +1,175 @@
1
+ #ifndef IPC_H
2
+ #define IPC_H
3
+
4
+ #include <string>
5
+ #include <stdlib.h>
6
+
7
+ #ifdef _WIN32
8
+ #include <winsock2.h>
9
+ #include <windows.h>
10
+ #else
11
+ #include <unistd.h>
12
+ #include <sys/socket.h>
13
+ #include <sys/un.h>
14
+ #endif
15
+
16
+ class IPC {
17
+ public:
18
+ IPC(std::string path) {
19
+ mStopped = false;
20
+ #ifdef _WIN32
21
+ while (true) {
22
+ mPipe = CreateFile(
23
+ path.data(), // pipe name
24
+ GENERIC_READ | GENERIC_WRITE, // read and write access
25
+ 0, // no sharing
26
+ NULL, // default security attributes
27
+ OPEN_EXISTING, // opens existing pipe
28
+ FILE_FLAG_OVERLAPPED, // attributes
29
+ NULL // no template file
30
+ );
31
+
32
+ if (mPipe != INVALID_HANDLE_VALUE) {
33
+ break;
34
+ }
35
+
36
+ if (GetLastError() != ERROR_PIPE_BUSY) {
37
+ throw std::runtime_error("Could not open pipe");
38
+ }
39
+
40
+ // Wait for pipe to become available if it is busy
41
+ if (!WaitNamedPipe(path.data(), 30000)) {
42
+ throw std::runtime_error("Error waiting for pipe");
43
+ }
44
+ }
45
+
46
+ mReader = CreateEvent(NULL, true, false, NULL);
47
+ mWriter = CreateEvent(NULL, true, false, NULL);
48
+ #else
49
+ struct sockaddr_un addr;
50
+ memset(&addr, 0, sizeof(addr));
51
+ addr.sun_family = AF_UNIX;
52
+ strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
53
+
54
+ mSock = socket(AF_UNIX, SOCK_STREAM, 0);
55
+ if (connect(mSock, (struct sockaddr *) &addr, sizeof(struct sockaddr_un))) {
56
+ throw std::runtime_error("Error connecting to socket");
57
+ }
58
+ #endif
59
+ }
60
+
61
+ ~IPC() {
62
+ mStopped = true;
63
+ #ifdef _WIN32
64
+ CancelIo(mPipe);
65
+ CloseHandle(mPipe);
66
+ CloseHandle(mReader);
67
+ CloseHandle(mWriter);
68
+ #else
69
+ shutdown(mSock, SHUT_RDWR);
70
+ #endif
71
+ }
72
+
73
+ void write(std::string buf) {
74
+ #ifdef _WIN32
75
+ OVERLAPPED overlapped;
76
+ overlapped.hEvent = mWriter;
77
+ bool success = WriteFile(
78
+ mPipe, // pipe handle
79
+ buf.data(), // message
80
+ static_cast<DWORD>(buf.size()), // message length
81
+ NULL, // bytes written
82
+ &overlapped // overlapped
83
+ );
84
+
85
+ if (mStopped) {
86
+ return;
87
+ }
88
+
89
+ if (!success) {
90
+ if (GetLastError() != ERROR_IO_PENDING) {
91
+ throw std::runtime_error("Write error");
92
+ }
93
+ }
94
+
95
+ DWORD written;
96
+ success = GetOverlappedResult(mPipe, &overlapped, &written, true);
97
+ if (!success) {
98
+ throw std::runtime_error("GetOverlappedResult failed");
99
+ }
100
+
101
+ if (written != buf.size()) {
102
+ throw std::runtime_error("Wrong number of bytes written");
103
+ }
104
+ #else
105
+ int r = 0;
106
+ for (unsigned int i = 0; i != buf.size(); i += r) {
107
+ r = ::write(mSock, &buf[i], buf.size() - i);
108
+ if (r == -1) {
109
+ if (errno == EAGAIN) {
110
+ r = 0;
111
+ } else if (mStopped) {
112
+ return;
113
+ } else {
114
+ throw std::runtime_error("Write error");
115
+ }
116
+ }
117
+ }
118
+ #endif
119
+ }
120
+
121
+ int read(char *buf, size_t len) {
122
+ #ifdef _WIN32
123
+ OVERLAPPED overlapped;
124
+ overlapped.hEvent = mReader;
125
+ bool success = ReadFile(
126
+ mPipe, // pipe handle
127
+ buf, // buffer to receive reply
128
+ static_cast<DWORD>(len), // size of buffer
129
+ NULL, // number of bytes read
130
+ &overlapped // overlapped
131
+ );
132
+
133
+ if (!success && !mStopped) {
134
+ if (GetLastError() != ERROR_IO_PENDING) {
135
+ throw std::runtime_error("Read error");
136
+ }
137
+ }
138
+
139
+ DWORD read = 0;
140
+ success = GetOverlappedResult(mPipe, &overlapped, &read, true);
141
+ if (!success && !mStopped) {
142
+ throw std::runtime_error("GetOverlappedResult failed");
143
+ }
144
+
145
+ return read;
146
+ #else
147
+ int r = ::read(mSock, buf, len);
148
+ if (r == 0 && !mStopped) {
149
+ throw std::runtime_error("Socket ended unexpectedly");
150
+ }
151
+
152
+ if (r < 0) {
153
+ if (mStopped) {
154
+ return 0;
155
+ }
156
+
157
+ throw std::runtime_error(strerror(errno));
158
+ }
159
+
160
+ return r;
161
+ #endif
162
+ }
163
+
164
+ private:
165
+ bool mStopped;
166
+ #ifdef _WIN32
167
+ HANDLE mPipe;
168
+ HANDLE mReader;
169
+ HANDLE mWriter;
170
+ #else
171
+ int mSock;
172
+ #endif
173
+ };
174
+
175
+ #endif
@@ -0,0 +1,342 @@
1
+ #include <string>
2
+ #include <fstream>
3
+ #include <stdlib.h>
4
+ #include <algorithm>
5
+ #include "../DirTree.hh"
6
+ #include "../Event.hh"
7
+ #include "./BSER.hh"
8
+ #include "./WatchmanBackend.hh"
9
+
10
+ #ifdef _WIN32
11
+ #include "../windows/win_utils.hh"
12
+ #define S_ISDIR(mode) ((mode & _S_IFDIR) == _S_IFDIR)
13
+ #define popen _popen
14
+ #define pclose _pclose
15
+ #else
16
+ #include <sys/stat.h>
17
+ #define normalizePath(dir) dir
18
+ #endif
19
+
20
+ template<typename T>
21
+ BSER readBSER(T &&do_read) {
22
+ std::stringstream oss;
23
+ char buffer[256];
24
+ size_t r;
25
+ int64_t len = -1;
26
+ do {
27
+ // Start by reading a minimal amount of data in order to decode the length.
28
+ // After that, attempt to read the remaining length, up to the buffer size.
29
+ r = do_read(buffer, len == -1 ? 20 : (len < 256 ? len : 256));
30
+ oss << std::string(buffer, r);
31
+
32
+ if (len == -1) {
33
+ uint64_t l = BSER::decodeLength(oss);
34
+ len = l + oss.tellg();
35
+ }
36
+
37
+ len -= r;
38
+ } while (len > 0);
39
+
40
+ return BSER(oss);
41
+ }
42
+
43
+ std::string getSockPath() {
44
+ auto var = getenv("WATCHMAN_SOCK");
45
+ if (var && *var) {
46
+ return std::string(var);
47
+ }
48
+
49
+ #ifdef _WIN32
50
+ FILE *fp = popen("watchman --output-encoding=bser get-sockname", "r");
51
+ #else
52
+ FILE *fp = popen("watchman --output-encoding=bser get-sockname 2>/dev/null", "r");
53
+ #endif
54
+ if (fp == NULL || errno == ECHILD) {
55
+ throw std::runtime_error("Failed to execute watchman");
56
+ }
57
+
58
+ BSER b = readBSER([fp] (char *buf, size_t len) {
59
+ return fread(buf, sizeof(char), len, fp);
60
+ });
61
+
62
+ pclose(fp);
63
+
64
+ auto objValue = b.objectValue();
65
+ auto foundSockname = objValue.find("sockname");
66
+ if (foundSockname == objValue.end()) {
67
+ throw std::runtime_error("sockname not found");
68
+ }
69
+ return foundSockname->second.stringValue();
70
+ }
71
+
72
+ std::unique_ptr<IPC> watchmanConnect() {
73
+ std::string path = getSockPath();
74
+ return std::unique_ptr<IPC>(new IPC(path));
75
+ }
76
+
77
+ BSER watchmanRead(IPC *ipc) {
78
+ return readBSER([ipc] (char *buf, size_t len) {
79
+ return ipc->read(buf, len);
80
+ });
81
+ }
82
+
83
+ BSER::Object WatchmanBackend::watchmanRequest(BSER b) {
84
+ std::string cmd = b.encode();
85
+ mIPC->write(cmd);
86
+ mRequestSignal.notify();
87
+
88
+ mResponseSignal.wait();
89
+ mResponseSignal.reset();
90
+
91
+ if (!mError.empty()) {
92
+ std::runtime_error err = std::runtime_error(mError);
93
+ mError = std::string();
94
+ throw err;
95
+ }
96
+
97
+ return mResponse;
98
+ }
99
+
100
+ void WatchmanBackend::watchmanWatch(std::string dir) {
101
+ std::vector<BSER> cmd;
102
+ cmd.push_back("watch");
103
+ cmd.push_back(normalizePath(dir));
104
+ watchmanRequest(cmd);
105
+ }
106
+
107
+ bool WatchmanBackend::checkAvailable() {
108
+ try {
109
+ watchmanConnect();
110
+ return true;
111
+ } catch (std::exception&) {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ void handleFiles(WatcherRef watcher, BSER::Object obj) {
117
+ auto found = obj.find("files");
118
+ if (found == obj.end()) {
119
+ throw WatcherError("Error reading changes from watchman", watcher);
120
+ }
121
+
122
+ auto files = found->second.arrayValue();
123
+ for (auto it = files.begin(); it != files.end(); it++) {
124
+ auto file = it->objectValue();
125
+ auto name = file.find("name")->second.stringValue();
126
+ #ifdef _WIN32
127
+ std::replace(name.begin(), name.end(), '/', '\\');
128
+ #endif
129
+ auto mode = file.find("mode")->second.intValue();
130
+ auto isNew = file.find("new")->second.boolValue();
131
+ auto exists = file.find("exists")->second.boolValue();
132
+ auto path = watcher->mDir + DIR_SEP + name;
133
+ if (watcher->isIgnored(path)) {
134
+ continue;
135
+ }
136
+
137
+ if (isNew && exists) {
138
+ watcher->mEvents.create(path);
139
+ } else if (exists && !S_ISDIR(mode)) {
140
+ watcher->mEvents.update(path);
141
+ } else if (!isNew && !exists) {
142
+ watcher->mEvents.remove(path);
143
+ }
144
+ }
145
+ }
146
+
147
+ void WatchmanBackend::handleSubscription(BSER::Object obj) {
148
+ std::unique_lock<std::mutex> lock(mMutex);
149
+ auto subscription = obj.find("subscription")->second.stringValue();
150
+ auto it = mSubscriptions.find(subscription);
151
+ if (it == mSubscriptions.end()) {
152
+ return;
153
+ }
154
+
155
+ auto watcher = it->second;
156
+ try {
157
+ handleFiles(watcher, obj);
158
+ watcher->notify();
159
+ } catch (WatcherError &err) {
160
+ handleWatcherError(err);
161
+ }
162
+ }
163
+
164
+ void WatchmanBackend::start() {
165
+ mIPC = watchmanConnect();
166
+ notifyStarted();
167
+
168
+ while (true) {
169
+ // If there are no subscriptions we are reading, wait for a request.
170
+ if (mSubscriptions.size() == 0) {
171
+ mRequestSignal.wait();
172
+ mRequestSignal.reset();
173
+ }
174
+
175
+ // Break out of loop if we are stopped.
176
+ if (mStopped) {
177
+ break;
178
+ }
179
+
180
+ // Attempt to read from the socket.
181
+ // If there is an error and we are stopped, break.
182
+ BSER b;
183
+ try {
184
+ b = watchmanRead(&*mIPC);
185
+ } catch (std::exception &err) {
186
+ if (mStopped) {
187
+ break;
188
+ } else if (mResponseSignal.isWaiting()) {
189
+ mError = err.what();
190
+ mResponseSignal.notify();
191
+ } else {
192
+ // Throwing causes the backend to be destroyed, but we never reach the code below to notify the signal
193
+ mEndedSignal.notify();
194
+ throw;
195
+ }
196
+ }
197
+
198
+ auto obj = b.objectValue();
199
+ auto error = obj.find("error");
200
+ if (error != obj.end()) {
201
+ mError = error->second.stringValue();
202
+ mResponseSignal.notify();
203
+ continue;
204
+ }
205
+
206
+ // If this message is for a subscription, handle it, otherwise notify the request.
207
+ auto subscription = obj.find("subscription");
208
+ if (subscription != obj.end()) {
209
+ handleSubscription(obj);
210
+ } else {
211
+ mResponse = obj;
212
+ mResponseSignal.notify();
213
+ }
214
+ }
215
+
216
+ mEndedSignal.notify();
217
+ }
218
+
219
+ WatchmanBackend::~WatchmanBackend() {
220
+ // Mark the watcher as stopped, close the socket, and trigger the lock.
221
+ // This will cause the read loop to be broken and the thread to exit.
222
+ mStopped = true;
223
+ mIPC.reset();
224
+ mRequestSignal.notify();
225
+
226
+ // If not ended yet, wait.
227
+ mEndedSignal.wait();
228
+ }
229
+
230
+ std::string WatchmanBackend::clock(WatcherRef watcher) {
231
+ BSER::Array cmd;
232
+ cmd.push_back("clock");
233
+ cmd.push_back(normalizePath(watcher->mDir));
234
+
235
+ BSER::Object obj = watchmanRequest(cmd);
236
+ auto found = obj.find("clock");
237
+ if (found == obj.end()) {
238
+ throw WatcherError("Error reading clock from watchman", watcher);
239
+ }
240
+
241
+ return found->second.stringValue();
242
+ }
243
+
244
+ void WatchmanBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) {
245
+ std::unique_lock<std::mutex> lock(mMutex);
246
+ watchmanWatch(watcher->mDir);
247
+
248
+ std::ofstream ofs(*snapshotPath);
249
+ ofs << clock(watcher);
250
+ }
251
+
252
+ void WatchmanBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) {
253
+ std::unique_lock<std::mutex> lock(mMutex);
254
+ std::ifstream ifs(*snapshotPath);
255
+ if (ifs.fail()) {
256
+ return;
257
+ }
258
+
259
+ watchmanWatch(watcher->mDir);
260
+
261
+ std::string clock;
262
+ ifs >> clock;
263
+
264
+ BSER::Array cmd;
265
+ cmd.push_back("since");
266
+ cmd.push_back(normalizePath(watcher->mDir));
267
+ cmd.push_back(clock);
268
+
269
+ BSER::Object obj = watchmanRequest(cmd);
270
+ handleFiles(watcher, obj);
271
+ }
272
+
273
+ std::string getId(WatcherRef watcher) {
274
+ std::ostringstream id;
275
+ id << "parcel-";
276
+ id << static_cast<void*>(watcher.get());
277
+ return id.str();
278
+ }
279
+
280
+ // This function is called by Backend::watch which takes a lock on mMutex
281
+ void WatchmanBackend::subscribe(WatcherRef watcher) {
282
+ watchmanWatch(watcher->mDir);
283
+
284
+ std::string id = getId(watcher);
285
+ BSER::Array cmd;
286
+ cmd.push_back("subscribe");
287
+ cmd.push_back(normalizePath(watcher->mDir));
288
+ cmd.push_back(id);
289
+
290
+ BSER::Array fields;
291
+ fields.push_back("name");
292
+ fields.push_back("mode");
293
+ fields.push_back("exists");
294
+ fields.push_back("new");
295
+
296
+ BSER::Object opts;
297
+ opts.emplace("fields", fields);
298
+ opts.emplace("since", clock(watcher));
299
+
300
+ if (watcher->mIgnorePaths.size() > 0) {
301
+ BSER::Array ignore;
302
+ BSER::Array anyOf;
303
+ anyOf.push_back("anyof");
304
+
305
+ for (auto it = watcher->mIgnorePaths.begin(); it != watcher->mIgnorePaths.end(); it++) {
306
+ std::string pathStart = watcher->mDir + DIR_SEP;
307
+ if (it->rfind(pathStart, 0) == 0) {
308
+ auto relative = it->substr(pathStart.size());
309
+ BSER::Array dirname;
310
+ dirname.push_back("dirname");
311
+ dirname.push_back(relative);
312
+ anyOf.push_back(dirname);
313
+ }
314
+ }
315
+
316
+ ignore.push_back("not");
317
+ ignore.push_back(anyOf);
318
+
319
+ opts.emplace("expression", ignore);
320
+ }
321
+
322
+ cmd.push_back(opts);
323
+ watchmanRequest(cmd);
324
+
325
+ mSubscriptions.emplace(id, watcher);
326
+ mRequestSignal.notify();
327
+ }
328
+
329
+ // This function is called by Backend::unwatch which takes a lock on mMutex
330
+ void WatchmanBackend::unsubscribe(WatcherRef watcher) {
331
+ std::string id = getId(watcher);
332
+ auto erased = mSubscriptions.erase(id);
333
+
334
+ if (erased) {
335
+ BSER::Array cmd;
336
+ cmd.push_back("unsubscribe");
337
+ cmd.push_back(normalizePath(watcher->mDir));
338
+ cmd.push_back(id);
339
+
340
+ watchmanRequest(cmd);
341
+ }
342
+ }
@@ -0,0 +1,35 @@
1
+ #ifndef WATCHMAN_H
2
+ #define WATCHMAN_H
3
+
4
+ #include "../Backend.hh"
5
+ #include "./BSER.hh"
6
+ #include "../Signal.hh"
7
+ #include "./IPC.hh"
8
+
9
+ class WatchmanBackend : public Backend {
10
+ public:
11
+ static bool checkAvailable();
12
+ void start() override;
13
+ WatchmanBackend() : mStopped(false) {};
14
+ ~WatchmanBackend();
15
+ void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override;
16
+ void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override;
17
+ void subscribe(WatcherRef watcher) override;
18
+ void unsubscribe(WatcherRef watcher) override;
19
+ private:
20
+ std::unique_ptr<IPC> mIPC;
21
+ Signal mRequestSignal;
22
+ Signal mResponseSignal;
23
+ BSER::Object mResponse;
24
+ std::string mError;
25
+ std::unordered_map<std::string, WatcherRef> mSubscriptions;
26
+ bool mStopped;
27
+ Signal mEndedSignal;
28
+
29
+ std::string clock(WatcherRef watcher);
30
+ void watchmanWatch(std::string dir);
31
+ BSER::Object watchmanRequest(BSER cmd);
32
+ void handleSubscription(BSER::Object obj);
33
+ };
34
+
35
+ #endif