Skip to content

Commit

Permalink
[WiP] Experiment with running on Cloudflare Workers
Browse files Browse the repository at this point in the history
  • Loading branch information
kleisauke committed Feb 3, 2025
1 parent f3255fb commit bab3b03
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
endif()

set(ENVIRONMENT "environment" CACHE STRING "Specifies the environment(s) to target.")
set(ENVIRONMENT_VALUES "web;node" CACHE INTERNAL "List of possible environments.")
set(ENVIRONMENT_VALUES "web;node;cf" CACHE INTERNAL "List of possible environments.")

set_property(CACHE ENVIRONMENT PROPERTY STRINGS ${ENVIRONMENT_VALUES})

Expand Down
9 changes: 9 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -564,3 +564,12 @@ node --version
# Copy versions.json
cp $TARGET/versions.json $SOURCE_DIR
)

[ -n "$DISABLE_BINDINGS" ] || [ "$ENVIRONMENT" != "cf" ] || (
# Ensure ENVIRONMENT_IS_WORKER == false
sed -i 's/"undefined"!=typeof WorkerGlobalScope/false/' $SOURCE_DIR/lib/vips.js
# Ensure ENVIRONMENT_IS_WEB == true (`Atomics.wait` cannot be used on Cloudflare workers)
sed -i 's/"object"==typeof window/true/' $SOURCE_DIR/lib/vips.js
# `navigator.hardwareConcurrency` cannot be used
sed -i -e 's/navigator.hardwareConcurrency/1/g' $SOURCE_DIR/lib/vips.js
)
36 changes: 36 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,23 @@ if ("web" IN_LIST ENVIRONMENT)
list(APPEND TARGETS ${PROJECT_NAME}-web ${PROJECT_NAME}-web-es6)
endif()

if ("cf" IN_LIST ENVIRONMENT)
add_executable(${PROJECT_NAME}-cf $<TARGET_OBJECTS:${PROJECT_NAME}>)

set_target_properties(${PROJECT_NAME}-cf
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}"
)

target_link_libraries(${PROJECT_NAME}-cf
PRIVATE
${VIPS_STATIC_LDFLAGS}
)

list(APPEND TARGETS ${PROJECT_NAME}-cf)
endif()


set(MAIN_COMPILE_OPTIONS
$<$<BOOL:${ENABLE_MODULES}>:-sMAIN_MODULE=2>
)
Expand Down Expand Up @@ -200,3 +217,22 @@ if ("web" IN_LIST ENVIRONMENT)
-sENVIRONMENT=web,deno,worker
)
endif()

if ("cf" IN_LIST ENVIRONMENT)
# Cloudflare workers:
# - disallows dynamic code execution and linking;
# - limits memory to 128 MB;
# - doesn't support node:worker_threads, nor the Web Workers API;
# The last point is a deal-breaker; wasm-vips cannot operate without it.
set(CF_LINK_OPTIONS
-sENVIRONMENT=web,worker
-sEXPORT_ES6
-sDYNAMIC_EXECUTION=0
-sINITIAL_MEMORY=64MB
)

target_link_options(${PROJECT_NAME}-cf
PUBLIC
${CF_LINK_OPTIONS}
)
endif()

0 comments on commit bab3b03

Please sign in to comment.