canvas: asynchronous drawImage speeds up execution but causes serious memory leaks.

// this is pmap status
0000000000400000    7644    3104       0 r---- node
0000000000b77000       8       8       0 r-x-- node
0000000000b7a000   27296   13892       0 r-x-- node
0000000002800000       4       0       0 r-x-- node
0000000002801000   46796    8980       0 r---- node
00000000055b4000      16      16       8 r---- node
00000000055b8000     124     108      92 rw--- node
00000000055d7000     180     168     168 rw---   [ anon ]
00000000075e0000 5697364 5697132 5697132 rw---   [ anon ]
00000266d94c0000     256     256     256 rw---   [ anon ]
0000033e93480000     256       8       8 rw---   [ anon ]
0000036b35cc0000     256     256     256 rw---   [ anon ]
0000039136800000     256     256     256 rw---   [ anon ]
000003f309900000     256     256     256 rw---   [ anon ]
000004103ff00000     256     256     256 rw---   [ anon ]

image The memory does not automatically drop to normal levels, even though I have enabled GC and cleared all cache.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 26 (14 by maintainers)

Most upvoted comments

same here, memory leaks still exist on 0.1.59

I tested 0.1.58 on my server, the same result. The memory did not released until my server got a maxMemoryUsage crash

@Brooooooklyn amazing!! the 0.1.60 significantly alleviated memory issues. image


However, when I tested with a sample size of 50, I found that although the memory usage decreased significantly compared to version 0.1.59, it still exhibits noticeable slowdowns and some memory is not released. image From the above image, it can be seen that 2GB of memory has been reclaimed, but there is still 2GB that has not been reclaimed for a long time.


However, when I start expose-gc, the memory recovery is particularly noticeable. image

there is my envinfo

  System:
    OS: Linux 3.10 Ubuntu 22.04.1 LTS 22.04.1 LTS (Jammy Jellyfish)
    CPU: (16) x64 Intel Xeon Processor (Cascadelake)
    Memory: 22.42 GB / 31.42 GB
    Container: Yes
    Shell: 5.1.16 - /bin/bash
  Binaries:
    Node: 20.14.0 - /usr/bin/node
    npm: 10.7.0 - /usr/bin/npm

@Brooooooklyn Looks good. My initial tests seem to confirm that the leak is fixed in 0.1.60. I’ve used the same script to test and I can’t find any memory at the moment.

Screenshot 2024-11-10 022211

@rambo-panda your memory leak was caused by then((a) => a.arrayBuffer()).then(Buffer.from), not from @napi-rs/canvas

@Brooooooklyn sorry, I didn’t understand. Even if I try to download the image locally and then use fs.readFileSync to read it before performing the loadImage operation, the RSS still remains high for a long time.

I had also modified Panda’s script by logging the RSS by default before logging it at intervals At the beginning, it reported 61-62MB of usage, which is normal But after that, it stayed stuck at 90MB Normally, after clearing the constant named res that holds all the loadImage instances, it should have gone back down to around 65MB, or maybe 70MB if some compiled code was added to the RSS during execution However, that’s not the case The amount of RAM used by the ArrayBuffer generated by loadImage increases proportionally and exponentially each time the script is called

If I reuse the script from @rambo-panda , the fix doesn’t seem to work

Why do you think it doesn’t work? The memoryUsage.rss() can not be 0.

Because in my script I generate GIFs (around 5 each time) Each frame has about 10 to 20 loadImage() calls, and each GIF has between 5 and 10 frames When I run this script three times, my 8GB of RAM gets maxed out, and Ubuntu starts using swap, if the server doesn’t crash

However, the script is written in TypeScript, so the promises are properly resolved I reused Panda’s script to better illustrate the issue

But in Chrome’s inspector, when using the --inspect flag, you can clearly see that ArrayBuffer instances keep growing and are never purged The only way to clean them up is to stop the script or wait for the server to crash Alternatively with PM2, I can set a memory usage limit so that PM2 automatically restarts the process

If I reuse the script from @rambo-panda , the fix doesn’t seem to work {10173544-F76D-4EF7-B4A2-DE65DCB9A889}

@Brooooooklyn Hello, excuse me for asking, but what version of rustc are you using for the compilation? I’ve been using a Docker container created on my home computer, and I find it unable to compile properly.

image

npm run build error log

warning: use of deprecated struct `napi::JsBuffer`: Please use Buffer or &[u8] instead
  --> src/svg.rs:11:13
   |
11 | ) -> Result<JsBuffer> {
   |             ^^^^^^^^

error[E0308]: `?` operator has incompatible types
   --> src/image.rs:242:17
    |
242 |       this_ref: env.create_reference(&this)?,
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Ref<()>`, found `Ref<JsObject>`
    |
    = note: `?` operator cannot convert from `napi::Ref<JsObject>` to `napi::Ref<()>`
    = note: expected struct `napi::Ref<()>`
               found struct `napi::Ref<JsObject>`

error[E0277]: the trait bound `(): napi::NapiValue` is not satisfied
   --> src/image.rs:426:46
    |
426 |     let this: This = env.get_reference_value(&self.this_ref)?;
    |                          ------------------- ^^^^^^^^^^^^^^ the trait `napi::NapiValue` is not implemented for `()`
    |                          |
    |                          required by a bound introduced by this call
    |
    = help: the following other types implement trait `napi::NapiValue`:
              JsArrayBuffer
              JsBoolean
              JsDataView
              JsExternal
              JsFunction
              JsGlobal
              JsNull
              JsNumber
            and 9 others
note: required by a bound in `napi::Env::get_reference_value`
   --> /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/napi-3.0.0-alpha.9/src/env.rs:884:8
    |
882 |   pub fn get_reference_value<T>(&self, reference: &Ref<T>) -> Result<T>
    |          ------------------- required by a bound in this associated function
883 |   where
884 |     T: NapiValue,
    |        ^^^^^^^^^ required by this bound in `Env::get_reference_value`

error[E0308]: `?` operator has incompatible types
   --> src/image.rs:426:22
    |
426 |     let this: This = env.get_reference_value(&self.this_ref)?;
    |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `JsObject`, found `()`
    |
    = note: `?` operator cannot convert from `()` to `JsObject`

warning: unused import: `NapiRaw`
 --> src/image.rs:5:46
  |
5 | use napi::{bindgen_prelude::*, check_status, NapiRaw, NapiValue, Ref};
  |                                              ^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

Some errors have detailed explanations: E0277, E0308.
For more information about an error, try `rustc --explain E0277`.
warning: `canvas` (lib) generated 9 warnings
The following warnings were emitted during compilation:

warning: canvas@0.1.0: skia-c/skia_c.cpp:455:19: warning: variable length arrays in C++ are a Clang extension [-Wvla-cxx-extension]
warning: canvas@0.1.0:   455 |     SkRect bounds[text_len];
warning: canvas@0.1.0:       |                   ^~~~~~~~
warning: canvas@0.1.0: skia-c/skia_c.cpp:455:19: note: function parameter 'text_len' with unknown value cannot be used in a constant expression
warning: canvas@0.1.0: skia-c/skia_c.cpp:398:14: note: declared here
warning: canvas@0.1.0:   398 |       size_t text_len,
warning: canvas@0.1.0:       |              ^
warning: canvas@0.1.0: 1 warning generated.

error: could not compile `canvas` (lib) due to 3 previous errors; 9 warnings emitted